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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.794   ! albertel    4: # $Id: lonnet.pm,v 1.793 2006/10/16 19:39:57 albertel Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.1       albertel   30: package Apache::lonnet;
                     31: 
                     32: use strict;
1.8       www        33: use LWP::UserAgent();
1.15      www        34: use HTTP::Headers;
1.486     www        35: use HTTP::Date;
                     36: # use Date::Parse;
1.11      www        37: use vars 
1.599     albertel   38: qw(%perlvar %hostname %badServerCache %iphost %spareid %hostdom 
                     39:    %libserv %pr %prp $memcache %packagetab 
1.662     raeburn    40:    %courselogs %accesshash %userrolehash %domainrolehash $processmarker $dumpcount 
1.741     raeburn    41:    %coursedombuf %coursenumbuf %coursehombuf %coursedescrbuf %courseinstcodebuf %courseownerbuf %coursetypebuf
1.599     albertel   42:    %domaindescription %domain_auth_def %domain_auth_arg_def 
1.685     raeburn    43:    %domain_lang_def %domain_city %domain_longi %domain_lati %domain_primary
                     44:    $tmpdir $_64bit %env);
1.403     www        45: 
1.1       albertel   46: use IO::Socket;
1.31      www        47: use GDBM_File;
1.208     albertel   48: use HTML::LCParser;
1.637     raeburn    49: use HTML::Parser;
1.88      www        50: use Fcntl qw(:flock);
1.557     albertel   51: use Storable qw(lock_store lock_nstore lock_retrieve freeze thaw nfreeze);
1.539     albertel   52: use Time::HiRes qw( gettimeofday tv_interval );
1.599     albertel   53: use Cache::Memcached;
1.676     albertel   54: use Digest::MD5;
1.790     albertel   55: use Math::Random;
1.740     www        56: use lib '/home/httpd/lib/perl';
                     57: use LONCAPA;
                     58: use LONCAPA::Configuration;
1.676     albertel   59: 
1.195     www        60: my $readit;
1.550     foxr       61: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel   62: 
1.619     albertel   63: require Exporter;
                     64: 
                     65: our @ISA = qw (Exporter);
                     66: our @EXPORT = qw(%env);
                     67: 
1.449     matthew    68: =pod
                     69: 
                     70: =head1 Package Variables
                     71: 
                     72: These are largely undocumented, so if you decipher one please note it here.
                     73: 
                     74: =over 4
                     75: 
                     76: =item $processmarker
                     77: 
                     78: Contains the time this process was started and this servers host id.
                     79: 
                     80: =item $dumpcount
                     81: 
                     82: Counts the number of times a message log flush has been attempted (regardless
                     83: of success) by this process.  Used as part of the filename when messages are
                     84: delayed.
                     85: 
                     86: =back
                     87: 
                     88: =cut
                     89: 
                     90: 
1.1       albertel   91: # --------------------------------------------------------------------- Logging
1.729     www        92: {
                     93:     my $logid;
                     94:     sub instructor_log {
                     95: 	my ($hash_name,$storehash,$delflag,$uname,$udom)=@_;
                     96: 	$logid++;
                     97: 	my $id=time().'00000'.$$.'00000'.$logid;
                     98: 	return &Apache::lonnet::put('nohist_'.$hash_name,
1.730     www        99: 				    { $id => {
                    100: 					'exe_uname' => $env{'user.name'},
                    101: 					'exe_udom'  => $env{'user.domain'},
                    102: 					'exe_time'  => time(),
                    103: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    104: 					'delflag'   => $delflag,
                    105: 					'logentry'  => $storehash,
                    106: 					'uname'     => $uname,
                    107: 					'udom'      => $udom,
                    108: 				    }
                    109: 				  },
1.729     www       110: 				    $env{'course.'.$env{'request.course.id'}.'.domain'},
                    111: 				    $env{'course.'.$env{'request.course.id'}.'.num'}
                    112: 				    );
                    113:     }
                    114: }
1.1       albertel  115: 
1.163     harris41  116: sub logtouch {
                    117:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  118:     unless (-e "$execdir/logs/lonnet.log") {	
                    119: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  120: 	close $fh;
                    121:     }
                    122:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    123:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    124: }
                    125: 
1.1       albertel  126: sub logthis {
                    127:     my $message=shift;
                    128:     my $execdir=$perlvar{'lonDaemons'};
                    129:     my $now=time;
                    130:     my $local=localtime($now);
1.448     albertel  131:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
                    132: 	print $fh "$local ($$): $message\n";
                    133: 	close($fh);
                    134:     }
1.1       albertel  135:     return 1;
                    136: }
                    137: 
                    138: sub logperm {
                    139:     my $message=shift;
                    140:     my $execdir=$perlvar{'lonDaemons'};
                    141:     my $now=time;
                    142:     my $local=localtime($now);
1.448     albertel  143:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    144: 	print $fh "$now:$message:$local\n";
                    145: 	close($fh);
                    146:     }
1.1       albertel  147:     return 1;
                    148: }
                    149: 
                    150: # -------------------------------------------------- Non-critical communication
                    151: sub subreply {
                    152:     my ($cmd,$server)=@_;
1.704     albertel  153:     my $peerfile="$perlvar{'lonSockDir'}/".$hostname{$server};
1.549     foxr      154:     #
                    155:     #  With loncnew process trimming, there's a timing hole between lonc server
                    156:     #  process exit and the master server picking up the listen on the AF_UNIX
                    157:     #  socket.  In that time interval, a lock file will exist:
                    158: 
                    159:     my $lockfile=$peerfile.".lock";
                    160:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    161: 	sleep(1);
                    162:     }
                    163:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      164:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      165:     #
1.550     foxr      166:     #   We'll give the connection a few tries before abandoning it.  If
                    167:     #   connection is not possible, we'll con_lost back to the client.
                    168:     #   
                    169:     my $client;
                    170:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    171: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    172: 				      Type    => SOCK_STREAM,
                    173: 				      Timeout => 10);
                    174: 	if($client) {
                    175: 	    last;		# Connected!
                    176: 	}
                    177: 	sleep(1);		# Try again later if failed connection.
                    178:     }
                    179:     my $answer;
                    180:     if ($client) {
1.704     albertel  181: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      182: 	$answer=<$client>;
                    183: 	if (!$answer) { $answer="con_lost"; }
                    184: 	chomp($answer);
                    185:     } else {
                    186: 	$answer = 'con_lost';	# Failed connection.
                    187:     }
1.1       albertel  188:     return $answer;
                    189: }
                    190: 
                    191: sub reply {
                    192:     my ($cmd,$server)=@_;
1.205     www       193:     unless (defined($hostname{$server})) { return 'no_such_host'; }
1.1       albertel  194:     my $answer=subreply($cmd,$server);
1.65      www       195:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  196:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       197:                 " $cmd to $server returned $answer</font>");
                    198:     }
1.1       albertel  199:     return $answer;
                    200: }
                    201: 
                    202: # ----------------------------------------------------------- Send USR1 to lonc
                    203: 
                    204: sub reconlonc {
                    205:     my $peerfile=shift;
                    206:     &logthis("Trying to reconnect for $peerfile");
                    207:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  208:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  209: 	my $loncpid=<$fh>;
                    210:         chomp($loncpid);
                    211:         if (kill 0 => $loncpid) {
                    212: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    213:             kill USR1 => $loncpid;
                    214:             sleep 1;
                    215:             if (-e "$peerfile") { return; }
                    216:             &logthis("$peerfile still not there, give it another try");
                    217:             sleep 5;
                    218:             if (-e "$peerfile") { return; }
1.12      www       219:             &logthis(
1.672     albertel  220:   "<font color=\"blue\">WARNING: $peerfile still not there, giving up</font>");
1.1       albertel  221:         } else {
1.12      www       222: 	    &logthis(
1.672     albertel  223:                "<font color=\"blue\">WARNING:".
1.12      www       224:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  225:         }
                    226:     } else {
1.672     albertel  227:      &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  228:     }
                    229: }
                    230: 
                    231: # ------------------------------------------------------ Critical communication
1.12      www       232: 
1.1       albertel  233: sub critical {
                    234:     my ($cmd,$server)=@_;
1.89      www       235:     unless ($hostname{$server}) {
1.672     albertel  236:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       237:                " Critical message to unknown server ($server)</font>");
                    238:         return 'no_such_host';
                    239:     }
1.1       albertel  240:     my $answer=reply($cmd,$server);
                    241:     if ($answer eq 'con_lost') {
                    242: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  243: 	my $answer=reply($cmd,$server);
1.1       albertel  244:         if ($answer eq 'con_lost') {
                    245:             my $now=time;
                    246:             my $middlename=$cmd;
1.5       www       247:             $middlename=substr($middlename,0,16);
1.1       albertel  248:             $middlename=~s/\W//g;
                    249:             my $dfilename=
1.305     www       250:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    251:             $dumpcount++;
1.1       albertel  252:             {
1.448     albertel  253: 		my $dfh;
                    254: 		if (open($dfh,">$dfilename")) {
                    255: 		    print $dfh "$cmd\n"; 
                    256: 		    close($dfh);
                    257: 		}
1.1       albertel  258:             }
                    259:             sleep 2;
                    260:             my $wcmd='';
                    261:             {
1.448     albertel  262: 		my $dfh;
                    263: 		if (open($dfh,"<$dfilename")) {
                    264: 		    $wcmd=<$dfh>; 
                    265: 		    close($dfh);
                    266: 		}
1.1       albertel  267:             }
                    268:             chomp($wcmd);
1.7       www       269:             if ($wcmd eq $cmd) {
1.672     albertel  270: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       271:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  272:                 &logperm("D:$server:$cmd");
                    273: 	        return 'con_delayed';
                    274:             } else {
1.672     albertel  275:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       276:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  277:                 &logperm("F:$server:$cmd");
                    278:                 return 'con_failed';
                    279:             }
                    280:         }
                    281:     }
                    282:     return $answer;
1.405     albertel  283: }
                    284: 
1.755     albertel  285: # ------------------------------------------- check if return value is an error
                    286: 
                    287: sub error {
                    288:     my ($result) = @_;
1.756     albertel  289:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  290: 	if ($2 == 2) { return undef; }
                    291: 	return $1;
                    292:     }
                    293:     return undef;
                    294: }
                    295: 
1.783     albertel  296: sub convert_and_load_session_env {
                    297:     my ($lonidsdir,$handle)=@_;
                    298:     my @profile;
                    299:     {
                    300: 	open(my $idf,"$lonidsdir/$handle.id");
                    301: 	flock($idf,LOCK_SH);
                    302: 	@profile=<$idf>;
                    303: 	close($idf);
                    304:     }
                    305:     my %temp_env;
                    306:     foreach my $line (@profile) {
1.786     albertel  307: 	if ($line !~ m/=/) {
                    308: 	    return 0;
                    309: 	}
1.783     albertel  310: 	chomp($line);
                    311: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    312: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    313:     }
                    314:     unlink("$lonidsdir/$handle.id");
                    315:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    316: 	    0640)) {
                    317: 	%disk_env = %temp_env;
                    318: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    319: 	untie(%disk_env);
                    320:     }
1.786     albertel  321:     return 1;
1.783     albertel  322: }
                    323: 
1.374     www       324: # ------------------------------------------- Transfer profile into environment
1.780     albertel  325: my $env_loaded;
                    326: sub transfer_profile_to_env {
1.788     albertel  327:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    328:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       329: 
1.720     albertel  330:     if (!defined($lonidsdir)) {
                    331: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    332:     }
                    333:     if (!defined($handle)) {
                    334:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    335:     }
                    336: 
1.786     albertel  337:     my $convert;
                    338:     {
                    339:     	open(my $idf,"$lonidsdir/$handle.id");
                    340: 	flock($idf,LOCK_SH);
                    341: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    342: 		&GDBM_READER(),0640)) {
                    343: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    344: 	    untie(%disk_env);
                    345: 	} else {
                    346: 	    $convert = 1;
                    347: 	}
                    348:     }
                    349:     if ($convert) {
                    350: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    351: 	    &logthis("Failed to load session, or convert session.");
                    352: 	}
1.374     www       353:     }
1.783     albertel  354: 
1.786     albertel  355:     my %remove;
1.783     albertel  356:     while ( my $envname = each(%env) ) {
1.433     matthew   357:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    358:             if ($time < time-300) {
1.783     albertel  359:                 $remove{$key}++;
1.433     matthew   360:             }
                    361:         }
                    362:     }
1.783     albertel  363: 
1.619     albertel  364:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  365:     $env_loaded=1;
1.783     albertel  366:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   367:         &delenv($expired_key);
1.374     www       368:     }
1.1       albertel  369: }
                    370: 
1.5       www       371: # ---------------------------------------------------------- Append Environment
                    372: 
                    373: sub appenv {
1.6       www       374:     my %newenv=@_;
1.692     albertel  375:     foreach my $key (keys(%newenv)) {
                    376: 	if (($newenv{$key}=~/^user\.role/) || ($newenv{$key}=~/^user\.priv/)) {
1.672     albertel  377:             &logthis("<font color=\"blue\">WARNING: ".
1.692     albertel  378:                 "Attempt to modify environment ".$key." to ".$newenv{$key}
1.151     www       379:                 .'</font>');
1.692     albertel  380: 	    delete($newenv{$key});
1.35      www       381:         } else {
1.692     albertel  382:             $env{$key}=$newenv{$key};
1.35      www       383:         }
1.191     harris41  384:     }
1.783     albertel  385:     if (tie(my %disk_env,'GDBM_File',$env{'user.environment'},&GDBM_WRITER(),
                    386: 	    0640)) {
                    387: 	while (my ($key,$value) = each(%newenv)) {
                    388: 	    $disk_env{$key} = $value;
1.448     albertel  389: 	}
1.783     albertel  390: 	untie(%disk_env);
1.56      www       391:     }
                    392:     return 'ok';
                    393: }
                    394: # ----------------------------------------------------- Delete from Environment
                    395: 
                    396: sub delenv {
                    397:     my $delthis=shift;
                    398:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672     albertel  399:         &logthis("<font color=\"blue\">WARNING: ".
1.56      www       400:                 "Attempt to delete from environment ".$delthis);
                    401:         return 'error';
                    402:     }
1.783     albertel  403:     if (tie(my %disk_env,'GDBM_File',$env{'user.environment'},&GDBM_WRITER(),
                    404: 	    0640)) {
                    405: 	foreach my $key (keys(%disk_env)) {
                    406: 	    if ($key=~/^$delthis/) { 
1.619     albertel  407:                 delete($env{$key});
1.783     albertel  408:                 delete($disk_env{$key});
1.473     matthew   409:             }
1.448     albertel  410: 	}
1.783     albertel  411: 	untie(%disk_env);
1.5       www       412:     }
                    413:     return 'ok';
1.369     albertel  414: }
                    415: 
1.790     albertel  416: =pod
                    417: 
                    418: =item * get_env_multiple($name) 
                    419: 
                    420: gets $name from the %env hash, it seemlessly handles the cases where multiple
                    421: values may be defined and end up as an array ref.
                    422: 
                    423: returns an array of values
                    424: 
                    425: =cut
                    426: 
                    427: sub get_env_multiple {
                    428:     my ($name) = @_;
                    429:     my @values;
                    430:     if (defined($env{$name})) {
                    431:         # exists is it an array
                    432:         if (ref($env{$name})) {
                    433:             @values=@{ $env{$name} };
                    434:         } else {
                    435:             $values[0]=$env{$name};
                    436:         }
                    437:     }
                    438:     return(@values);
                    439: }
                    440: 
1.369     albertel  441: # ------------------------------------------ Find out current server userload
                    442: # there is a copy in lond
                    443: sub userload {
                    444:     my $numusers=0;
                    445:     {
                    446: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    447: 	my $filename;
                    448: 	my $curtime=time;
                    449: 	while ($filename=readdir(LONIDS)) {
                    450: 	    if ($filename eq '.' || $filename eq '..') {next;}
1.404     albertel  451: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  452: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  453: 	}
                    454: 	closedir(LONIDS);
                    455:     }
                    456:     my $userloadpercent=0;
                    457:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    458:     if ($maxuserload) {
1.371     albertel  459: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  460:     }
1.372     albertel  461:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  462:     return $userloadpercent;
1.283     www       463: }
                    464: 
                    465: # ------------------------------------------ Fight off request when overloaded
                    466: 
                    467: sub overloaderror {
                    468:     my ($r,$checkserver)=@_;
                    469:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
                    470:     my $loadavg;
                    471:     if ($checkserver eq $perlvar{'lonHostID'}) {
1.448     albertel  472:        open(my $loadfile,'/proc/loadavg');
1.283     www       473:        $loadavg=<$loadfile>;
                    474:        $loadavg =~ s/\s.*//g;
1.285     matthew   475:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448     albertel  476:        close($loadfile);
1.283     www       477:     } else {
                    478:        $loadavg=&reply('load',$checkserver);
                    479:     }
1.285     matthew   480:     my $overload=$loadavg-100;
1.283     www       481:     if ($overload>0) {
1.285     matthew   482: 	$r->err_headers_out->{'Retry-After'}=$overload;
1.283     www       483:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554     www       484:         return 413;
1.283     www       485:     }    
                    486:     return '';
1.5       www       487: }
1.1       albertel  488: 
                    489: # ------------------------------ Find server with least workload from spare.tab
1.11      www       490: 
1.1       albertel  491: sub spareserver {
1.670     albertel  492:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.784     albertel  493:     my $spare_server;
1.370     albertel  494:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  495:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    496:                                                      :  $userloadpercent;
                    497:     
                    498:     foreach my $try_server (@{ $spareid{'primary'} }) {
                    499: 	($spare_server, $lowest_load) =
                    500: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
                    501:     }
                    502: 
                    503:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    504: 
                    505:     if (!$found_server) {
                    506: 	foreach my $try_server (@{ $spareid{'default'} }) {
                    507: 	    ($spare_server, $lowest_load) =
                    508: 		&compare_server_load($try_server, $spare_server, $lowest_load);
                    509: 	}
                    510:     }
                    511: 
                    512:     if (!$want_server_name) {
                    513: 	$spare_server="http://$hostname{$spare_server}";
                    514:     }
                    515:     return $spare_server;
                    516: }
                    517: 
                    518: sub compare_server_load {
                    519:     my ($try_server, $spare_server, $lowest_load) = @_;
                    520: 
                    521:     my $loadans     = &reply('load',    $try_server);
                    522:     my $userloadans = &reply('userload',$try_server);
                    523: 
                    524:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
                    525: 	next; #didn't get a number from the server
                    526:     }
                    527: 
                    528:     my $load;
                    529:     if ($loadans =~ /\d/) {
                    530: 	if ($userloadans =~ /\d/) {
                    531: 	    #both are numbers, pick the bigger one
                    532: 	    $load = ($loadans > $userloadans) ? $loadans 
                    533: 		                              : $userloadans;
1.411     albertel  534: 	} else {
1.784     albertel  535: 	    $load = $loadans;
1.411     albertel  536: 	}
1.784     albertel  537:     } else {
                    538: 	$load = $userloadans;
                    539:     }
                    540: 
                    541:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    542: 	$spare_server = $try_server;
                    543: 	$lowest_load  = $load;
1.370     albertel  544:     }
1.784     albertel  545:     return ($spare_server,$lowest_load);
1.202     matthew   546: }
                    547: # --------------------------------------------- Try to change a user's password
                    548: 
                    549: sub changepass {
                    550:     my ($uname,$udom,$currentpass,$newpass,$server)=@_;
                    551:     $currentpass = &escape($currentpass);
                    552:     $newpass     = &escape($newpass);
                    553:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass",
                    554: 		       $server);
                    555:     if (! $answer) {
                    556: 	&logthis("No reply on password change request to $server ".
                    557: 		 "by $uname in domain $udom.");
                    558:     } elsif ($answer =~ "^ok") {
                    559:         &logthis("$uname in $udom successfully changed their password ".
                    560: 		 "on $server.");
                    561:     } elsif ($answer =~ "^pwchange_failure") {
                    562: 	&logthis("$uname in $udom was unable to change their password ".
                    563: 		 "on $server.  The action was blocked by either lcpasswd ".
                    564: 		 "or pwchange");
                    565:     } elsif ($answer =~ "^non_authorized") {
                    566:         &logthis("$uname in $udom did not get their password correct when ".
                    567: 		 "attempting to change it on $server.");
                    568:     } elsif ($answer =~ "^auth_mode_error") {
                    569:         &logthis("$uname in $udom attempted to change their password despite ".
                    570: 		 "not being locally or internally authenticated on $server.");
                    571:     } elsif ($answer =~ "^unknown_user") {
                    572:         &logthis("$uname in $udom attempted to change their password ".
                    573: 		 "on $server but were unable to because $server is not ".
                    574: 		 "their home server.");
                    575:     } elsif ($answer =~ "^refused") {
                    576: 	&logthis("$server refused to change $uname in $udom password because ".
                    577: 		 "it was sent an unencrypted request to change the password.");
                    578:     }
                    579:     return $answer;
1.1       albertel  580: }
                    581: 
1.169     harris41  582: # ----------------------- Try to determine user's current authentication scheme
                    583: 
                    584: sub queryauthenticate {
                    585:     my ($uname,$udom)=@_;
1.456     albertel  586:     my $uhome=&homeserver($uname,$udom);
                    587:     if (!$uhome) {
                    588: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                    589: 	return 'no_host';
                    590:     }
                    591:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                    592:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                    593: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41  594:     }
1.456     albertel  595:     return $answer;
1.169     harris41  596: }
                    597: 
1.1       albertel  598: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       599: 
1.1       albertel  600: sub authenticate {
                    601:     my ($uname,$upass,$udom)=@_;
1.12      www       602:     $upass=escape($upass);
1.199     www       603:     $uname=~s/\W//g;
1.471     albertel  604:     my $uhome=&homeserver($uname,$udom);
                    605:     if (!$uhome) {
                    606: 	&logthis("User $uname at $udom is unknown in authenticate");
                    607: 	return 'no_host';
1.1       albertel  608:     }
1.471     albertel  609:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
                    610:     if ($answer eq 'authorized') {
                    611: 	&logthis("User $uname at $udom authorized by $uhome"); 
                    612: 	return $uhome; 
                    613:     }
                    614:     if ($answer eq 'non_authorized') {
                    615: 	&logthis("User $uname at $udom rejected by $uhome");
                    616: 	return 'no_host'; 
1.9       www       617:     }
1.471     albertel  618:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel  619:     return 'no_host';
                    620: }
                    621: 
                    622: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www       623: 
1.599     albertel  624: my %homecache;
1.1       albertel  625: sub homeserver {
1.230     stredwic  626:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel  627:     my $index="$uname:$udom";
1.426     albertel  628: 
1.599     albertel  629:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.1       albertel  630:     my $tryserver;
                    631:     foreach $tryserver (keys %libserv) {
1.230     stredwic  632:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic  633: 		 exists($badServerCache{$tryserver}));
1.1       albertel  634: 	if ($hostdom{$tryserver} eq $udom) {
                    635:            my $answer=reply("home:$udom:$uname",$tryserver);
                    636:            if ($answer eq 'found') { 
1.599     albertel  637: 	       return $homecache{$index}=$tryserver;
1.231     stredwic  638:            } elsif ($answer eq 'no_host') {
                    639: 	       $badServerCache{$tryserver}=1;
1.221     matthew   640:            }
1.1       albertel  641:        }
                    642:     }    
                    643:     return 'no_host';
1.70      www       644: }
                    645: 
                    646: # ------------------------------------- Find the usernames behind a list of IDs
                    647: 
                    648: sub idget {
                    649:     my ($udom,@ids)=@_;
                    650:     my %returnhash=();
                    651:     
                    652:     my $tryserver;
                    653:     foreach $tryserver (keys %libserv) {
                    654:        if ($hostdom{$tryserver} eq $udom) {
                    655: 	  my $idlist=join('&',@ids);
                    656:           $idlist=~tr/A-Z/a-z/; 
                    657: 	  my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                    658:           my @answer=();
1.76      www       659:           if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1.70      www       660: 	      @answer=split(/\&/,$reply);
                    661:           }                    ;
                    662:           my $i;
                    663:           for ($i=0;$i<=$#ids;$i++) {
                    664:               if ($answer[$i]) {
                    665: 		  $returnhash{$ids[$i]}=$answer[$i];
                    666:               } 
                    667:           }
                    668:        }
                    669:     }    
                    670:     return %returnhash;
                    671: }
                    672: 
                    673: # ------------------------------------- Find the IDs behind a list of usernames
                    674: 
                    675: sub idrget {
                    676:     my ($udom,@unames)=@_;
                    677:     my %returnhash=();
1.191     harris41  678:     foreach (@unames) {
1.70      www       679:         $returnhash{$_}=(&userenvironment($udom,$_,'id'))[1];
1.191     harris41  680:     }
1.70      www       681:     return %returnhash;
                    682: }
                    683: 
                    684: # ------------------------------- Store away a list of names and associated IDs
                    685: 
                    686: sub idput {
                    687:     my ($udom,%ids)=@_;
                    688:     my %servers=();
1.191     harris41  689:     foreach (keys %ids) {
1.487     albertel  690: 	&cput('environment',{'id'=>$ids{$_}},$udom,$_);
1.70      www       691:         my $uhom=&homeserver($_,$udom);
                    692:         if ($uhom ne 'no_host') {
                    693:             my $id=&escape($ids{$_});
                    694:             $id=~tr/A-Z/a-z/;
                    695:             my $unam=&escape($_);
                    696: 	    if ($servers{$uhom}) {
                    697: 		$servers{$uhom}.='&'.$id.'='.$unam;
                    698:             } else {
                    699:                 $servers{$uhom}=$id.'='.$unam;
                    700:             }
                    701:         }
1.191     harris41  702:     }
                    703:     foreach (keys %servers) {
1.70      www       704:         &critical('idput:'.$udom.':'.$servers{$_},$_);
1.191     harris41  705:     }
1.344     www       706: }
                    707: 
                    708: # --------------------------------------------------- Assign a key to a student
                    709: 
                    710: sub assign_access_key {
1.364     www       711: #
                    712: # a valid key looks like uname:udom#comments
                    713: # comments are being appended
                    714: #
1.498     www       715:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                    716:     $kdom=
1.620     albertel  717:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www       718:     $knum=
1.620     albertel  719:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www       720:     $cdom=
1.620     albertel  721:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       722:     $cnum=
1.620     albertel  723:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    724:     $udom=$env{'user.name'} unless (defined($udom));
                    725:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www       726:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www       727:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel  728:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www       729:                                                   # assigned to this person
                    730:                                                   # - this should not happen,
1.345     www       731:                                                   # unless something went wrong
                    732:                                                   # the first time around
                    733: # ready to assign
1.364     www       734:         $logentry=$1.'; '.$logentry;
1.496     www       735:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www       736:                                                  $kdom,$knum) eq 'ok') {
1.345     www       737: # key now belongs to user
1.346     www       738: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www       739:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
                    740:                 &appenv('environment.'.$envkey => $ckey);
                    741:                 return 'ok';
                    742:             } else {
                    743:                 return 
                    744:   'error: Count not permanently assign key, will need to be re-entered later.';
                    745: 	    }
                    746:         } else {
                    747:             return 'error: Could not assign key, try again later.';
                    748:         }
1.364     www       749:     } elsif (!$existing{$ckey}) {
1.345     www       750: # the key does not exist
                    751: 	return 'error: The key does not exist';
                    752:     } else {
                    753: # the key is somebody else's
                    754: 	return 'error: The key is already in use';
                    755:     }
1.344     www       756: }
                    757: 
1.364     www       758: # ------------------------------------------ put an additional comment on a key
                    759: 
                    760: sub comment_access_key {
                    761: #
                    762: # a valid key looks like uname:udom#comments
                    763: # comments are being appended
                    764: #
                    765:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                    766:     $cdom=
1.620     albertel  767:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www       768:     $cnum=
1.620     albertel  769:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www       770:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                    771:     if ($existing{$ckey}) {
                    772:         $existing{$ckey}.='; '.$logentry;
                    773: # ready to assign
1.367     www       774:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www       775:                                                  $cdom,$cnum) eq 'ok') {
                    776: 	    return 'ok';
                    777:         } else {
                    778: 	    return 'error: Count not store comment.';
                    779:         }
                    780:     } else {
                    781: # the key does not exist
                    782: 	return 'error: The key does not exist';
                    783:     }
                    784: }
                    785: 
1.344     www       786: # ------------------------------------------------------ Generate a set of keys
                    787: 
                    788: sub generate_access_keys {
1.364     www       789:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www       790:     $cdom=
1.620     albertel  791:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       792:     $cnum=
1.620     albertel  793:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www       794:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www       795:     unless (($cdom) && ($cnum)) { return 0; }
                    796:     if ($number>10000) { return 0; }
                    797:     sleep(2); # make sure don't get same seed twice
                    798:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                    799:     my $total=0;
                    800:     for (my $i=1;$i<=$number;$i++) {
                    801:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                    802:                   sprintf("%lx",int(100000*rand)).'-'.
                    803:                   sprintf("%lx",int(100000*rand));
                    804:        $newkey=~s/1/g/g; # folks mix up 1 and l
                    805:        $newkey=~s/0/h/g; # and also 0 and O
                    806:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                    807:        if ($existing{$newkey}) {
                    808:            $i--;
                    809:        } else {
1.364     www       810: 	  if (&put('accesskeys',
                    811:               { $newkey => '# generated '.localtime().
1.620     albertel  812:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www       813:                            '; '.$logentry },
                    814: 		   $cdom,$cnum) eq 'ok') {
1.344     www       815:               $total++;
                    816: 	  }
                    817:        }
                    818:     }
1.620     albertel  819:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www       820:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                    821:     return $total;
                    822: }
                    823: 
                    824: # ------------------------------------------------------- Validate an accesskey
                    825: 
                    826: sub validate_access_key {
                    827:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                    828:     $cdom=
1.620     albertel  829:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       830:     $cnum=
1.620     albertel  831:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    832:     $udom=$env{'user.domain'} unless (defined($udom));
                    833:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www       834:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel  835:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www       836: }
                    837: 
                    838: # ------------------------------------- Find the section of student in a course
1.652     albertel  839: sub devalidate_getsection_cache {
                    840:     my ($udom,$unam,$courseid)=@_;
                    841:     $courseid=~s/\_/\//g;
                    842:     $courseid=~s/^(\w)/\/$1/;
                    843:     my $hashid="$udom:$unam:$courseid";
                    844:     &devalidate_cache_new('getsection',$hashid);
                    845: }
1.298     matthew   846: 
                    847: sub getsection {
                    848:     my ($udom,$unam,$courseid)=@_;
1.599     albertel  849:     my $cachetime=1800;
1.298     matthew   850:     $courseid=~s/\_/\//g;
                    851:     $courseid=~s/^(\w)/\/$1/;
1.551     albertel  852: 
                    853:     my $hashid="$udom:$unam:$courseid";
1.599     albertel  854:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel  855:     if (defined($cached)) { return $result; }
                    856: 
1.298     matthew   857:     my %Pending; 
                    858:     my %Expired;
                    859:     #
                    860:     # Each role can either have not started yet (pending), be active, 
                    861:     #    or have expired.
                    862:     #
                    863:     # If there is an active role, we are done.
                    864:     #
                    865:     # If there is more than one role which has not started yet, 
                    866:     #     choose the one which will start sooner
                    867:     # If there is one role which has not started yet, return it.
                    868:     #
                    869:     # If there is more than one expired role, choose the one which ended last.
                    870:     # If there is a role which has expired, return it.
                    871:     #
                    872:     foreach (split(/\&/,&reply('dump:'.$udom.':'.$unam.':roles',
                    873:                         &homeserver($unam,$udom)))) {
                    874:         my ($key,$value)=split(/\=/,$_);
                    875:         $key=&unescape($key);
1.479     albertel  876:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew   877:         my $section=$1;
                    878:         if ($key eq $courseid.'_st') { $section=''; }
                    879:         my ($dummy,$end,$start)=split(/\_/,&unescape($value));
                    880:         my $now=time;
1.548     albertel  881:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew   882:             $Expired{$end}=$section;
                    883:             next;
                    884:         }
1.548     albertel  885:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew   886:             $Pending{$start}=$section;
                    887:             next;
                    888:         }
1.599     albertel  889:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew   890:     }
                    891:     #
                    892:     # Presumedly there will be few matching roles from the above
                    893:     # loop and the sorting time will be negligible.
                    894:     if (scalar(keys(%Pending))) {
                    895:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel  896:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew   897:     } 
                    898:     if (scalar(keys(%Expired))) {
                    899:         my @sorted = sort {$a <=> $b} keys(%Expired);
                    900:         my $time = pop(@sorted);
1.599     albertel  901:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew   902:     }
1.599     albertel  903:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew   904: }
1.70      www       905: 
1.599     albertel  906: sub save_cache {
                    907:     &purge_remembered();
1.722     albertel  908:     #&Apache::loncommon::validate_page();
1.620     albertel  909:     undef(%env);
1.780     albertel  910:     undef($env_loaded);
1.599     albertel  911: }
1.452     albertel  912: 
1.599     albertel  913: my $to_remember=-1;
                    914: my %remembered;
                    915: my %accessed;
                    916: my $kicks=0;
                    917: my $hits=0;
                    918: sub devalidate_cache_new {
                    919:     my ($name,$id,$debug) = @_;
                    920:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
                    921:     $id=&escape($name.':'.$id);
                    922:     $memcache->delete($id);
                    923:     delete($remembered{$id});
                    924:     delete($accessed{$id});
                    925: }
                    926: 
                    927: sub is_cached_new {
                    928:     my ($name,$id,$debug) = @_;
                    929:     $id=&escape($name.':'.$id);
                    930:     if (exists($remembered{$id})) {
                    931: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                    932: 	$accessed{$id}=[&gettimeofday()];
                    933: 	$hits++;
                    934: 	return ($remembered{$id},1);
                    935:     }
                    936:     my $value = $memcache->get($id);
                    937:     if (!(defined($value))) {
                    938: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel  939: 	return (undef,undef);
1.416     albertel  940:     }
1.599     albertel  941:     if ($value eq '__undef__') {
                    942: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                    943: 	$value=undef;
                    944:     }
                    945:     &make_room($id,$value,$debug);
                    946:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                    947:     return ($value,1);
                    948: }
                    949: 
                    950: sub do_cache_new {
                    951:     my ($name,$id,$value,$time,$debug) = @_;
                    952:     $id=&escape($name.':'.$id);
                    953:     my $setvalue=$value;
                    954:     if (!defined($setvalue)) {
                    955: 	$setvalue='__undef__';
                    956:     }
1.623     albertel  957:     if (!defined($time) ) {
                    958: 	$time=600;
                    959:     }
1.599     albertel  960:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.600     albertel  961:     $memcache->set($id,$setvalue,$time);
                    962:     # need to make a copy of $value
                    963:     #&make_room($id,$value,$debug);
1.599     albertel  964:     return $value;
                    965: }
                    966: 
                    967: sub make_room {
                    968:     my ($id,$value,$debug)=@_;
                    969:     $remembered{$id}=$value;
                    970:     if ($to_remember<0) { return; }
                    971:     $accessed{$id}=[&gettimeofday()];
                    972:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                    973:     my $to_kick;
                    974:     my $max_time=0;
                    975:     foreach my $other (keys(%accessed)) {
                    976: 	if (&tv_interval($accessed{$other}) > $max_time) {
                    977: 	    $to_kick=$other;
                    978: 	    $max_time=&tv_interval($accessed{$other});
                    979: 	}
                    980:     }
                    981:     delete($remembered{$to_kick});
                    982:     delete($accessed{$to_kick});
                    983:     $kicks++;
                    984:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel  985:     return;
                    986: }
                    987: 
1.599     albertel  988: sub purge_remembered {
1.604     albertel  989:     #&logthis("Tossing ".scalar(keys(%remembered)));
                    990:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel  991:     undef(%remembered);
                    992:     undef(%accessed);
1.428     albertel  993: }
1.70      www       994: # ------------------------------------- Read an entry from a user's environment
                    995: 
                    996: sub userenvironment {
                    997:     my ($udom,$unam,@what)=@_;
                    998:     my %returnhash=();
                    999:     my @answer=split(/\&/,
                   1000:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
                   1001:                       &homeserver($unam,$udom)));
                   1002:     my $i;
                   1003:     for ($i=0;$i<=$#what;$i++) {
                   1004: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                   1005:     }
                   1006:     return %returnhash;
1.1       albertel 1007: }
                   1008: 
1.617     albertel 1009: # ---------------------------------------------------------- Get a studentphoto
                   1010: sub studentphoto {
                   1011:     my ($udom,$unam,$ext) = @_;
                   1012:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1013:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1014:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1015:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1016:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1017:             } else {
                   1018:                 my ($result,$perm_reqd)=
1.707     albertel 1019: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1020:                 if ($result eq 'ok') {
                   1021:                     if (!($perm_reqd eq 'yes')) {
                   1022:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1023:                     }
                   1024:                 }
                   1025:             }
                   1026:         }
                   1027:     } else {
                   1028:         my ($result,$perm_reqd) = 
1.707     albertel 1029: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1030:         if ($result eq 'ok') {
                   1031:             if (!($perm_reqd eq 'yes')) {
                   1032:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1033:             }
                   1034:         }
                   1035:     }
                   1036:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1037: }
                   1038: 
                   1039: sub retrievestudentphoto {
                   1040:     my ($udom,$unam,$ext,$type) = @_;
                   1041:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1042:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1043:     if ($ret eq 'ok') {
                   1044:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1045:         if ($type eq 'thumbnail') {
                   1046:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1047:         }
                   1048:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1049:         return $tokenurl;
                   1050:     } else {
                   1051:         if ($type eq 'thumbnail') {
                   1052:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1053:         } else { 
                   1054:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1055:         }
1.617     albertel 1056:     }
                   1057: }
                   1058: 
1.263     www      1059: # -------------------------------------------------------------------- New chat
                   1060: 
                   1061: sub chatsend {
1.724     raeburn  1062:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1063:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1064:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1065:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1066:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1067: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1068: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1069: }
                   1070: 
                   1071: # ------------------------------------------ Find current version of a resource
                   1072: 
                   1073: sub getversion {
                   1074:     my $fname=&clutter(shift);
                   1075:     unless ($fname=~/^\/res\//) { return -1; }
                   1076:     return &currentversion(&filelocation('',$fname));
                   1077: }
                   1078: 
                   1079: sub currentversion {
                   1080:     my $fname=shift;
1.599     albertel 1081:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1082:     if (defined($cached)) { return $result; }
1.292     www      1083:     my $author=$fname;
                   1084:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1085:     my ($udom,$uname)=split(/\//,$author);
                   1086:     my $home=homeserver($uname,$udom);
                   1087:     if ($home eq 'no_host') { 
                   1088:         return -1; 
                   1089:     }
                   1090:     my $answer=reply("currentversion:$fname",$home);
                   1091:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1092: 	return -1;
                   1093:     }
1.599     albertel 1094:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1095: }
                   1096: 
1.1       albertel 1097: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1098: 
1.1       albertel 1099: sub subscribe {
                   1100:     my $fname=shift;
1.761     raeburn  1101:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1102:     $fname=~s/[\n\r]//g;
1.1       albertel 1103:     my $author=$fname;
                   1104:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1105:     my ($udom,$uname)=split(/\//,$author);
                   1106:     my $home=homeserver($uname,$udom);
1.335     albertel 1107:     if ($home eq 'no_host') {
                   1108:         return 'not_found';
1.1       albertel 1109:     }
                   1110:     my $answer=reply("sub:$fname",$home);
1.64      www      1111:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1112: 	$answer.=' by '.$home;
                   1113:     }
1.1       albertel 1114:     return $answer;
                   1115: }
                   1116:     
1.8       www      1117: # -------------------------------------------------------------- Replicate file
                   1118: 
                   1119: sub repcopy {
                   1120:     my $filename=shift;
1.23      www      1121:     $filename=~s/\/+/\//g;
1.607     raeburn  1122:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1123:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1124:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1125: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1126: 	return &repcopy_userfile($filename);
                   1127:     }
1.532     albertel 1128:     $filename=~s/[\n\r]//g;
1.8       www      1129:     my $transname="$filename.in.transfer";
1.607     raeburn  1130:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1131:     my $remoteurl=subscribe($filename);
1.64      www      1132:     if ($remoteurl =~ /^con_lost by/) {
                   1133: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1134:            return 'unavailable';
1.8       www      1135:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1136: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1137: 	   return 'not_found';
1.64      www      1138:     } elsif ($remoteurl =~ /^rejected by/) {
                   1139: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1140:            return 'forbidden';
1.20      www      1141:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1142:            return 'ok';
1.8       www      1143:     } else {
1.290     www      1144:         my $author=$filename;
                   1145:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1146:         my ($udom,$uname)=split(/\//,$author);
                   1147:         my $home=homeserver($uname,$udom);
                   1148:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1149:            my @parts=split(/\//,$filename);
                   1150:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1151:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1152:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1153: 	       return 'bad_request';
1.8       www      1154:            }
                   1155:            my $count;
                   1156:            for ($count=5;$count<$#parts;$count++) {
                   1157:                $path.="/$parts[$count]";
                   1158:                if ((-e $path)!=1) {
                   1159: 		   mkdir($path,0777);
                   1160:                }
                   1161:            }
                   1162:            my $ua=new LWP::UserAgent;
                   1163:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1164:            my $response=$ua->request($request,$transname);
                   1165:            if ($response->is_error()) {
                   1166: 	       unlink($transname);
                   1167:                my $message=$response->status_line;
1.672     albertel 1168:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      1169:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1170:                return 'unavailable';
1.8       www      1171:            } else {
1.16      www      1172: 	       if ($remoteurl!~/\.meta$/) {
                   1173:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1174:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1175:                   if ($mresponse->is_error()) {
                   1176: 		      unlink($filename.'.meta');
                   1177:                       &logthis(
1.672     albertel 1178:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      1179:                   }
                   1180: 	       }
1.8       www      1181:                rename($transname,$filename);
1.607     raeburn  1182:                return 'ok';
1.8       www      1183:            }
1.290     www      1184:        }
1.8       www      1185:     }
1.330     www      1186: }
                   1187: 
                   1188: # ------------------------------------------------ Get server side include body
                   1189: sub ssi_body {
1.381     albertel 1190:     my ($filelink,%form)=@_;
1.606     matthew  1191:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1192:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1193:     }
1.330     www      1194:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
1.381     albertel 1195:                                      &ssi($filelink,%form));
1.778     albertel 1196:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1197:     $output=~s/^.*?\<body[^\>]*\>//si;
                   1198:     $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
1.330     www      1199:     return $output;
1.8       www      1200: }
                   1201: 
1.15      www      1202: # --------------------------------------------------------- Server Side Include
                   1203: 
1.782     albertel 1204: sub absolute_url {
                   1205:     my ($host_name) = @_;
                   1206:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   1207:     if ($host_name eq '') {
                   1208: 	$host_name = $ENV{'SERVER_NAME'};
                   1209:     }
                   1210:     return $protocol.$host_name;
                   1211: }
                   1212: 
1.15      www      1213: sub ssi {
                   1214: 
1.23      www      1215:     my ($fn,%form)=@_;
1.15      www      1216: 
                   1217:     my $ua=new LWP::UserAgent;
1.23      www      1218:     
                   1219:     my $request;
1.711     albertel 1220: 
                   1221:     $form{'no_update_last_known'}=1;
                   1222: 
1.23      www      1223:     if (%form) {
1.782     albertel 1224:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.201     albertel 1225:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www      1226:     } else {
1.782     albertel 1227:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      1228:     }
                   1229: 
1.15      www      1230:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1231:     my $response=$ua->request($request);
                   1232: 
1.324     www      1233:     return $response->content;
                   1234: }
                   1235: 
                   1236: sub externalssi {
                   1237:     my ($url)=@_;
                   1238:     my $ua=new LWP::UserAgent;
                   1239:     my $request=new HTTP::Request('GET',$url);
                   1240:     my $response=$ua->request($request);
1.15      www      1241:     return $response->content;
                   1242: }
1.254     www      1243: 
1.492     albertel 1244: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1245: 
                   1246: sub allowuploaded {
                   1247:     my ($srcurl,$url)=@_;
                   1248:     $url=&clutter(&declutter($url));
                   1249:     my $dir=$url;
                   1250:     $dir=~s/\/[^\/]+$//;
                   1251:     my %httpref=();
                   1252:     my $httpurl=&hreflocation('',$url);
                   1253:     $httpref{'httpref.'.$httpurl}=$srcurl;
                   1254:     &Apache::lonnet::appenv(%httpref);
1.254     www      1255: }
1.477     raeburn  1256: 
1.478     albertel 1257: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 1258: # input: action, courseID, current domain, intended
1.637     raeburn  1259: #        path to file, source of file, instruction to parse file for objects,
                   1260: #        ref to hash for embedded objects,
                   1261: #        ref to hash for codebase of java objects.
                   1262: #
1.485     raeburn  1263: # output: url to file (if action was uploaddoc), 
                   1264: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  1265: #
1.478     albertel 1266: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   1267: # course.
1.477     raeburn  1268: #
1.478     albertel 1269: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1270: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   1271: #          course's home server.
1.477     raeburn  1272: #
1.478     albertel 1273: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   1274: #          be copied from $source (current location) to 
                   1275: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1276: #         and will then be copied to
                   1277: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   1278: #         course's home server.
1.485     raeburn  1279: #
1.481     raeburn  1280: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 1281: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  1282: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1283: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   1284: #         in course's home server.
1.637     raeburn  1285: #
1.477     raeburn  1286: 
                   1287: sub process_coursefile {
1.638     albertel 1288:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  1289:     my $fetchresult;
1.638     albertel 1290:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  1291:     if ($action eq 'propagate') {
1.638     albertel 1292:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1293: 			     $home);
1.481     raeburn  1294:     } else {
1.477     raeburn  1295:         my $fpath = '';
                   1296:         my $fname = $file;
1.478     albertel 1297:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  1298:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  1299:         my $filepath = &build_filepath($fpath);
1.481     raeburn  1300:         if ($action eq 'copy') {
                   1301:             if ($source eq '') {
                   1302:                 $fetchresult = 'no source file';
                   1303:                 return $fetchresult;
                   1304:             } else {
                   1305:                 my $destination = $filepath.'/'.$fname;
                   1306:                 rename($source,$destination);
                   1307:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1308:                                  $home);
1.481     raeburn  1309:             }
                   1310:         } elsif ($action eq 'uploaddoc') {
                   1311:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 1312:             print $fh $env{'form.'.$source};
1.481     raeburn  1313:             close($fh);
1.637     raeburn  1314:             if ($parser eq 'parse') {
                   1315:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
                   1316:                 unless ($parse_result eq 'ok') {
                   1317:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   1318:                 }
                   1319:             }
1.477     raeburn  1320:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1321:                                  $home);
1.481     raeburn  1322:             if ($fetchresult eq 'ok') {
                   1323:                 return '/uploaded/'.$fpath.'/'.$fname;
                   1324:             } else {
                   1325:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1326:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  1327:                 return '/adm/notfound.html';
                   1328:             }
1.477     raeburn  1329:         }
                   1330:     }
1.485     raeburn  1331:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  1332:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1333:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  1334:     }
                   1335:     return $fetchresult;
                   1336: }
                   1337: 
1.637     raeburn  1338: sub build_filepath {
                   1339:     my ($fpath) = @_;
                   1340:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   1341:     unless ($fpath eq '') {
                   1342:         my @parts=split('/',$fpath);
                   1343:         foreach my $part (@parts) {
                   1344:             $filepath.= '/'.$part;
                   1345:             if ((-e $filepath)!=1) {
                   1346:                 mkdir($filepath,0777);
                   1347:             }
                   1348:         }
                   1349:     }
                   1350:     return $filepath;
                   1351: }
                   1352: 
                   1353: sub store_edited_file {
1.638     albertel 1354:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  1355:     my $file = $primary_url;
                   1356:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   1357:     my $fpath = '';
                   1358:     my $fname = $file;
                   1359:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   1360:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   1361:     my $filepath = &build_filepath($fpath);
                   1362:     open(my $fh,'>'.$filepath.'/'.$fname);
                   1363:     print $fh $content;
                   1364:     close($fh);
1.638     albertel 1365:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  1366:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1367: 			  $home);
1.637     raeburn  1368:     if ($$fetchresult eq 'ok') {
                   1369:         return '/uploaded/'.$fpath.'/'.$fname;
                   1370:     } else {
1.638     albertel 1371:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   1372: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  1373:         return '/adm/notfound.html';
                   1374:     }
                   1375: }
                   1376: 
1.531     albertel 1377: sub clean_filename {
                   1378:     my ($fname)=@_;
1.315     www      1379: # Replace Windows backslashes by forward slashes
1.257     www      1380:     $fname=~s/\\/\//g;
1.315     www      1381: # Get rid of everything but the actual filename
1.257     www      1382:     $fname=~s/^.*\/([^\/]+)$/$1/;
1.315     www      1383: # Replace spaces by underscores
                   1384:     $fname=~s/\s+/\_/g;
                   1385: # Replace all other weird characters by nothing
1.317     www      1386:     $fname=~s/[^\w\.\-]//g;
1.540     albertel 1387: # Replace all .\d. sequences with _\d. so they no longer look like version
                   1388: # numbers
                   1389:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 1390:     return $fname;
                   1391: }
                   1392: 
1.608     albertel 1393: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 1394: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 1395: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 1396: #        $coursedoc - if true up to the current course
                   1397: #                     if false
                   1398: #        $subdir - directory in userfile to store the file into
                   1399: #        $parser, $allfiles, $codebase - unknown
                   1400: #
                   1401: # output: url of file in userspace, or error: <message> 
                   1402: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 1403: 
                   1404: 
1.531     albertel 1405: sub userfileupload {
1.719     banghart 1406:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,$destudom)=@_;
1.531     albertel 1407:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 1408:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 1409:     $fname=&clean_filename($fname);
1.315     www      1410: # See if there is anything left
1.257     www      1411:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 1412:     chop($env{'form.'.$formname});
1.523     raeburn  1413:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   1414:         my $now = time;
                   1415:         my $filepath = 'tmp/helprequests/'.$now;
                   1416:         my @parts=split(/\//,$filepath);
                   1417:         my $fullpath = $perlvar{'lonDaemons'};
                   1418:         for (my $i=0;$i<@parts;$i++) {
                   1419:             $fullpath .= '/'.$parts[$i];
                   1420:             if ((-e $fullpath)!=1) {
                   1421:                 mkdir($fullpath,0777);
                   1422:             }
                   1423:         }
                   1424:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 1425:         print $fh $env{'form.'.$formname};
1.523     raeburn  1426:         close($fh);
1.741     raeburn  1427:         return $fullpath.'/'.$fname;
                   1428:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   1429:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   1430:                        '_'.$env{'user.domain'}.'/pending';
                   1431:         my @parts=split(/\//,$filepath);
                   1432:         my $fullpath = $perlvar{'lonDaemons'};
                   1433:         for (my $i=0;$i<@parts;$i++) {
                   1434:             $fullpath .= '/'.$parts[$i];
                   1435:             if ((-e $fullpath)!=1) {
                   1436:                 mkdir($fullpath,0777);
                   1437:             }
                   1438:         }
                   1439:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   1440:         print $fh $env{'form.'.$formname};
                   1441:         close($fh);
                   1442:         return $fullpath.'/'.$fname;
1.523     raeburn  1443:     }
1.719     banghart 1444:     
1.258     www      1445: # Create the directory if not present
1.493     albertel 1446:     $fname="$subdir/$fname";
1.259     www      1447:     if ($coursedoc) {
1.638     albertel 1448: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1449: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  1450:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 1451:             return &finishuserfileupload($docuname,$docudom,
                   1452: 					 $formname,$fname,$parser,$allfiles,
                   1453: 					 $codebase);
1.481     raeburn  1454:         } else {
1.620     albertel 1455:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 1456:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   1457: 				       $fname,$formname,$parser,
                   1458: 				       $allfiles,$codebase);
1.481     raeburn  1459:         }
1.719     banghart 1460:     } elsif (defined($destuname)) {
                   1461:         my $docuname=$destuname;
                   1462:         my $docudom=$destudom;
                   1463: 	return &finishuserfileupload($docuname,$docudom,$formname,
                   1464: 				     $fname,$parser,$allfiles,$codebase);
                   1465:         
1.259     www      1466:     } else {
1.638     albertel 1467:         my $docuname=$env{'user.name'};
                   1468:         my $docudom=$env{'user.domain'};
1.714     raeburn  1469:         if (exists($env{'form.group'})) {
                   1470:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1471:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1472:         }
1.638     albertel 1473: 	return &finishuserfileupload($docuname,$docudom,$formname,
                   1474: 				     $fname,$parser,$allfiles,$codebase);
1.259     www      1475:     }
1.271     www      1476: }
                   1477: 
                   1478: sub finishuserfileupload {
1.638     albertel 1479:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase) = @_;
1.477     raeburn  1480:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      1481:     my $filepath=$perlvar{'lonDocRoot'};
1.494     albertel 1482:     my ($fnamepath,$file);
                   1483:     $file=$fname;
                   1484:     if ($fname=~m|/|) {
                   1485:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   1486: 	$path.=$fnamepath.'/';
                   1487:     }
1.259     www      1488:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      1489:     my $count;
                   1490:     for ($count=4;$count<=$#parts;$count++) {
                   1491:         $filepath.="/$parts[$count]";
                   1492:         if ((-e $filepath)!=1) {
                   1493: 	    mkdir($filepath,0777);
                   1494:         }
                   1495:     }
                   1496: # Save the file
                   1497:     {
1.701     albertel 1498: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   1499: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   1500: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   1501: 	    return '/adm/notfound.html';
                   1502: 	}
                   1503: 	if (!print FH ($env{'form.'.$formname})) {
                   1504: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   1505: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   1506: 	    return '/adm/notfound.html';
                   1507: 	}
1.570     albertel 1508: 	close(FH);
1.258     www      1509:     }
1.637     raeburn  1510:     if ($parser eq 'parse') {
1.638     albertel 1511:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
                   1512: 						   $codebase);
1.637     raeburn  1513:         unless ($parse_result eq 'ok') {
1.638     albertel 1514:             &logthis('Failed to parse '.$filepath.$file.
                   1515: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  1516:         }
                   1517:     }
1.259     www      1518: # Notify homeserver to grep it
                   1519: #
1.638     albertel 1520:     my $docuhome=&homeserver($docuname,$docudom);
1.494     albertel 1521:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      1522:     if ($fetchresult eq 'ok') {
1.259     www      1523: #
1.258     www      1524: # Return the URL to it
1.494     albertel 1525:         return '/uploaded/'.$path.$file;
1.263     www      1526:     } else {
1.494     albertel 1527:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   1528: 		 ': '.$fetchresult);
1.263     www      1529:         return '/adm/notfound.html';
                   1530:     }    
1.493     albertel 1531: }
                   1532: 
1.637     raeburn  1533: sub extract_embedded_items {
1.648     raeburn  1534:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
1.637     raeburn  1535:     my @state = ();
                   1536:     my %javafiles = (
                   1537:                       codebase => '',
                   1538:                       code => '',
                   1539:                       archive => ''
                   1540:                     );
                   1541:     my %mediafiles = (
                   1542:                       src => '',
                   1543:                       movie => '',
                   1544:                      );
1.648     raeburn  1545:     my $p;
                   1546:     if ($content) {
                   1547:         $p = HTML::LCParser->new($content);
                   1548:     } else {
                   1549:         $p = HTML::LCParser->new($filepath.'/'.$file);
                   1550:     }
1.641     albertel 1551:     while (my $t=$p->get_token()) {
1.640     albertel 1552: 	if ($t->[0] eq 'S') {
                   1553: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
                   1554: 	    push (@state, $tagname);
1.648     raeburn  1555:             if (lc($tagname) eq 'allow') {
                   1556:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   1557:             }
1.640     albertel 1558: 	    if (lc($tagname) eq 'img') {
                   1559: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   1560: 	    }
1.645     raeburn  1561:             if (lc($tagname) eq 'script') {
                   1562:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   1563:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   1564:                 } else {
                   1565:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   1566:                 }
                   1567:             }
                   1568:             if (lc($tagname) eq 'link') {
                   1569:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   1570:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   1571:                 }
                   1572:             }
1.640     albertel 1573: 	    if (lc($tagname) eq 'object' ||
                   1574: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   1575: 		foreach my $item (keys(%javafiles)) {
                   1576: 		    $javafiles{$item} = '';
                   1577: 		}
                   1578: 	    }
                   1579: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   1580: 		my $name = lc($attr->{'name'});
                   1581: 		foreach my $item (keys(%javafiles)) {
                   1582: 		    if ($name eq $item) {
                   1583: 			$javafiles{$item} = $attr->{'value'};
                   1584: 			last;
                   1585: 		    }
                   1586: 		}
                   1587: 		foreach my $item (keys(%mediafiles)) {
                   1588: 		    if ($name eq $item) {
                   1589: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   1590: 			last;
                   1591: 		    }
                   1592: 		}
                   1593: 	    }
                   1594: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   1595: 		foreach my $item (keys(%javafiles)) {
                   1596: 		    if ($attr->{$item}) {
                   1597: 			$javafiles{$item} = $attr->{$item};
                   1598: 			last;
                   1599: 		    }
                   1600: 		}
                   1601: 		foreach my $item (keys(%mediafiles)) {
                   1602: 		    if ($attr->{$item}) {
                   1603: 			&add_filetype($allfiles,$attr->{$item},$item);
                   1604: 			last;
                   1605: 		    }
                   1606: 		}
                   1607: 	    }
                   1608: 	} elsif ($t->[0] eq 'E') {
                   1609: 	    my ($tagname) = ($t->[1]);
                   1610: 	    if ($javafiles{'codebase'} ne '') {
                   1611: 		$javafiles{'codebase'} .= '/';
                   1612: 	    }  
                   1613: 	    if (lc($tagname) eq 'applet' ||
                   1614: 		lc($tagname) eq 'object' ||
                   1615: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   1616: 		) {
                   1617: 		foreach my $item (keys(%javafiles)) {
                   1618: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   1619: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   1620: 			&add_filetype($allfiles,$file,$item);
                   1621: 		    }
                   1622: 		}
                   1623: 	    } 
                   1624: 	    pop @state;
                   1625: 	}
                   1626:     }
1.637     raeburn  1627:     return 'ok';
                   1628: }
                   1629: 
1.639     albertel 1630: sub add_filetype {
                   1631:     my ($allfiles,$file,$type)=@_;
                   1632:     if (exists($allfiles->{$file})) {
                   1633: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   1634: 	    push(@{$allfiles->{$file}}, &escape($type));
                   1635: 	}
                   1636:     } else {
                   1637: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  1638:     }
                   1639: }
                   1640: 
1.493     albertel 1641: sub removeuploadedurl {
                   1642:     my ($url)=@_;
                   1643:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613     albertel 1644:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 1645: }
                   1646: 
                   1647: sub removeuserfile {
                   1648:     my ($docuname,$docudom,$fname)=@_;
                   1649:     my $home=&homeserver($docuname,$docudom);
                   1650:     return &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.257     www      1651: }
1.15      www      1652: 
1.530     albertel 1653: sub mkdiruserfile {
                   1654:     my ($docuname,$docudom,$dir)=@_;
                   1655:     my $home=&homeserver($docuname,$docudom);
                   1656:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   1657: }
                   1658: 
1.531     albertel 1659: sub renameuserfile {
                   1660:     my ($docuname,$docudom,$old,$new)=@_;
                   1661:     my $home=&homeserver($docuname,$docudom);
                   1662:     return &reply("renameuserfile:$docudom:$docuname:".&escape("$old").':'.
                   1663: 		  &escape("$new"),$home);
                   1664: }
                   1665: 
1.14      www      1666: # ------------------------------------------------------------------------- Log
                   1667: 
                   1668: sub log {
                   1669:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      1670:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      1671: }
                   1672: 
                   1673: # ------------------------------------------------------------------ Course Log
1.352     www      1674: #
                   1675: # This routine flushes several buffers of non-mission-critical nature
                   1676: #
1.157     www      1677: 
                   1678: sub flushcourselogs {
1.352     www      1679:     &logthis('Flushing log buffers');
                   1680: #
                   1681: # course logs
                   1682: # This is a log of all transactions in a course, which can be used
                   1683: # for data mining purposes
                   1684: #
                   1685: # It also collects the courseid database, which lists last transaction
                   1686: # times and course titles for all courseids
                   1687: #
                   1688:     my %courseidbuffer=();
1.191     harris41 1689:     foreach (keys %courselogs) {
1.157     www      1690:         my $crsid=$_;
1.352     www      1691:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      1692: 		          &escape($courselogs{$crsid}),
                   1693: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      1694: 	    delete $courselogs{$crsid};
                   1695:         } else {
                   1696:             &logthis('Failed to flush log buffer for '.$crsid);
                   1697:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 1698:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      1699:                         " exceeded maximum size, deleting.</font>");
                   1700:                delete $courselogs{$crsid};
                   1701:             }
1.352     www      1702:         }
                   1703:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
                   1704:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
1.516     raeburn  1705: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  1706:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.352     www      1707:         } else {
                   1708:            $courseidbuffer{$coursehombuf{$crsid}}=
1.516     raeburn  1709: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  1710:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.571     raeburn  1711:         }
1.191     harris41 1712:     }
1.352     www      1713: #
                   1714: # Write course id database (reverse lookup) to homeserver of courses 
                   1715: # Is used in pickcourse
                   1716: #
                   1717:     foreach (keys %courseidbuffer) {
1.353     www      1718:         &courseidput($hostdom{$_},$courseidbuffer{$_},$_);
1.352     www      1719:     }
                   1720: #
                   1721: # File accesses
                   1722: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   1723: #
1.449     matthew  1724:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  1725:         if ($entry =~ /___count$/) {
                   1726:             my ($dom,$name);
                   1727:             ($dom,$name,undef)=($entry=~m:___(\w+)/(\w+)/(.*)___count$:);
                   1728:             if (! defined($dom) || $dom eq '' || 
                   1729:                 ! defined($name) || $name eq '') {
1.620     albertel 1730:                 my $cid = $env{'request.course.id'};
                   1731:                 $dom  = $env{'request.'.$cid.'.domain'};
                   1732:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  1733:             }
1.450     matthew  1734:             my $value = $accesshash{$entry};
                   1735:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   1736:             my %temphash=($url => $value);
1.449     matthew  1737:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   1738:             if ($result eq 'ok') {
                   1739:                 delete $accesshash{$entry};
                   1740:             } elsif ($result eq 'unknown_cmd') {
                   1741:                 # Target server has old code running on it.
1.450     matthew  1742:                 my %temphash=($entry => $value);
1.449     matthew  1743:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1744:                     delete $accesshash{$entry};
                   1745:                 }
                   1746:             }
                   1747:         } else {
1.458     matthew  1748:             my ($dom,$name) = ($entry=~m:___(\w+)/(\w+)/(.*)___(\w+)$:);
1.450     matthew  1749:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  1750:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1751:                 delete $accesshash{$entry};
                   1752:             }
1.185     www      1753:         }
1.191     harris41 1754:     }
1.352     www      1755: #
                   1756: # Roles
                   1757: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   1758: #
1.349     www      1759:     foreach (keys %userrolehash) {
                   1760:         my $entry=$_;
1.351     www      1761:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      1762: 	    split(/\:/,$entry);
                   1763:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      1764:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      1765:                 $rudom,$runame) eq 'ok') {
                   1766: 	    delete $userrolehash{$entry};
                   1767:         }
                   1768:     }
1.662     raeburn  1769: #
                   1770: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   1771: #
                   1772:     my %domrolebuffer = ();
                   1773:     foreach my $entry (keys %domainrolehash) {
                   1774:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split/:/,$entry;
                   1775:         if ($domrolebuffer{$rudom}) {
                   1776:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   1777:                       '='.&escape($domainrolehash{$entry});
                   1778:         } else {
                   1779:             $domrolebuffer{$rudom}.=&escape($entry).
                   1780:                       '='.&escape($domainrolehash{$entry});
                   1781:         }
                   1782:         delete $domainrolehash{$entry};
                   1783:     }
                   1784:     foreach my $dom (keys(%domrolebuffer)) {
                   1785:         foreach my $tryserver (keys %libserv) {
                   1786:             if ($hostdom{$tryserver} eq $dom) {
                   1787:                 unless (&reply('domroleput:'.$dom.':'.
                   1788:                   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   1789:                     &logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   1790:                 }
                   1791:             }
                   1792:         }
                   1793:     }
1.186     www      1794:     $dumpcount++;
1.157     www      1795: }
                   1796: 
                   1797: sub courselog {
                   1798:     my $what=shift;
1.158     www      1799:     $what=time.':'.$what;
1.620     albertel 1800:     unless ($env{'request.course.id'}) { return ''; }
                   1801:     $coursedombuf{$env{'request.course.id'}}=
                   1802:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   1803:     $coursenumbuf{$env{'request.course.id'}}=
                   1804:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   1805:     $coursehombuf{$env{'request.course.id'}}=
                   1806:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   1807:     $coursedescrbuf{$env{'request.course.id'}}=
                   1808:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   1809:     $courseinstcodebuf{$env{'request.course.id'}}=
                   1810:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   1811:     $courseownerbuf{$env{'request.course.id'}}=
                   1812:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  1813:     $coursetypebuf{$env{'request.course.id'}}=
                   1814:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 1815:     if (defined $courselogs{$env{'request.course.id'}}) {
                   1816: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      1817:     } else {
1.620     albertel 1818: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      1819:     }
1.620     albertel 1820:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      1821: 	&flushcourselogs();
                   1822:     }
1.158     www      1823: }
                   1824: 
                   1825: sub courseacclog {
                   1826:     my $fnsymb=shift;
1.620     albertel 1827:     unless ($env{'request.course.id'}) { return ''; }
                   1828:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 1829:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      1830:         $what.=':POST';
1.583     matthew  1831:         # FIXME: Probably ought to escape things....
1.620     albertel 1832: 	foreach (keys %env) {
1.158     www      1833:             if ($_=~/^form\.(.*)/) {
1.620     albertel 1834: 		$what.=':'.$1.'='.$env{$_};
1.158     www      1835:             }
1.191     harris41 1836:         }
1.583     matthew  1837:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   1838:         # FIXME: We should not be depending on a form parameter that someone
                   1839:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 1840:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  1841:             $what.= ':POST';
                   1842:             # FIXME: Probably ought to escape things....
                   1843:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   1844:                                  'crsdiscuss') {
1.620     albertel 1845:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  1846:             }
                   1847:         }
1.158     www      1848:     }
                   1849:     &courselog($what);
1.149     www      1850: }
                   1851: 
1.185     www      1852: sub countacc {
                   1853:     my $url=&declutter(shift);
1.458     matthew  1854:     return if (! defined($url) || $url eq '');
1.620     albertel 1855:     unless ($env{'request.course.id'}) { return ''; }
                   1856:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      1857:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  1858:     $accesshash{$key}++;
1.185     www      1859: }
1.349     www      1860: 
1.361     www      1861: sub linklog {
                   1862:     my ($from,$to)=@_;
                   1863:     $from=&declutter($from);
                   1864:     $to=&declutter($to);
                   1865:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   1866:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   1867: }
                   1868:   
1.349     www      1869: sub userrolelog {
                   1870:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  1871:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  1872:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  1873:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   1874:         ($trole=~/^ta/)) {
1.350     www      1875:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   1876:        $userrolehash
                   1877:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      1878:                     =$tend.':'.$tstart;
1.662     raeburn  1879:     }
                   1880:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   1881:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   1882:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   1883:         ($trole=~/^sc/)) {
                   1884:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   1885:        $domainrolehash
                   1886:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   1887:                     = $tend.':'.$tstart;
                   1888:     }
1.351     www      1889: }
                   1890: 
                   1891: sub get_course_adv_roles {
                   1892:     my $cid=shift;
1.620     albertel 1893:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      1894:     my %coursehash=&coursedescription($cid);
1.470     www      1895:     my %nothide=();
                   1896:     foreach (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   1897: 	$nothide{join(':',split(/[\@\:]/,$_))}=1;
                   1898:     }
1.351     www      1899:     my %returnhash=();
                   1900:     my %dumphash=
                   1901:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   1902:     my $now=time;
                   1903:     foreach (keys %dumphash) {
                   1904: 	my ($tend,$tstart)=split(/\:/,$dumphash{$_});
                   1905:         if (($tstart) && ($tstart<0)) { next; }
                   1906:         if (($tend) && ($tend<$now)) { next; }
                   1907:         if (($tstart) && ($now<$tstart)) { next; }
                   1908:         my ($role,$username,$domain,$section)=split(/\:/,$_);
1.576     albertel 1909: 	if ($username eq '' || $domain eq '') { next; }
1.470     www      1910: 	if ((&privileged($username,$domain)) && 
                   1911: 	    (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 1912: 	if ($role eq 'cr') { next; }
1.351     www      1913:         my $key=&plaintext($role);
                   1914:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
                   1915:         if ($returnhash{$key}) {
                   1916: 	    $returnhash{$key}.=','.$username.':'.$domain;
                   1917:         } else {
                   1918:             $returnhash{$key}=$username.':'.$domain;
                   1919:         }
1.400     www      1920:      }
                   1921:     return %returnhash;
                   1922: }
                   1923: 
                   1924: sub get_my_roles {
                   1925:     my ($uname,$udom)=@_;
1.620     albertel 1926:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   1927:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.400     www      1928:     my %dumphash=
                   1929:             &dump('nohist_userroles',$udom,$uname);
                   1930:     my %returnhash=();
                   1931:     my $now=time;
                   1932:     foreach (keys %dumphash) {
                   1933: 	my ($tend,$tstart)=split(/\:/,$dumphash{$_});
                   1934:         if (($tstart) && ($tstart<0)) { next; }
                   1935:         if (($tend) && ($tend<$now)) { next; }
                   1936:         if (($tstart) && ($now<$tstart)) { next; }
                   1937:         my ($role,$username,$domain,$section)=split(/\:/,$_);
                   1938: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
1.373     www      1939:      }
                   1940:     return %returnhash;
1.399     www      1941: }
                   1942: 
                   1943: # ----------------------------------------------------- Frontpage Announcements
                   1944: #
                   1945: #
                   1946: 
                   1947: sub postannounce {
                   1948:     my ($server,$text)=@_;
                   1949:     unless (&allowed('psa',$hostdom{$server})) { return 'refused'; }
                   1950:     unless ($text=~/\w/) { $text=''; }
                   1951:     return &reply('setannounce:'.&escape($text),$server);
                   1952: }
                   1953: 
                   1954: sub getannounce {
1.448     albertel 1955: 
                   1956:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      1957: 	my $announcement='';
                   1958: 	while (<$fh>) { $announcement .=$_; }
1.448     albertel 1959: 	close($fh);
1.399     www      1960: 	if ($announcement=~/\w/) { 
                   1961: 	    return 
                   1962:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 1963:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      1964: 	} else {
                   1965: 	    return '';
                   1966: 	}
                   1967:     } else {
                   1968: 	return '';
                   1969:     }
1.351     www      1970: }
1.353     www      1971: 
                   1972: # ---------------------------------------------------------- Course ID routines
                   1973: # Deal with domain's nohist_courseid.db files
                   1974: #
                   1975: 
                   1976: sub courseidput {
                   1977:     my ($domain,$what,$coursehome)=@_;
                   1978:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   1979: }
                   1980: 
                   1981: sub courseiddump {
1.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 {
1.793     albertel 4220:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   4221: 	$cat_order) = @_;
1.521     raeburn  4222:     my $courses = '';
1.772     raeburn  4223:     my @homeservers;
1.521     raeburn  4224:     if ($caller eq 'global') {
1.793     albertel 4225:         foreach my $tryserver (keys(%libserv)) {
1.584     raeburn  4226:             if ($hostdom{$tryserver} eq $codedom) {
1.793     albertel 4227:                 if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
1.772     raeburn  4228:                     push(@homeservers,$tryserver);
                   4229:                 }
1.584     raeburn  4230:             }
                   4231:         }
1.521     raeburn  4232:     } else {
1.772     raeburn  4233:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  4234:     }
1.793     albertel 4235:     foreach my $code (keys(%{$instcodes})) {
                   4236:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  4237:     }
                   4238:     chop($courses);
1.772     raeburn  4239:     my $ok_response = 0;
                   4240:     my $response;
                   4241:     while (@homeservers > 0 && $ok_response == 0) {
                   4242:         my $server = shift(@homeservers); 
                   4243:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   4244:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   4245:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.793     albertel 4246: 		split/:/,$response;
1.772     raeburn  4247:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   4248:             push(@{$codetitles},&str2array($codetitles_str));
                   4249:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   4250:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   4251:             $ok_response = 1;
                   4252:         }
                   4253:     }
                   4254:     if ($ok_response) {
1.521     raeburn  4255:         return 'ok';
1.772     raeburn  4256:     } else {
                   4257:         return $response;
1.521     raeburn  4258:     }
                   4259: }
                   4260: 
1.792     raeburn  4261: sub auto_instcode_defaults {
                   4262:     my ($domain,$returnhash,$code_order) = @_;
                   4263:     my @homeservers;
1.793     albertel 4264:     foreach my $tryserver (keys(%libserv)) {
1.792     raeburn  4265:         if ($hostdom{$tryserver} eq $domain) {
1.793     albertel 4266:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
1.792     raeburn  4267:                 push(@homeservers,$tryserver);
                   4268:             }
                   4269:         }
                   4270:     }
                   4271:     my $ok_response = 0;
                   4272:     my $response;
                   4273:     while (@homeservers > 0 && $ok_response == 0) {
                   4274:         my $server = shift(@homeservers);
                   4275:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
                   4276:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
1.793     albertel 4277:             foreach my $pair (split(/\&/,$response)) {
                   4278:                 my ($name,$value)=split(/\=/,$pair);
1.792     raeburn  4279:                 if ($name eq 'code_order') {
1.793     albertel 4280:                     $code_order = [split(/\&/,&unescape($value))];
1.792     raeburn  4281:                 } else {
                   4282:                     $$returnhash{&unescape($name)}=&unescape($value);
                   4283:                 }
                   4284:             }
                   4285:         }
                   4286:         $ok_response = 1;
                   4287:     }
                   4288:     if ($ok_response) {
                   4289:         return 'ok';
                   4290:     } else {
                   4291:         return $response;
                   4292:     }
                   4293: } 
                   4294: 
1.777     albertel 4295: sub auto_validate_class_sec {
1.773     raeburn  4296:     my ($cdom,$cnum,$owner,$inst_class) = @_;
                   4297:     my $homeserver = &homeserver($cnum,$cdom);
                   4298:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.774     banghart 4299:                         &escape($owner).':'.$cdom,$homeserver);
1.773     raeburn  4300:     return $response;
                   4301: }
                   4302: 
1.679     raeburn  4303: # ------------------------------------------------------- Course Group routines
                   4304: 
                   4305: sub get_coursegroups {
1.683     raeburn  4306:     my ($cdom,$cnum,$group) = @_;
                   4307:     return(&dump('coursegroups',$cdom,$cnum,$group));
1.679     raeburn  4308: }
                   4309: 
                   4310: sub modify_coursegroup {
                   4311:     my ($cdom,$cnum,$groupsettings) = @_;
                   4312:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   4313: }
                   4314: 
                   4315: sub modify_group_roles {
                   4316:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
                   4317:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   4318:     my $role = 'gr/'.&escape($userprivs);
                   4319:     my ($uname,$udom) = split(/:/,$user);
                   4320:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
1.684     raeburn  4321:     if ($result eq 'ok') {
                   4322:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   4323:     }
1.679     raeburn  4324:     return $result;
                   4325: }
                   4326: 
                   4327: sub modify_coursegroup_membership {
                   4328:     my ($cdom,$cnum,$membership) = @_;
                   4329:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   4330:     return $result;
                   4331: }
                   4332: 
1.682     raeburn  4333: sub get_active_groups {
                   4334:     my ($udom,$uname,$cdom,$cnum) = @_;
                   4335:     my $now = time;
                   4336:     my %groups = ();
                   4337:     foreach my $key (keys(%env)) {
                   4338:         if ($key =~ m-user\.role\.gr\./([^/]+)/([^/]+)/(\w+)$-) {
                   4339:             my ($start,$end) = split(/\./,$env{$key});
                   4340:             if (($end!=0) && ($end<$now)) { next; }
                   4341:             if (($start!=0) && ($start>$now)) { next; }
                   4342:             if ($1 eq $cdom && $2 eq $cnum) {
                   4343:                 $groups{$3} = $env{$key} ;
                   4344:             }
                   4345:         }
                   4346:     }
                   4347:     return %groups;
                   4348: }
                   4349: 
1.683     raeburn  4350: sub get_group_membership {
                   4351:     my ($cdom,$cnum,$group) = @_;
                   4352:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   4353: }
                   4354: 
                   4355: sub get_users_groups {
                   4356:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  4357:     my @usersgroups;
1.683     raeburn  4358:     my $cachetime=1800;
                   4359:     $courseid=~s/\_/\//g;
                   4360:     $courseid=~s/^(\w)/\/$1/;
                   4361: 
                   4362:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  4363:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   4364:     if (defined($cached)) {
1.734     albertel 4365:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  4366:     } else {  
                   4367:         $grouplist = '';
                   4368:         my %roleshash = &dump('roles',$udom,$uname,$courseid);
                   4369:         my ($tmp) = keys(%roleshash);
                   4370:         if ($tmp=~/^error:/) {
                   4371:             &logthis('Error retrieving roles: '.$tmp.' for '.$uname.':'.$udom);
                   4372:         } else {
                   4373:             my $access_end = $env{'course.'.$courseid.
                   4374:                                   '.default_enrollment_end_date'};
                   4375:             my $now = time;
1.734     albertel 4376:             foreach my $key (keys(%roleshash)) {
1.733     raeburn  4377:                 if ($key =~ /^\Q$courseid\E\/(\w+)\_gr$/) {
                   4378:                     my $group = $1;
                   4379:                     if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   4380:                         my $start = $2;
                   4381:                         my $end = $1;
                   4382:                         if ($start == -1) { next; } # deleted from group
                   4383:                         if (($start!=0) && ($start>$now)) { next; }
                   4384:                         if (($end!=0) && ($end<$now)) {
                   4385:                             if ($access_end && $access_end < $now) {
                   4386:                                 if ($access_end - $end < 86400) {
                   4387:                                     push(@usersgroups,$group);
                   4388:                                 }
                   4389:                             }
                   4390:                             next;
                   4391:                         }
                   4392:                         push(@usersgroups,$group);
                   4393:                     }
1.683     raeburn  4394:                 }
                   4395:             }
1.733     raeburn  4396:             @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   4397:             $grouplist = join(':',@usersgroups);
                   4398:             &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  4399:         }
                   4400:     }
1.733     raeburn  4401:     return @usersgroups;
1.683     raeburn  4402: }
                   4403: 
                   4404: sub devalidate_getgroups_cache {
                   4405:     my ($udom,$uname,$cdom,$cnum)=@_;
                   4406:     my $courseid = $cdom.'_'.$cnum;
                   4407:     $courseid=~s/\_/\//g;
                   4408:     $courseid=~s/^(\w)/\/$1/;
                   4409:     my $hashid="$udom:$uname:$courseid";
                   4410:     &devalidate_cache_new('getgroups',$hashid);
                   4411: }
                   4412: 
1.12      www      4413: # ------------------------------------------------------------------ Plain Text
                   4414: 
                   4415: sub plaintext {
1.742     raeburn  4416:     my ($short,$type,$cid) = @_;
1.758     albertel 4417:     if ($short =~ /^cr/) {
                   4418: 	return (split('/',$short))[-1];
                   4419:     }
1.742     raeburn  4420:     if (!defined($cid)) {
                   4421:         $cid = $env{'request.course.id'};
                   4422:     }
                   4423:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
                   4424:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
                   4425:                                           '.plaintext'});
                   4426:     }
                   4427:     my %rolenames = (
                   4428:                       Course => 'std',
                   4429:                       Group => 'alt1',
                   4430:                     );
                   4431:     if (defined($type) && 
                   4432:          defined($rolenames{$type}) && 
                   4433:          defined($prp{$short}{$rolenames{$type}})) {
                   4434:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   4435:     } else {
                   4436:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   4437:     }
1.12      www      4438: }
                   4439: 
                   4440: # ----------------------------------------------------------------- Assign Role
                   4441: 
                   4442: sub assignrole {
1.357     www      4443:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
1.21      www      4444:     my $mrole;
                   4445:     if ($role =~ /^cr\//) {
1.393     www      4446:         my $cwosec=$url;
                   4447:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
                   4448: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      4449:            &logthis('Refused custom assignrole: '.
                   4450:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4451: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4452:            return 'refused'; 
                   4453:         }
1.21      www      4454:         $mrole='cr';
1.678     raeburn  4455:     } elsif ($role =~ /^gr\//) {
                   4456:         my $cwogrp=$url;
                   4457:         $cwogrp=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
                   4458:         unless (&allowed('mdg',$cwogrp)) {
                   4459:             &logthis('Refused group assignrole: '.
                   4460:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   4461:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   4462:             return 'refused';
                   4463:         }
                   4464:         $mrole='gr';
1.21      www      4465:     } else {
1.82      www      4466:         my $cwosec=$url;
1.83      www      4467:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
1.373     www      4468:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
1.104     www      4469:            &logthis('Refused assignrole: '.
                   4470:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4471: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4472:            return 'refused'; 
                   4473:         }
1.21      www      4474:         $mrole=$role;
                   4475:     }
1.620     albertel 4476:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4477:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      4478:     if ($end) { $command.='_'.$end; }
1.21      www      4479:     if ($start) {
                   4480: 	if ($end) { 
1.81      www      4481:            $command.='_'.$start; 
1.21      www      4482:         } else {
1.81      www      4483:            $command.='_0_'.$start;
1.21      www      4484:         }
                   4485:     }
1.739     raeburn  4486:     my $origstart = $start;
                   4487:     my $origend = $end;
1.357     www      4488: # actually delete
                   4489:     if ($deleteflag) {
1.373     www      4490: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      4491: # modify command to delete the role
1.620     albertel 4492:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      4493:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 4494: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      4495: # set start and finish to negative values for userrolelog
                   4496:            $start=-1;
                   4497:            $end=-1;
                   4498:         }
                   4499:     }
                   4500: # send command
1.349     www      4501:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      4502: # log new user role if status is ok
1.349     www      4503:     if ($answer eq 'ok') {
1.663     raeburn  4504: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  4505: # for course roles, perform group memberships changes triggered by role change.
                   4506:         unless ($role =~ /^gr/) {
                   4507:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   4508:                                              $origstart);
                   4509:         }
1.349     www      4510:     }
                   4511:     return $answer;
1.169     harris41 4512: }
                   4513: 
                   4514: # -------------------------------------------------- Modify user authentication
1.197     www      4515: # Overrides without validation
                   4516: 
1.169     harris41 4517: sub modifyuserauth {
                   4518:     my ($udom,$uname,$umode,$upass)=@_;
                   4519:     my $uhome=&homeserver($uname,$udom);
1.197     www      4520:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   4521:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 4522:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4523:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 4524:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   4525: 		     &escape($upass),$uhome);
1.620     albertel 4526:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      4527:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   4528:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   4529:     &log($udom,,$uname,$uhome,
1.620     albertel 4530:         'Authentication changed by '.$env{'user.domain'}.', '.
                   4531:                                      $env{'user.name'}.', '.$umode.
1.197     www      4532:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 4533:     unless ($reply eq 'ok') {
1.197     www      4534:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 4535: 	return 'error: '.$reply;
                   4536:     }   
1.170     harris41 4537:     return 'ok';
1.80      www      4538: }
                   4539: 
1.81      www      4540: # --------------------------------------------------------------- Modify a user
1.80      www      4541: 
1.81      www      4542: sub modifyuser {
1.206     matthew  4543:     my ($udom,    $uname, $uid,
                   4544:         $umode,   $upass, $first,
                   4545:         $middle,  $last,  $gene,
1.387     www      4546:         $forceid, $desiredhome, $email)=@_;
1.198     www      4547:     $udom=~s/\W//g;
                   4548:     $uname=~s/\W//g;
1.81      www      4549:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4550:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  4551: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   4552:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   4553:                                      ' desiredhome not specified'). 
1.620     albertel 4554:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4555:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 4556:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      4557: # ----------------------------------------------------------------- Create User
1.406     albertel 4558:     if (($uhome eq 'no_host') && 
                   4559: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      4560:         my $unhome='';
1.209     matthew  4561:         if (defined($desiredhome) && $hostdom{$desiredhome} eq $udom) { 
                   4562:             $unhome = $desiredhome;
1.620     albertel 4563: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   4564: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  4565:         } else { # load balancing routine for determining $unhome
1.80      www      4566:             my $tryserver;
1.81      www      4567:             my $loadm=10000000;
1.80      www      4568:             foreach $tryserver (keys %libserv) {
                   4569: 	       if ($hostdom{$tryserver} eq $udom) {
                   4570:                   my $answer=reply('load',$tryserver);
                   4571:                   if (($answer=~/\d+/) && ($answer<$loadm)) {
                   4572: 		      $loadm=$answer;
                   4573:                       $unhome=$tryserver;
                   4574:                   }
                   4575: 	       }
                   4576: 	    }
                   4577:         }
                   4578:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  4579: 	    return 'error: unable to find a home server for '.$uname.
                   4580:                    ' in domain '.$udom;
1.80      www      4581:         }
                   4582:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   4583:                          &escape($upass),$unhome);
                   4584: 	unless ($reply eq 'ok') {
                   4585:             return 'error: '.$reply;
                   4586:         }   
1.230     stredwic 4587:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      4588:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  4589: 	    return 'error: unable verify users home machine.';
1.80      www      4590:         }
1.209     matthew  4591:     }   # End of creation of new user
1.80      www      4592: # ---------------------------------------------------------------------- Add ID
                   4593:     if ($uid) {
                   4594:        $uid=~tr/A-Z/a-z/;
                   4595:        my %uidhash=&idrget($udom,$uname);
1.196     www      4596:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   4597:          && (!$forceid)) {
1.80      www      4598: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  4599: 	      return 'error: user id "'.$uid.'" does not match '.
                   4600:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      4601:           }
                   4602:        } else {
                   4603: 	  &idput($udom,($uname => $uid));
                   4604:        }
                   4605:     }
                   4606: # -------------------------------------------------------------- Add names, etc
1.313     matthew  4607:     my @tmp=&get('environment',
1.134     albertel 4608: 		   ['firstname','middlename','lastname','generation'],
                   4609: 		   $udom,$uname);
1.313     matthew  4610:     my %names;
                   4611:     if ($tmp[0] =~ m/^error:.*/) { 
                   4612:         %names=(); 
                   4613:     } else {
                   4614:         %names = @tmp;
                   4615:     }
1.388     www      4616: #
                   4617: # Make sure to not trash student environment if instructor does not bother
                   4618: # to supply name and email information
                   4619: #
                   4620:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  4621:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      4622:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  4623:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      4624:     if ($email) {
                   4625:        $email=~s/[^\w\@\.\-\,]//gs;
                   4626:        if ($email=~/\@/) { $names{'notification'} = $email;
                   4627: 			   $names{'critnotification'} = $email;
                   4628: 			   $names{'permanentemail'} = $email; }
                   4629:     }
1.134     albertel 4630:     my $reply = &put('environment', \%names, $udom,$uname);
                   4631:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.680     www      4632:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.81      www      4633:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4634:              $umode.', '.$first.', '.$middle.', '.
                   4635: 	     $last.', '.$gene.' by '.
1.620     albertel 4636:              $env{'user.name'}.' at '.$env{'user.domain'});
1.134     albertel 4637:     return 'ok';
1.80      www      4638: }
                   4639: 
1.81      www      4640: # -------------------------------------------------------------- Modify student
1.80      www      4641: 
1.81      www      4642: sub modifystudent {
                   4643:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.515     raeburn  4644:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
1.455     albertel 4645:     if (!$cid) {
1.620     albertel 4646: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 4647: 	    return 'not_in_class';
                   4648: 	}
1.80      www      4649:     }
                   4650: # --------------------------------------------------------------- Make the user
1.81      www      4651:     my $reply=&modifyuser
1.209     matthew  4652: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      4653:          $desiredhome,$email);
1.80      www      4654:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  4655:     # This will cause &modify_student_enrollment to get the uid from the
                   4656:     # students environment
                   4657:     $uid = undef if (!$forceid);
1.455     albertel 4658:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.515     raeburn  4659: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
1.297     matthew  4660:     return $reply;
                   4661: }
                   4662: 
                   4663: sub modify_student_enrollment {
1.515     raeburn  4664:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
1.455     albertel 4665:     my ($cdom,$cnum,$chome);
                   4666:     if (!$cid) {
1.620     albertel 4667: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 4668: 	    return 'not_in_class';
                   4669: 	}
1.620     albertel 4670: 	$cdom=$env{'course.'.$cid.'.domain'};
                   4671: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 4672:     } else {
                   4673: 	($cdom,$cnum)=split(/_/,$cid);
                   4674:     }
1.620     albertel 4675:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 4676:     if (!$chome) {
1.457     raeburn  4677: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  4678:     }
1.455     albertel 4679:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  4680:     # Make sure the user exists
1.81      www      4681:     my $uhome=&homeserver($uname,$udom);
                   4682:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   4683: 	return 'error: no such user';
                   4684:     }
1.297     matthew  4685:     # Get student data if we were not given enough information
                   4686:     if (!defined($first)  || $first  eq '' || 
                   4687:         !defined($last)   || $last   eq '' || 
                   4688:         !defined($uid)    || $uid    eq '' || 
                   4689:         !defined($middle) || $middle eq '' || 
                   4690:         !defined($gene)   || $gene   eq '') {
1.294     matthew  4691:         # They did not supply us with enough data to enroll the student, so
                   4692:         # we need to pick up more information.
1.297     matthew  4693:         my %tmp = &get('environment',
1.294     matthew  4694:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  4695:                        ,$udom,$uname);
                   4696: 
1.455     albertel 4697:         #foreach (keys(%tmp)) {
                   4698:         #    &logthis("key $_ = ".$tmp{$_});
                   4699:         #}
1.294     matthew  4700:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   4701:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   4702:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  4703:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  4704:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   4705:     }
1.556     albertel 4706:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 4707:     my $reply=cput('classlist',
                   4708: 		   {"$uname:$udom" => 
1.515     raeburn  4709: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 4710: 		   $cdom,$cnum);
1.81      www      4711:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   4712: 	return 'error: '.$reply;
1.652     albertel 4713:     } else {
                   4714: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      4715:     }
1.297     matthew  4716:     # Add student role to user
1.83      www      4717:     my $uurl='/'.$cid;
1.81      www      4718:     $uurl=~s/\_/\//g;
                   4719:     if ($usec) {
                   4720: 	$uurl.='/'.$usec;
                   4721:     }
                   4722:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21      www      4723: }
                   4724: 
1.556     albertel 4725: sub format_name {
                   4726:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   4727:     my $name;
                   4728:     if ($first ne 'lastname') {
                   4729: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   4730:     } else {
                   4731: 	if ($lastname=~/\S/) {
                   4732: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   4733: 	    $name=~s/\s+,/,/;
                   4734: 	} else {
                   4735: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   4736: 	}
                   4737:     }
                   4738:     $name=~s/^\s+//;
                   4739:     $name=~s/\s+$//;
                   4740:     $name=~s/\s+/ /g;
                   4741:     return $name;
                   4742: }
                   4743: 
1.84      www      4744: # ------------------------------------------------- Write to course preferences
                   4745: 
                   4746: sub writecoursepref {
                   4747:     my ($courseid,%prefs)=@_;
                   4748:     $courseid=~s/^\///;
                   4749:     $courseid=~s/\_/\//g;
                   4750:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   4751:     my $chome=homeserver($cnum,$cdomain);
                   4752:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   4753: 	return 'error: no such course';
                   4754:     }
                   4755:     my $cstring='';
1.191     harris41 4756:     foreach (keys %prefs) {
1.84      www      4757: 	$cstring.=escape($_).'='.escape($prefs{$_}).'&';
1.191     harris41 4758:     }
1.84      www      4759:     $cstring=~s/\&$//;
                   4760:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   4761: }
                   4762: 
                   4763: # ---------------------------------------------------------- Make/modify course
                   4764: 
                   4765: sub createcourse {
1.741     raeburn  4766:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
                   4767:         $course_owner,$crstype)=@_;
1.84      www      4768:     $url=&declutter($url);
                   4769:     my $cid='';
1.264     matthew  4770:     unless (&allowed('ccc',$udom)) {
1.84      www      4771:         return 'refused';
                   4772:     }
                   4773: # ------------------------------------------------------------------- Create ID
1.674     www      4774:    my $uname=int(1+rand(9)).
                   4775:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   4776:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      4777:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   4778: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 4779:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      4780:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   4781:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   4782:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 4783:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      4784:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   4785:            return 'error: unable to generate unique course-ID';
                   4786:        } 
                   4787:    }
1.264     matthew  4788: # ------------------------------------------------ Check supplied server name
1.620     albertel 4789:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.264     matthew  4790:     if (! exists($libserv{$course_server})) {
                   4791:         return 'error:bad server name '.$course_server;
                   4792:     }
1.84      www      4793: # ------------------------------------------------------------- Make the course
                   4794:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  4795:                       $course_server);
1.84      www      4796:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 4797:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      4798:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   4799: 	return 'error: no such course';
                   4800:     }
1.271     www      4801: # ----------------------------------------------------------------- Course made
1.516     raeburn  4802: # log existence
                   4803:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
1.741     raeburn  4804:                  ':'.&escape($inst_code).':'.&escape($course_owner).':'.
                   4805:                   &escape($crstype),$uhome);
1.358     www      4806:     &flushcourselogs();
                   4807: # set toplevel url
1.271     www      4808:     my $topurl=$url;
                   4809:     unless ($nonstandard) {
                   4810: # ------------------------------------------ For standard courses, make top url
                   4811:         my $mapurl=&clutter($url);
1.278     www      4812:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 4813:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      4814: <map>
                   4815: <resource id="1" type="start"></resource>
                   4816: <resource id="2" src="$mapurl"></resource>
                   4817: <resource id="3" type="finish"></resource>
                   4818: <link index="1" from="1" to="2"></link>
                   4819: <link index="2" from="2" to="3"></link>
                   4820: </map>
                   4821: ENDINITMAP
                   4822:         $topurl=&declutter(
1.638     albertel 4823:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      4824:                           );
                   4825:     }
                   4826: # ----------------------------------------------------------- Write preferences
1.84      www      4827:     &writecoursepref($udom.'_'.$uname,
                   4828:                      ('description' => $description,
1.271     www      4829:                       'url'         => $topurl));
1.84      www      4830:     return '/'.$udom.'/'.$uname;
                   4831: }
                   4832: 
1.21      www      4833: # ---------------------------------------------------------- Assign Custom Role
                   4834: 
                   4835: sub assigncustomrole {
1.357     www      4836:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21      www      4837:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357     www      4838:                        $end,$start,$deleteflag);
1.21      www      4839: }
                   4840: 
                   4841: # ----------------------------------------------------------------- Revoke Role
                   4842: 
                   4843: sub revokerole {
1.357     www      4844:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21      www      4845:     my $now=time;
1.357     www      4846:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21      www      4847: }
                   4848: 
                   4849: # ---------------------------------------------------------- Revoke Custom Role
                   4850: 
                   4851: sub revokecustomrole {
1.357     www      4852:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21      www      4853:     my $now=time;
1.357     www      4854:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
                   4855:            $deleteflag);
1.17      www      4856: }
                   4857: 
1.533     banghart 4858: # ------------------------------------------------------------ Disk usage
1.535     albertel 4859: sub diskusage {
1.533     banghart 4860:     my ($udom,$uname,$directoryRoot)=@_;
                   4861:     $directoryRoot =~ s/\/$//;
1.535     albertel 4862:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
1.514     albertel 4863:     return $listing;
1.512     banghart 4864: }
                   4865: 
1.566     banghart 4866: sub is_locked {
                   4867:     my ($file_name, $domain, $user) = @_;
                   4868:     my @check;
                   4869:     my $is_locked;
                   4870:     push @check, $file_name;
1.613     albertel 4871:     my %locked = &get('file_permissions',\@check,
1.620     albertel 4872: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 4873:     my ($tmp)=keys(%locked);
                   4874:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  4875:     
1.566     banghart 4876:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  4877:         $is_locked = 'false';
                   4878:         foreach my $entry (@{$locked{$file_name}}) {
                   4879:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  4880:                $is_locked = 'true';
                   4881:                last;
1.745     raeburn  4882:            }
                   4883:        }
1.566     banghart 4884:     } else {
                   4885:         $is_locked = 'false';
                   4886:     }
                   4887: }
                   4888: 
1.759     albertel 4889: sub declutter_portfile {
                   4890:     my ($file) = @_;
                   4891:     &logthis("got $file");
                   4892:     $file =~ s-^(/portfolio/|portfolio/)-/-;
                   4893:     &logthis("ret $file");
                   4894:     return $file;
                   4895: }
                   4896: 
1.559     banghart 4897: # ------------------------------------------------------------- Mark as Read Only
                   4898: 
                   4899: sub mark_as_readonly {
                   4900:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 4901:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 4902:     my ($tmp)=keys(%current_permissions);
                   4903:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 4904:     foreach my $file (@{$files}) {
1.759     albertel 4905: 	$file = &declutter_portfile($file);
1.561     banghart 4906:         push(@{$current_permissions{$file}},$what);
1.559     banghart 4907:     }
1.613     albertel 4908:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 4909:     return;
                   4910: }
                   4911: 
1.572     banghart 4912: # ------------------------------------------------------------Save Selected Files
                   4913: 
                   4914: sub save_selected_files {
                   4915:     my ($user, $path, @files) = @_;
                   4916:     my $filename = $user."savedfiles";
1.573     banghart 4917:     my @other_files = &files_not_in_path($user, $path);
1.574     banghart 4918:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 4919:     foreach my $file (@files) {
1.620     albertel 4920:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 4921:     }
                   4922:     foreach my $file (@other_files) {
1.574     banghart 4923:         print (OUT $file."\n");
1.572     banghart 4924:     }
1.574     banghart 4925:     close (OUT);
1.572     banghart 4926:     return 'ok';
                   4927: }
                   4928: 
1.574     banghart 4929: sub clear_selected_files {
                   4930:     my ($user) = @_;
                   4931:     my $filename = $user."savedfiles";
                   4932:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   4933:     print (OUT undef);
                   4934:     close (OUT);
                   4935:     return ("ok");    
                   4936: }
                   4937: 
1.572     banghart 4938: sub files_in_path {
                   4939:     my ($user, $path) = @_;
                   4940:     my $filename = $user."savedfiles";
                   4941:     my %return_files;
1.574     banghart 4942:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 4943:     while (my $line_in = <IN>) {
1.574     banghart 4944:         chomp ($line_in);
                   4945:         my @paths_and_file = split (m!/!, $line_in);
                   4946:         my $file_part = pop (@paths_and_file);
                   4947:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 4948:         $path_part.='/';
                   4949:         my $path_and_file = $path_part.$file_part;
                   4950:         if ($path_part eq $path) {
                   4951:             $return_files{$file_part}= 'selected';
                   4952:         }
                   4953:     }
1.574     banghart 4954:     close (IN);
                   4955:     return (\%return_files);
1.572     banghart 4956: }
                   4957: 
                   4958: # called in portfolio select mode, to show files selected NOT in current directory
                   4959: sub files_not_in_path {
                   4960:     my ($user, $path) = @_;
                   4961:     my $filename = $user."savedfiles";
                   4962:     my @return_files;
                   4963:     my $path_part;
1.574     banghart 4964:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.572     banghart 4965:     while (<IN>) {
                   4966:         #ok, I know it's clunky, but I want it to work
                   4967:         my @paths_and_file = split m!/!, $_;
1.574     banghart 4968:         my $file_part = pop (@paths_and_file);
                   4969:         chomp ($file_part);
                   4970:         my $path_part = join ('/', @paths_and_file);
1.572     banghart 4971:         $path_part .= '/';
                   4972:         my $path_and_file = $path_part.$file_part;
                   4973:         if ($path_part ne $path) {
1.574     banghart 4974:             push (@return_files, ($path_and_file));
1.572     banghart 4975:         }
                   4976:     }
1.574     banghart 4977:     close (OUT);
                   4978:     return (@return_files);
1.572     banghart 4979: }
                   4980: 
1.745     raeburn  4981: #----------------------------------------------Get portfolio file permissions
1.629     banghart 4982: 
1.745     raeburn  4983: sub get_portfile_permissions {
                   4984:     my ($domain,$user) = @_;
1.613     albertel 4985:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 4986:     my ($tmp)=keys(%current_permissions);
                   4987:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  4988:     return \%current_permissions;
                   4989: }
                   4990: 
                   4991: #---------------------------------------------Get portfolio file access controls
                   4992: 
1.749     raeburn  4993: sub get_access_controls {
1.745     raeburn  4994:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 4995:     my %access;
                   4996:     my $real_file = $file;
                   4997:     $file =~ s/\.meta$//;
1.745     raeburn  4998:     if (defined($file)) {
1.749     raeburn  4999:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   5000:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 5001:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  5002:             }
                   5003:         }
1.745     raeburn  5004:     } else {
1.749     raeburn  5005:         foreach my $key (keys(%{$current_permissions})) {
                   5006:             if ($key =~ /\0accesscontrol$/) {
                   5007:                 if (defined($group)) {
                   5008:                     if ($key !~ m-^\Q$group\E/-) {
                   5009:                         next;
                   5010:                     }
                   5011:                 }
                   5012:                 my ($fullpath) = split(/\0/,$key);
                   5013:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   5014:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   5015:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   5016:                     }
                   5017:                 }
                   5018:             }
                   5019:         }
                   5020:     }
                   5021:     return %access;
                   5022: }
                   5023: 
                   5024: sub modify_access_controls {
                   5025:     my ($file_name,$changes,$domain,$user)=@_;
                   5026:     my ($outcome,$deloutcome);
                   5027:     my %store_permissions;
                   5028:     my %new_values;
                   5029:     my %new_control;
                   5030:     my %translation;
                   5031:     my @deletions = ();
                   5032:     my $now = time;
                   5033:     if (exists($$changes{'activate'})) {
                   5034:         if (ref($$changes{'activate'}) eq 'HASH') {
                   5035:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   5036:             my $numnew = scalar(@newitems);
                   5037:             for (my $i=0; $i<$numnew; $i++) {
                   5038:                 my $newkey = $newitems[$i];
                   5039:                 my $newid = &Apache::loncommon::get_cgi_id();
                   5040:                 $newkey =~ s/^(\d+)/$newid/;
                   5041:                 $translation{$1} = $newid;
                   5042:                 $new_values{$file_name."\0".$newkey} = 
                   5043:                                           $$changes{'activate'}{$newitems[$i]};
                   5044:                 $new_control{$newkey} = $now;
                   5045:             }
                   5046:         }
                   5047:     }
                   5048:     my %todelete;
                   5049:     my %changed_items;
                   5050:     foreach my $action ('delete','update') {
                   5051:         if (exists($$changes{$action})) {
                   5052:             if (ref($$changes{$action}) eq 'HASH') {
                   5053:                 foreach my $key (keys(%{$$changes{$action}})) {
                   5054:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   5055:                     if ($action eq 'delete') { 
                   5056:                         $todelete{$itemnum} = 1;
                   5057:                     } else {
                   5058:                         $changed_items{$itemnum} = $key;
                   5059:                     }
                   5060:                 }
1.745     raeburn  5061:             }
                   5062:         }
1.749     raeburn  5063:     }
                   5064:     # get lock on access controls for file.
                   5065:     my $lockhash = {
                   5066:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   5067:                                                        ':'.$env{'user.domain'},
                   5068:                    }; 
                   5069:     my $tries = 0;
                   5070:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5071:    
                   5072:     while (($gotlock ne 'ok') && $tries <3) {
                   5073:         $tries ++;
                   5074:         sleep 1;
                   5075:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5076:     }
                   5077:     if ($gotlock eq 'ok') {
                   5078:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   5079:         my ($tmp)=keys(%curr_permissions);
                   5080:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   5081:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   5082:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   5083:             if (ref($curr_controls) eq 'HASH') {
                   5084:                 foreach my $control_item (keys(%{$curr_controls})) {
                   5085:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   5086:                     if (defined($todelete{$itemnum})) {
                   5087:                         push(@deletions,$file_name."\0".$control_item);
                   5088:                     } else {
                   5089:                         if (defined($changed_items{$itemnum})) {
                   5090:                             $new_control{$changed_items{$itemnum}} = $now;
                   5091:                             push(@deletions,$file_name."\0".$control_item);
                   5092:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   5093:                         } else {
                   5094:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   5095:                         }
                   5096:                     }
1.745     raeburn  5097:                 }
                   5098:             }
                   5099:         }
1.749     raeburn  5100:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   5101:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   5102:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   5103:         #  remove lock
                   5104:         my @del_lock = ($file_name."\0".'locked_access_records');
                   5105:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
                   5106:     } else {
                   5107:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  5108:     }
1.749     raeburn  5109:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  5110: }
                   5111: 
                   5112: #------------------------------------------------------Get Marked as Read Only
                   5113: 
                   5114: sub get_marked_as_readonly {
                   5115:     my ($domain,$user,$what,$group) = @_;
                   5116:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 5117:     my @readonly_files;
1.629     banghart 5118:     my $cmp1=$what;
                   5119:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  5120:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5121:         if (defined($group)) {
                   5122:             if ($file_name !~ m-^\Q$group\E/-) {
                   5123:                 next;
                   5124:             }
                   5125:         }
1.561     banghart 5126:         if (ref($value) eq "ARRAY"){
                   5127:             foreach my $stored_what (@{$value}) {
1.629     banghart 5128:                 my $cmp2=$stored_what;
1.759     albertel 5129:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  5130:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  5131:                 }
1.629     banghart 5132:                 if ($cmp1 eq $cmp2) {
1.561     banghart 5133:                     push(@readonly_files, $file_name);
1.745     raeburn  5134:                     last;
1.563     banghart 5135:                 } elsif (!defined($what)) {
                   5136:                     push(@readonly_files, $file_name);
1.745     raeburn  5137:                     last;
1.561     banghart 5138:                 }
                   5139:             }
1.745     raeburn  5140:         }
1.561     banghart 5141:     }
                   5142:     return @readonly_files;
                   5143: }
1.577     banghart 5144: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 5145: 
1.577     banghart 5146: sub get_marked_as_readonly_hash {
1.745     raeburn  5147:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 5148:     my %readonly_files;
1.745     raeburn  5149:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5150:         if (defined($group)) {
                   5151:             if ($file_name !~ m-^\Q$group\E/-) {
                   5152:                 next;
                   5153:             }
                   5154:         }
1.577     banghart 5155:         if (ref($value) eq "ARRAY"){
                   5156:             foreach my $stored_what (@{$value}) {
1.745     raeburn  5157:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 5158:                     foreach my $lock_descriptor(@{$stored_what}) {
                   5159:                         if ($lock_descriptor eq 'graded') {
                   5160:                             $readonly_files{$file_name} = 'graded';
                   5161:                         } elsif ($lock_descriptor eq 'handback') {
                   5162:                             $readonly_files{$file_name} = 'handback';
                   5163:                         } else {
                   5164:                             if (!exists($readonly_files{$file_name})) {
                   5165:                                 $readonly_files{$file_name} = 'locked';
                   5166:                             }
                   5167:                         }
1.745     raeburn  5168:                     }
1.750     banghart 5169:                 } 
1.577     banghart 5170:             }
                   5171:         } 
                   5172:     }
                   5173:     return %readonly_files;
                   5174: }
1.559     banghart 5175: # ------------------------------------------------------------ Unmark as Read Only
                   5176: 
                   5177: sub unmark_as_readonly {
1.629     banghart 5178:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   5179:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  5180:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 5181:     $file_name = &declutter_portfile($file_name);
1.634     albertel 5182:     my $symb_crs = $what;
                   5183:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  5184:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 5185:     my ($tmp)=keys(%current_permissions);
                   5186:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5187:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 5188:     foreach my $file (@readonly_files) {
1.759     albertel 5189: 	my $clean_file = &declutter_portfile($file);
                   5190: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 5191: 	my $current_locks = $current_permissions{$file};
1.563     banghart 5192:         my @new_locks;
                   5193:         my @del_keys;
                   5194:         if (ref($current_locks) eq "ARRAY"){
                   5195:             foreach my $locker (@{$current_locks}) {
1.632     albertel 5196:                 my $compare=$locker;
1.749     raeburn  5197:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  5198:                     $compare=join('',@{$locker});
1.746     raeburn  5199:                     if ($compare ne $symb_crs) {
                   5200:                         push(@new_locks, $locker);
                   5201:                     }
1.563     banghart 5202:                 }
                   5203:             }
1.650     albertel 5204:             if (scalar(@new_locks) > 0) {
1.563     banghart 5205:                 $current_permissions{$file} = \@new_locks;
                   5206:             } else {
                   5207:                 push(@del_keys, $file);
1.613     albertel 5208:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 5209:                 delete($current_permissions{$file});
1.563     banghart 5210:             }
                   5211:         }
1.561     banghart 5212:     }
1.613     albertel 5213:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5214:     return;
                   5215: }
1.512     banghart 5216: 
1.17      www      5217: # ------------------------------------------------------------ Directory lister
                   5218: 
                   5219: sub dirlist {
1.253     stredwic 5220:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
                   5221: 
1.18      www      5222:     $uri=~s/^\///;
                   5223:     $uri=~s/\/$//;
1.253     stredwic 5224:     my ($udom, $uname);
                   5225:     (undef,$udom,$uname)=split(/\//,$uri);
                   5226:     if(defined($userdomain)) {
                   5227:         $udom = $userdomain;
                   5228:     }
                   5229:     if(defined($username)) {
                   5230:         $uname = $username;
                   5231:     }
                   5232: 
                   5233:     my $dirRoot = $perlvar{'lonDocRoot'};
                   5234:     if(defined($alternateDirectoryRoot)) {
                   5235:         $dirRoot = $alternateDirectoryRoot;
                   5236:         $dirRoot =~ s/\/$//;
1.751     banghart 5237:     }
1.253     stredwic 5238: 
                   5239:     if($udom) {
                   5240:         if($uname) {
1.605     matthew  5241:             my $listing=reply('ls2:'.$dirRoot.'/'.$uri,
1.253     stredwic 5242:                               homeserver($uname,$udom));
1.605     matthew  5243:             my @listing_results;
                   5244:             if ($listing eq 'unknown_cmd') {
                   5245:                 $listing=reply('ls:'.$dirRoot.'/'.$uri,
                   5246:                                homeserver($uname,$udom));
                   5247:                 @listing_results = split(/:/,$listing);
                   5248:             } else {
                   5249:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   5250:             }
                   5251:             return @listing_results;
1.253     stredwic 5252:         } elsif(!defined($alternateDirectoryRoot)) {
                   5253:             my $tryserver;
                   5254:             my %allusers=();
                   5255:             foreach $tryserver (keys %libserv) {
                   5256:                 if($hostdom{$tryserver} eq $udom) {
1.605     matthew  5257:                     my $listing=reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
1.253     stredwic 5258:                                       $udom, $tryserver);
1.605     matthew  5259:                     my @listing_results;
                   5260:                     if ($listing eq 'unknown_cmd') {
                   5261:                         $listing=reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   5262:                                        $udom, $tryserver);
                   5263:                         @listing_results = split(/:/,$listing);
                   5264:                     } else {
                   5265:                         @listing_results =
                   5266:                             map { &unescape($_); } split(/:/,$listing);
                   5267:                     }
                   5268:                     if ($listing_results[0] ne 'no_such_dir' && 
                   5269:                         $listing_results[0] ne 'empty'       &&
                   5270:                         $listing_results[0] ne 'con_lost') {
                   5271:                         foreach (@listing_results) {
1.253     stredwic 5272:                             my ($entry,@stat)=split(/&/,$_);
                   5273:                             $allusers{$entry}=1;
                   5274:                         }
                   5275:                     }
1.191     harris41 5276:                 }
1.253     stredwic 5277:             }
                   5278:             my $alluserstr='';
                   5279:             foreach (sort keys %allusers) {
                   5280:                 $alluserstr.=$_.'&user:';
                   5281:             }
                   5282:             $alluserstr=~s/:$//;
                   5283:             return split(/:/,$alluserstr);
                   5284:         } else {
                   5285:             my @emptyResults = ();
                   5286:             push(@emptyResults, 'missing user name');
                   5287:             return split(':',@emptyResults);
                   5288:         }
                   5289:     } elsif(!defined($alternateDirectoryRoot)) {
                   5290:         my $tryserver;
                   5291:         my %alldom=();
                   5292:         foreach $tryserver (keys %libserv) {
                   5293:             $alldom{$hostdom{$tryserver}}=1;
                   5294:         }
                   5295:         my $alldomstr='';
                   5296:         foreach (sort keys %alldom) {
1.397     albertel 5297:             $alldomstr.=$perlvar{'lonDocRoot'}.'/res/'.$_.'/&domain:';
1.253     stredwic 5298:         }
                   5299:         $alldomstr=~s/:$//;
                   5300:         return split(/:/,$alldomstr);       
                   5301:     } else {
                   5302:         my @emptyResults = ();
                   5303:         push(@emptyResults, 'missing domain');
                   5304:         return split(':',@emptyResults);
1.275     stredwic 5305:     }
                   5306: }
                   5307: 
                   5308: # --------------------------------------------- GetFileTimestamp
                   5309: # This function utilizes dirlist and returns the date stamp for
                   5310: # when it was last modified.  It will also return an error of -1
                   5311: # if an error occurs
                   5312: 
1.410     matthew  5313: ##
                   5314: ## FIXME: This subroutine assumes its caller knows something about the
                   5315: ## directory structure of the home server for the student ($root).
                   5316: ## Not a good assumption to make.  Since this is for looking up files
                   5317: ## in user directories, the full path should be constructed by lond, not
                   5318: ## whatever machine we request data from.
                   5319: ##
1.275     stredwic 5320: sub GetFileTimestamp {
                   5321:     my ($studentDomain,$studentName,$filename,$root)=@_;
                   5322:     $studentDomain=~s/\W//g;
                   5323:     $studentName=~s/\W//g;
                   5324:     my $subdir=$studentName.'__';
                   5325:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   5326:     my $proname="$studentDomain/$subdir/$studentName";
                   5327:     $proname .= '/'.$filename;
1.375     matthew  5328:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
                   5329:                                               $studentName, $root);
1.275     stredwic 5330:     my @stats = split('&', $fileStat);
                   5331:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  5332:         # @stats contains first the filename, then the stat output
                   5333:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 5334:     } else {
                   5335:         return -1;
1.253     stredwic 5336:     }
1.26      www      5337: }
                   5338: 
1.712     albertel 5339: sub stat_file {
                   5340:     my ($uri) = @_;
1.787     albertel 5341:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 5342: 
1.712     albertel 5343:     my ($udom,$uname,$file,$dir);
                   5344:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   5345: 	($udom,$uname,$file) =
                   5346: 	    ($uri =~ m-/(?:uploaded|editupload)/?([^/]*)/?([^/]*)/?(.*)-);
                   5347: 	$file = 'userfiles/'.$file;
1.740     www      5348: 	$dir = &propath($udom,$uname);
1.712     albertel 5349:     }
                   5350:     if ($uri =~ m-^/res/-) {
                   5351: 	($udom,$uname) = 
                   5352: 	    ($uri =~ m-/(?:res)/?([^/]*)/?([^/]*)/-);
                   5353: 	$file = $uri;
                   5354:     }
                   5355: 
                   5356:     if (!$udom || !$uname || !$file) {
                   5357: 	# unable to handle the uri
                   5358: 	return ();
                   5359:     }
                   5360: 
                   5361:     my ($result) = &dirlist($file,$udom,$uname,$dir);
                   5362:     my @stats = split('&', $result);
1.721     banghart 5363:     
1.712     albertel 5364:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   5365: 	shift(@stats); #filename is first
                   5366: 	return @stats;
                   5367:     }
                   5368:     return ();
                   5369: }
                   5370: 
1.26      www      5371: # -------------------------------------------------------- Value of a Condition
                   5372: 
1.713     albertel 5373: # gets the value of a specific preevaluated condition
                   5374: #    stored in the string  $env{user.state.<cid>}
                   5375: # or looks up a condition reference in the bighash and if if hasn't
                   5376: # already been evaluated recurses into docondval to get the value of
                   5377: # the condition, then memoizing it to 
                   5378: #   $env{user.state.<cid>.<condition>}
1.40      www      5379: sub directcondval {
                   5380:     my $number=shift;
1.620     albertel 5381:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 5382: 	&Apache::lonuserstate::evalstate();
                   5383:     }
1.713     albertel 5384:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   5385: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   5386:     } elsif ($number =~ /^_/) {
                   5387: 	my $sub_condition;
                   5388: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   5389: 		&GDBM_READER(),0640)) {
                   5390: 	    $sub_condition=$bighash{'conditions'.$number};
                   5391: 	    untie(%bighash);
                   5392: 	}
                   5393: 	my $value = &docondval($sub_condition);
                   5394: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
                   5395: 	return $value;
                   5396:     }
1.620     albertel 5397:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   5398:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      5399:     } else {
                   5400:        return 2;
                   5401:     }
                   5402: }
                   5403: 
1.713     albertel 5404: # get the collection of conditions for this resource
1.26      www      5405: sub condval {
                   5406:     my $condidx=shift;
1.54      www      5407:     my $allpathcond='';
1.713     albertel 5408:     foreach my $cond (split(/\|/,$condidx)) {
                   5409: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   5410: 	    $allpathcond.=
                   5411: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   5412: 	}
1.191     harris41 5413:     }
1.54      www      5414:     $allpathcond=~s/\|$//;
1.713     albertel 5415:     return &docondval($allpathcond);
                   5416: }
                   5417: 
                   5418: #evaluates an expression of conditions
                   5419: sub docondval {
                   5420:     my ($allpathcond) = @_;
                   5421:     my $result=0;
                   5422:     if ($env{'request.course.id'}
                   5423: 	&& defined($allpathcond)) {
                   5424: 	my $operand='|';
                   5425: 	my @stack;
                   5426: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   5427: 	    if ($chunk eq '(') {
                   5428: 		push @stack,($operand,$result);
                   5429: 	    } elsif ($chunk eq ')') {
                   5430: 		my $before=pop @stack;
                   5431: 		if (pop @stack eq '&') {
                   5432: 		    $result=$result>$before?$before:$result;
                   5433: 		} else {
                   5434: 		    $result=$result>$before?$result:$before;
                   5435: 		}
                   5436: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   5437: 		$operand=$chunk;
                   5438: 	    } else {
                   5439: 		my $new=directcondval($chunk);
                   5440: 		if ($operand eq '&') {
                   5441: 		    $result=$result>$new?$new:$result;
                   5442: 		} else {
                   5443: 		    $result=$result>$new?$result:$new;
                   5444: 		}
                   5445: 	    }
                   5446: 	}
1.26      www      5447:     }
                   5448:     return $result;
1.421     albertel 5449: }
                   5450: 
                   5451: # ---------------------------------------------------- Devalidate courseresdata
                   5452: 
                   5453: sub devalidatecourseresdata {
                   5454:     my ($coursenum,$coursedomain)=@_;
                   5455:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 5456:     &devalidate_cache_new('courseres',$hashid);
1.28      www      5457: }
                   5458: 
1.763     www      5459: 
1.200     www      5460: # --------------------------------------------------- Course Resourcedata Query
                   5461: 
1.624     albertel 5462: sub get_courseresdata {
                   5463:     my ($coursenum,$coursedomain)=@_;
1.200     www      5464:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   5465:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 5466:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 5467:     my %dumpreply;
1.417     albertel 5468:     unless (defined($cached)) {
1.624     albertel 5469: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 5470: 	$result=\%dumpreply;
1.251     albertel 5471: 	my ($tmp) = keys(%dumpreply);
                   5472: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 5473: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 5474: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   5475: 	    return $tmp;
1.416     albertel 5476: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 5477: 	    $result=undef;
1.599     albertel 5478: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 5479: 	}
                   5480:     }
1.624     albertel 5481:     return $result;
                   5482: }
                   5483: 
1.633     albertel 5484: sub devalidateuserresdata {
                   5485:     my ($uname,$udom)=@_;
                   5486:     my $hashid="$udom:$uname";
                   5487:     &devalidate_cache_new('userres',$hashid);
                   5488: }
                   5489: 
1.624     albertel 5490: sub get_userresdata {
                   5491:     my ($uname,$udom)=@_;
                   5492:     #most student don\'t have any data set, check if there is some data
                   5493:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   5494: 
                   5495:     my $hashid="$udom:$uname";
                   5496:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   5497:     if (!defined($cached)) {
                   5498: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   5499: 	$result=\%resourcedata;
                   5500: 	&do_cache_new('userres',$hashid,$result,600);
                   5501:     }
                   5502:     my ($tmp)=keys(%$result);
                   5503:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   5504: 	return $result;
                   5505:     }
                   5506:     #error 2 occurs when the .db doesn't exist
                   5507:     if ($tmp!~/error: 2 /) {
1.672     albertel 5508: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 5509: 		 " Trying to get resource data for ".
                   5510: 		 $uname." at ".$udom.": ".
                   5511: 		 $tmp."</font>");
                   5512:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 5513: 	#&EXT_cache_set($udom,$uname);
                   5514: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 5515: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 5516:     }
                   5517:     return $tmp;
                   5518: }
                   5519: 
                   5520: sub resdata {
                   5521:     my ($name,$domain,$type,@which)=@_;
                   5522:     my $result;
                   5523:     if ($type eq 'course') {
                   5524: 	$result=&get_courseresdata($name,$domain);
                   5525:     } elsif ($type eq 'user') {
                   5526: 	$result=&get_userresdata($name,$domain);
                   5527:     }
                   5528:     if (!ref($result)) { return $result; }    
1.251     albertel 5529:     foreach my $item (@which) {
1.417     albertel 5530: 	if (defined($result->{$item})) {
                   5531: 	    return $result->{$item};
1.251     albertel 5532: 	}
1.250     albertel 5533:     }
1.291     albertel 5534:     return undef;
1.200     www      5535: }
                   5536: 
1.379     matthew  5537: #
                   5538: # EXT resource caching routines
                   5539: #
                   5540: 
                   5541: sub clear_EXT_cache_status {
1.383     albertel 5542:     &delenv('cache.EXT.');
1.379     matthew  5543: }
                   5544: 
                   5545: sub EXT_cache_status {
                   5546:     my ($target_domain,$target_user) = @_;
1.383     albertel 5547:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 5548:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  5549:         # We know already the user has no data
                   5550:         return 1;
                   5551:     } else {
                   5552:         return 0;
                   5553:     }
                   5554: }
                   5555: 
                   5556: sub EXT_cache_set {
                   5557:     my ($target_domain,$target_user) = @_;
1.383     albertel 5558:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.633     albertel 5559:     #&appenv($cachename => time);
1.379     matthew  5560: }
                   5561: 
1.28      www      5562: # --------------------------------------------------------- Value of a Variable
1.58      www      5563: sub EXT {
1.715     albertel 5564: 
1.395     albertel 5565:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      5566:     unless ($varname) { return ''; }
1.218     albertel 5567:     #get real user name/domain, courseid and symb
                   5568:     my $courseid;
1.359     albertel 5569:     my $publicuser;
1.427     www      5570:     if ($symbparm) {
                   5571: 	$symbparm=&get_symb_from_alias($symbparm);
                   5572:     }
1.218     albertel 5573:     if (!($uname && $udom)) {
1.790     albertel 5574:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 5575:       if (!$symbparm) {	$symbparm=$cursymb; }
                   5576:     } else {
1.620     albertel 5577: 	$courseid=$env{'request.course.id'};
1.218     albertel 5578:     }
1.48      www      5579:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   5580:     my $rest;
1.320     albertel 5581:     if (defined($therest[0])) {
1.48      www      5582:        $rest=join('.',@therest);
                   5583:     } else {
                   5584:        $rest='';
                   5585:     }
1.320     albertel 5586: 
1.57      www      5587:     my $qualifierrest=$qualifier;
                   5588:     if ($rest) { $qualifierrest.='.'.$rest; }
                   5589:     my $spacequalifierrest=$space;
                   5590:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      5591:     if ($realm eq 'user') {
1.48      www      5592: # --------------------------------------------------------------- user.resource
                   5593: 	if ($space eq 'resource') {
1.651     albertel 5594: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   5595: 		  || defined($Apache::lonhomework::parsing_a_task))
                   5596: 		 &&
1.744     albertel 5597: 		 ($symbparm eq &symbread()) ) {	
                   5598: 		# if we are in the middle of processing the resource the
                   5599: 		# get the value we are planning on committing
                   5600:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   5601:                     return $Apache::lonhomework::results{$qualifierrest};
                   5602:                 } else {
                   5603:                     return $Apache::lonhomework::history{$qualifierrest};
                   5604:                 }
1.335     albertel 5605: 	    } else {
1.359     albertel 5606: 		my %restored;
1.620     albertel 5607: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 5608: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   5609: 		} else {
                   5610: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   5611: 		}
1.335     albertel 5612: 		return $restored{$qualifierrest};
                   5613: 	    }
1.48      www      5614: # ----------------------------------------------------------------- user.access
                   5615:         } elsif ($space eq 'access') {
1.218     albertel 5616: 	    # FIXME - not supporting calls for a specific user
1.48      www      5617:             return &allowed($qualifier,$rest);
                   5618: # ------------------------------------------ user.preferences, user.environment
                   5619:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 5620: 	    if (($uname eq $env{'user.name'}) &&
                   5621: 		($udom eq $env{'user.domain'})) {
                   5622: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 5623: 	    } else {
1.359     albertel 5624: 		my %returnhash;
                   5625: 		if (!$publicuser) {
                   5626: 		    %returnhash=&userenvironment($udom,$uname,
                   5627: 						 $qualifierrest);
                   5628: 		}
1.218     albertel 5629: 		return $returnhash{$qualifierrest};
                   5630: 	    }
1.48      www      5631: # ----------------------------------------------------------------- user.course
                   5632:         } elsif ($space eq 'course') {
1.218     albertel 5633: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 5634:             return $env{join('.',('request.course',$qualifier))};
1.48      www      5635: # ------------------------------------------------------------------- user.role
                   5636:         } elsif ($space eq 'role') {
1.218     albertel 5637: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 5638:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      5639:             if ($qualifier eq 'value') {
                   5640: 		return $role;
                   5641:             } elsif ($qualifier eq 'extent') {
                   5642:                 return $where;
                   5643:             }
                   5644: # ----------------------------------------------------------------- user.domain
                   5645:         } elsif ($space eq 'domain') {
1.218     albertel 5646:             return $udom;
1.48      www      5647: # ------------------------------------------------------------------- user.name
                   5648:         } elsif ($space eq 'name') {
1.218     albertel 5649:             return $uname;
1.48      www      5650: # ---------------------------------------------------- Any other user namespace
1.29      www      5651:         } else {
1.359     albertel 5652: 	    my %reply;
                   5653: 	    if (!$publicuser) {
                   5654: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   5655: 	    }
                   5656: 	    return $reply{$qualifierrest};
1.48      www      5657:         }
1.236     www      5658:     } elsif ($realm eq 'query') {
                   5659: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 5660:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   5661: 						[$spacequalifierrest]);
1.620     albertel 5662: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      5663:    } elsif ($realm eq 'request') {
1.48      www      5664: # ------------------------------------------------------------- request.browser
                   5665:         if ($space eq 'browser') {
1.430     www      5666: 	    if ($qualifier eq 'textremote') {
1.676     albertel 5667: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      5668: 		    return 1;
                   5669: 		} else {
                   5670: 		    return 0;
                   5671: 		}
                   5672: 	    } else {
1.620     albertel 5673: 		return $env{'browser.'.$qualifier};
1.430     www      5674: 	    }
1.57      www      5675: # ------------------------------------------------------------ request.filename
                   5676:         } else {
1.620     albertel 5677:             return $env{'request.'.$spacequalifierrest};
1.29      www      5678:         }
1.28      www      5679:     } elsif ($realm eq 'course') {
1.48      www      5680: # ---------------------------------------------------------- course.description
1.620     albertel 5681:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      5682:     } elsif ($realm eq 'resource') {
1.165     www      5683: 
1.620     albertel 5684: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 5685: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   5686: 	}
1.693     albertel 5687: 
                   5688: 	if ($space eq 'title') {
                   5689: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   5690: 	    return &gettitle($symbparm);
                   5691: 	}
                   5692: 	
                   5693: 	if ($space eq 'map') {
                   5694: 	    my ($map) = &decode_symb($symbparm);
                   5695: 	    return &symbread($map);
                   5696: 	}
                   5697: 
                   5698: 	my ($section, $group, @groups);
1.593     albertel 5699: 	my ($courselevelm,$courselevel);
1.539     albertel 5700: 	if ($symbparm && defined($courseid) && 
1.620     albertel 5701: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      5702: 
1.218     albertel 5703: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      5704: 
1.60      www      5705: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 5706: 	    my $symbp=$symbparm;
1.735     albertel 5707: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 5708: 
                   5709: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   5710: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   5711: 
1.620     albertel 5712: 	    if (($env{'user.name'} eq $uname) &&
                   5713: 		($env{'user.domain'} eq $udom)) {
                   5714: 		$section=$env{'request.course.sec'};
1.733     raeburn  5715:                 @groups = split(/:/,$env{'request.course.groups'});  
                   5716:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 5717: 	    } else {
1.539     albertel 5718: 		if (! defined($usection)) {
1.551     albertel 5719: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 5720: 		} else {
                   5721: 		    $section = $usection;
                   5722: 		}
1.733     raeburn  5723:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 5724: 	    }
                   5725: 
                   5726: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   5727: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   5728: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   5729: 
1.593     albertel 5730: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 5731: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 5732: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      5733: 
1.60      www      5734: # ----------------------------------------------------------- first, check user
1.624     albertel 5735: 
                   5736: 	    my $userreply=&resdata($uname,$udom,'user',
                   5737: 				       ($courselevelr,$courselevelm,
                   5738: 					$courselevel));
                   5739: 	    if (defined($userreply)) { return $userreply; }
1.95      www      5740: 
1.594     albertel 5741: # ------------------------------------------------ second, check some of course
1.684     raeburn  5742:             my $coursereply;
1.691     raeburn  5743:             if (@groups > 0) {
                   5744:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   5745:                                        $mapparm,$spacequalifierrest);
1.684     raeburn  5746:                 if (defined($coursereply)) { return $coursereply; }
                   5747:             }
1.96      www      5748: 
1.684     raeburn  5749: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.624     albertel 5750: 				     $env{'course.'.$courseid.'.domain'},
                   5751: 				     'course',
                   5752: 				     ($seclevelr,$seclevelm,$seclevel,
                   5753: 				      $courselevelr));
1.287     albertel 5754: 	    if (defined($coursereply)) { return $coursereply; }
1.200     www      5755: 
1.60      www      5756: # ------------------------------------------------------ third, check map parms
1.218     albertel 5757: 	    my %parmhash=();
                   5758: 	    my $thisparm='';
                   5759: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 5760: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 5761: 		    &GDBM_READER(),0640)) {
1.218     albertel 5762: 		$thisparm=$parmhash{$symbparm};
                   5763: 		untie(%parmhash);
                   5764: 	    }
                   5765: 	    if ($thisparm) { return $thisparm; }
                   5766: 	}
1.594     albertel 5767: # ------------------------------------------ fourth, look in resource metadata
1.71      www      5768: 
1.218     albertel 5769: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 5770: 	my $filename;
                   5771: 	if (!$symbparm) { $symbparm=&symbread(); }
                   5772: 	if ($symbparm) {
1.409     www      5773: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 5774: 	} else {
1.620     albertel 5775: 	    $filename=$env{'request.filename'};
1.282     albertel 5776: 	}
                   5777: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.288     albertel 5778: 	if (defined($metadata)) { return $metadata; }
1.282     albertel 5779: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.288     albertel 5780: 	if (defined($metadata)) { return $metadata; }
1.142     www      5781: 
1.594     albertel 5782: # ---------------------------------------------- fourth, look in rest pf course
1.593     albertel 5783: 	if ($symbparm && defined($courseid) && 
1.620     albertel 5784: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 5785: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   5786: 				     $env{'course.'.$courseid.'.domain'},
                   5787: 				     'course',
                   5788: 				     ($courselevelm,$courselevel));
1.593     albertel 5789: 	    if (defined($coursereply)) { return $coursereply; }
                   5790: 	}
1.145     www      5791: # ------------------------------------------------------------------ Cascade up
1.218     albertel 5792: 	unless ($space eq '0') {
1.336     albertel 5793: 	    my @parts=split(/_/,$space);
                   5794: 	    my $id=pop(@parts);
                   5795: 	    my $part=join('_',@parts);
                   5796: 	    if ($part eq '') { $part='0'; }
                   5797: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 5798: 				 $symbparm,$udom,$uname,$section,1);
1.337     albertel 5799: 	    if (defined($partgeneral)) { return $partgeneral; }
1.218     albertel 5800: 	}
1.395     albertel 5801: 	if ($recurse) { return undef; }
                   5802: 	my $pack_def=&packages_tab_default($filename,$varname);
                   5803: 	if (defined($pack_def)) { return $pack_def; }
1.71      www      5804: 
1.48      www      5805: # ---------------------------------------------------- Any other user namespace
                   5806:     } elsif ($realm eq 'environment') {
                   5807: # ----------------------------------------------------------------- environment
1.620     albertel 5808: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   5809: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 5810: 	} else {
1.770     albertel 5811: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   5812: 		return '';
                   5813: 	    }
1.219     albertel 5814: 	    my %returnhash=&userenvironment($udom,$uname,
                   5815: 					    $spacequalifierrest);
                   5816: 	    return $returnhash{$spacequalifierrest};
                   5817: 	}
1.28      www      5818:     } elsif ($realm eq 'system') {
1.48      www      5819: # ----------------------------------------------------------------- system.time
                   5820: 	if ($space eq 'time') {
                   5821: 	    return time;
                   5822:         }
1.696     albertel 5823:     } elsif ($realm eq 'server') {
                   5824: # ----------------------------------------------------------------- system.time
                   5825: 	if ($space eq 'name') {
                   5826: 	    return $ENV{'SERVER_NAME'};
                   5827:         }
1.28      www      5828:     }
1.48      www      5829:     return '';
1.61      www      5830: }
                   5831: 
1.691     raeburn  5832: sub check_group_parms {
                   5833:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   5834:     my @groupitems = ();
                   5835:     my $resultitem;
                   5836:     my @levels = ($symbparm,$mapparm,$what);
                   5837:     foreach my $group (@{$groups}) {
                   5838:         foreach my $level (@levels) {
                   5839:              my $item = $courseid.'.['.$group.'].'.$level;
                   5840:              push(@groupitems,$item);
                   5841:         }
                   5842:     }
                   5843:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   5844:                             $env{'course.'.$courseid.'.domain'},
                   5845:                                      'course',@groupitems);
                   5846:     return $coursereply;
                   5847: }
                   5848: 
                   5849: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  5850:     my ($courseid,@groups) = @_;
                   5851:     @groups = sort(@groups);
1.691     raeburn  5852:     return @groups;
                   5853: }
                   5854: 
1.395     albertel 5855: sub packages_tab_default {
                   5856:     my ($uri,$varname)=@_;
                   5857:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 5858: 
                   5859:     my (@extension,@specifics,$do_default);
                   5860:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 5861: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 5862: 	if ($pack_type eq 'default') {
                   5863: 	    $do_default=1;
                   5864: 	} elsif ($pack_type eq 'extension') {
                   5865: 	    push(@extension,[$package,$pack_type,$pack_part]);
                   5866: 	} else {
                   5867: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   5868: 	}
                   5869:     }
                   5870:     # first look for a package that matches the requested part id
                   5871:     foreach my $package (@specifics) {
                   5872: 	my (undef,$pack_type,$pack_part)=@{$package};
                   5873: 	next if ($pack_part ne $part);
                   5874: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   5875: 	    return $packagetab{"$pack_type&$name&default"};
                   5876: 	}
                   5877:     }
                   5878:     # look for any possible matching non extension_ package
                   5879:     foreach my $package (@specifics) {
                   5880: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 5881: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   5882: 	    return $packagetab{"$pack_type&$name&default"};
                   5883: 	}
1.585     albertel 5884: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 5885: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   5886: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 5887: 	}
                   5888:     }
1.738     albertel 5889:     # look for any posible extension_ match
                   5890:     foreach my $package (@extension) {
                   5891: 	my ($package,$pack_type)=@{$package};
                   5892: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   5893: 	    return $packagetab{"$pack_type&$name&default"};
                   5894: 	}
                   5895: 	if (defined($packagetab{$package."&$name&default"})) {
                   5896: 	    return $packagetab{$package."&$name&default"};
                   5897: 	}
                   5898:     }
                   5899:     # look for a global default setting
                   5900:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   5901: 	return $packagetab{"default&$name&default"};
                   5902:     }
1.395     albertel 5903:     return undef;
                   5904: }
                   5905: 
1.334     albertel 5906: sub add_prefix_and_part {
                   5907:     my ($prefix,$part)=@_;
                   5908:     my $keyroot;
                   5909:     if (defined($prefix) && $prefix !~ /^__/) {
                   5910: 	# prefix that has a part already
                   5911: 	$keyroot=$prefix;
                   5912:     } elsif (defined($prefix)) {
                   5913: 	# prefix that is missing a part
                   5914: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   5915:     } else {
                   5916: 	# no prefix at all
                   5917: 	if (defined($part)) { $keyroot='_'.$part; }
                   5918:     }
                   5919:     return $keyroot;
                   5920: }
                   5921: 
1.71      www      5922: # ---------------------------------------------------------------- Get metadata
                   5923: 
1.599     albertel 5924: my %metaentry;
1.71      www      5925: sub metadata {
1.176     www      5926:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      5927:     $uri=&declutter($uri);
1.288     albertel 5928:     # if it is a non metadata possible uri return quickly
1.529     albertel 5929:     if (($uri eq '') || 
                   5930: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 5931: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.423     albertel 5932:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
1.489     albertel 5933: 	($uri =~ m|home/[^/]+/public_html/|)) {
1.468     albertel 5934: 	return undef;
1.288     albertel 5935:     }
1.73      www      5936:     my $filename=$uri;
                   5937:     $uri=~s/\.meta$//;
1.172     www      5938: #
                   5939: # Is the metadata already cached?
1.177     www      5940: # Look at timestamp of caching
1.172     www      5941: # Everything is cached by the main uri, libraries are never directly cached
                   5942: #
1.428     albertel 5943:     if (!defined($liburi)) {
1.599     albertel 5944: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 5945: 	if (defined($cached)) { return $result->{':'.$what}; }
                   5946:     }
                   5947:     {
1.172     www      5948: #
                   5949: # Is this a recursive call for a library?
                   5950: #
1.599     albertel 5951: #	if (! exists($metacache{$uri})) {
                   5952: #	    $metacache{$uri}={};
                   5953: #	}
1.171     www      5954:         if ($liburi) {
                   5955: 	    $liburi=&declutter($liburi);
                   5956:             $filename=$liburi;
1.401     bowersj2 5957:         } else {
1.599     albertel 5958: 	    &devalidate_cache_new('meta',$uri);
                   5959: 	    undef(%metaentry);
1.401     bowersj2 5960: 	}
1.140     www      5961:         my %metathesekeys=();
1.73      www      5962:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 5963: 	my $metastring;
1.768     albertel 5964: 	if ($uri !~ m -^(editupload)/-) {
1.543     albertel 5965: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 5966: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 5967: 	    $metastring=&getfile($file);
1.489     albertel 5968: 	}
1.208     albertel 5969:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      5970:         my $token;
1.140     www      5971:         undef %metathesekeys;
1.71      www      5972:         while ($token=$parser->get_token) {
1.339     albertel 5973: 	    if ($token->[0] eq 'S') {
                   5974: 		if (defined($token->[2]->{'package'})) {
1.172     www      5975: #
                   5976: # This is a package - get package info
                   5977: #
1.339     albertel 5978: 		    my $package=$token->[2]->{'package'};
                   5979: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   5980: 		    if (defined($token->[2]->{'id'})) { 
                   5981: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   5982: 		    }
1.599     albertel 5983: 		    if ($metaentry{':packages'}) {
                   5984: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 5985: 		    } else {
1.599     albertel 5986: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 5987: 		    }
1.736     albertel 5988: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 5989: 			my $part=$keyroot;
                   5990: 			$part=~s/^\_//;
1.736     albertel 5991: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   5992: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   5993: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 5994: 			    # ignore package.tab specified default values
                   5995:                             # here &package_tab_default() will fetch those
                   5996: 			    if ($subp eq 'default') { next; }
1.736     albertel 5997: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 5998: 			    my $unikey;
                   5999: 			    if ($pack =~ /_0$/) {
                   6000: 				$unikey='parameter_0_'.$name;
                   6001: 				$part=0;
                   6002: 			    } else {
                   6003: 				$unikey='parameter'.$keyroot.'_'.$name;
                   6004: 			    }
1.339     albertel 6005: 			    if ($subp eq 'display') {
                   6006: 				$value.=' [Part: '.$part.']';
                   6007: 			    }
1.599     albertel 6008: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 6009: 			    $metathesekeys{$unikey}=1;
1.599     albertel 6010: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6011: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 6012: 			    }
1.599     albertel 6013: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   6014: 				$metaentry{':'.$unikey}=
                   6015: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 6016: 			    }
1.339     albertel 6017: 			}
                   6018: 		    }
                   6019: 		} else {
1.172     www      6020: #
                   6021: # This is not a package - some other kind of start tag
1.339     albertel 6022: #
                   6023: 		    my $entry=$token->[1];
                   6024: 		    my $unikey;
                   6025: 		    if ($entry eq 'import') {
                   6026: 			$unikey='';
                   6027: 		    } else {
                   6028: 			$unikey=$entry;
                   6029: 		    }
                   6030: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6031: 
                   6032: 		    if (defined($token->[2]->{'id'})) { 
                   6033: 			$unikey.='_'.$token->[2]->{'id'}; 
                   6034: 		    }
1.175     www      6035: 
1.339     albertel 6036: 		    if ($entry eq 'import') {
1.175     www      6037: #
                   6038: # Importing a library here
1.339     albertel 6039: #
                   6040: 			if ($depthcount<20) {
                   6041: 			    my $location=$parser->get_text('/import');
                   6042: 			    my $dir=$filename;
                   6043: 			    $dir=~s|[^/]*$||;
                   6044: 			    $location=&filelocation($dir,$location);
1.736     albertel 6045: 			    my $metadata = 
                   6046: 				&metadata($uri,'keys', $location,$unikey,
                   6047: 					  $depthcount+1);
                   6048: 			    foreach my $meta (split(',',$metadata)) {
                   6049: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   6050: 				$metathesekeys{$meta}=1;
1.339     albertel 6051: 			    }
                   6052: 			}
                   6053: 		    } else { 
                   6054: 			
                   6055: 			if (defined($token->[2]->{'name'})) { 
                   6056: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   6057: 			}
                   6058: 			$metathesekeys{$unikey}=1;
1.736     albertel 6059: 			foreach my $param (@{$token->[3]}) {
                   6060: 			    $metaentry{':'.$unikey.'.'.$param} =
                   6061: 				$token->[2]->{$param};
1.339     albertel 6062: 			}
                   6063: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 6064: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 6065: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   6066: 		 # only ws inside the tag, and not in default, so use default
                   6067: 		 # as value
1.599     albertel 6068: 			    $metaentry{':'.$unikey}=$default;
1.339     albertel 6069: 			} else {
1.321     albertel 6070: 		  # either something interesting inside the tag or default
                   6071:                   # uninteresting
1.599     albertel 6072: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 6073: 			}
1.172     www      6074: # end of not-a-package not-a-library import
1.339     albertel 6075: 		    }
1.172     www      6076: # end of not-a-package start tag
1.339     albertel 6077: 		}
1.172     www      6078: # the next is the end of "start tag"
1.339     albertel 6079: 	    }
                   6080: 	}
1.483     albertel 6081: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.737     albertel 6082: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 6083: 	    #no specific packages #how's our extension
                   6084: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 6085: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 6086: 					 \%metathesekeys);
                   6087: 	}
1.599     albertel 6088: 	if (!exists($metaentry{':packages'})) {
1.737     albertel 6089: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 6090: 		#no specific packages well let's get default then
                   6091: 		if ($key!~/^default&/) { next; }
1.488     albertel 6092: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 6093: 					     \%metathesekeys);
                   6094: 	    }
                   6095: 	}
1.338     www      6096: # are there custom rights to evaluate
1.599     albertel 6097: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 6098: 
1.338     www      6099:     #
                   6100:     # Importing a rights file here
1.339     albertel 6101:     #
                   6102: 	    unless ($depthcount) {
1.599     albertel 6103: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 6104: 		my $dir=$filename;
                   6105: 		$dir=~s|[^/]*$||;
                   6106: 		$location=&filelocation($dir,$location);
1.736     albertel 6107: 		my $rights_metadata =
                   6108: 		    &metadata($uri,'keys',$location,'_rights',
                   6109: 			      $depthcount+1);
                   6110: 		foreach my $rights (split(',',$rights_metadata)) {
                   6111: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   6112: 		    $metathesekeys{$rights}=1;
1.339     albertel 6113: 		}
                   6114: 	    }
                   6115: 	}
1.737     albertel 6116: 	# uniqifiy package listing
                   6117: 	my %seen;
                   6118: 	my @uniq_packages =
                   6119: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   6120: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   6121: 
                   6122: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 6123: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   6124: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.699     albertel 6125: 	&do_cache_new('meta',$uri,\%metaentry,60*60);
1.177     www      6126: # this is the end of "was not already recently cached
1.71      www      6127:     }
1.599     albertel 6128:     return $metaentry{':'.$what};
1.261     albertel 6129: }
                   6130: 
1.488     albertel 6131: sub metadata_create_package_def {
1.483     albertel 6132:     my ($uri,$key,$package,$metathesekeys)=@_;
                   6133:     my ($pack,$name,$subp)=split(/\&/,$key);
                   6134:     if ($subp eq 'default') { next; }
                   6135:     
1.599     albertel 6136:     if (defined($metaentry{':packages'})) {
                   6137: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 6138:     } else {
1.599     albertel 6139: 	$metaentry{':packages'}=$package;
1.483     albertel 6140:     }
                   6141:     my $value=$packagetab{$key};
                   6142:     my $unikey;
                   6143:     $unikey='parameter_0_'.$name;
1.599     albertel 6144:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 6145:     $$metathesekeys{$unikey}=1;
1.599     albertel 6146:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6147: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 6148:     }
1.599     albertel 6149:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   6150: 	$metaentry{':'.$unikey}=
                   6151: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 6152:     }
                   6153: }
                   6154: 
1.261     albertel 6155: sub metadata_generate_part0 {
                   6156:     my ($metadata,$metacache,$uri) = @_;
                   6157:     my %allnames;
1.737     albertel 6158:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 6159: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 6160: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   6161: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 6162: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 6163: 	    $allnames{$name}=$part;
                   6164: 	  }
                   6165: 	}
                   6166:     }
                   6167:     foreach my $name (keys(%allnames)) {
                   6168:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 6169:       my $key=":parameter_0_$name";
1.261     albertel 6170:       $$metacache{"$key.part"}='0';
                   6171:       $$metacache{"$key.name"}=$name;
1.428     albertel 6172:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 6173: 					   $allnames{$name}.'_'.$name.
                   6174: 					   '.type'};
1.428     albertel 6175:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 6176: 			     '.display'};
1.644     www      6177:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 6178:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 6179:       $$metacache{"$key.display"}=$olddis;
                   6180:     }
1.71      www      6181: }
                   6182: 
1.764     albertel 6183: # ------------------------------------------------------ Devalidate title cache
                   6184: 
                   6185: sub devalidate_title_cache {
                   6186:     my ($url)=@_;
                   6187:     if (!$env{'request.course.id'}) { return; }
                   6188:     my $symb=&symbread($url);
                   6189:     if (!$symb) { return; }
                   6190:     my $key=$env{'request.course.id'}."\0".$symb;
                   6191:     &devalidate_cache_new('title',$key);
                   6192: }
                   6193: 
1.301     www      6194: # ------------------------------------------------- Get the title of a resource
                   6195: 
                   6196: sub gettitle {
                   6197:     my $urlsymb=shift;
                   6198:     my $symb=&symbread($urlsymb);
1.534     albertel 6199:     if ($symb) {
1.620     albertel 6200: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 6201: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 6202: 	if (defined($cached)) { 
                   6203: 	    return $result;
                   6204: 	}
1.534     albertel 6205: 	my ($map,$resid,$url)=&decode_symb($symb);
                   6206: 	my $title='';
                   6207: 	my %bighash;
1.620     albertel 6208: 	if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.534     albertel 6209: 		&GDBM_READER(),0640)) {
                   6210: 	    my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   6211: 	    $title=$bighash{'title_'.$mapid.'.'.$resid};
                   6212: 	    untie %bighash;
                   6213: 	}
                   6214: 	$title=~s/\&colon\;/\:/gs;
                   6215: 	if ($title) {
1.599     albertel 6216: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 6217: 	}
                   6218: 	$urlsymb=$url;
                   6219:     }
                   6220:     my $title=&metadata($urlsymb,'title');
                   6221:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   6222:     return $title;
1.301     www      6223: }
1.613     albertel 6224: 
1.614     albertel 6225: sub get_slot {
                   6226:     my ($which,$cnum,$cdom)=@_;
                   6227:     if (!$cnum || !$cdom) {
1.790     albertel 6228: 	(undef,my $courseid)=&whichuser();
1.620     albertel 6229: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   6230: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 6231:     }
1.703     albertel 6232:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   6233:     my %slotinfo;
                   6234:     if (exists($remembered{$key})) {
                   6235: 	$slotinfo{$which} = $remembered{$key};
                   6236:     } else {
                   6237: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   6238: 	&Apache::lonhomework::showhash(%slotinfo);
                   6239: 	my ($tmp)=keys(%slotinfo);
                   6240: 	if ($tmp=~/^error:/) { return (); }
                   6241: 	$remembered{$key} = $slotinfo{$which};
                   6242:     }
1.616     albertel 6243:     if (ref($slotinfo{$which}) eq 'HASH') {
                   6244: 	return %{$slotinfo{$which}};
                   6245:     }
                   6246:     return $slotinfo{$which};
1.614     albertel 6247: }
1.31      www      6248: # ------------------------------------------------- Update symbolic store links
                   6249: 
                   6250: sub symblist {
                   6251:     my ($mapname,%newhash)=@_;
1.438     www      6252:     $mapname=&deversion(&declutter($mapname));
1.31      www      6253:     my %hash;
1.620     albertel 6254:     if (($env{'request.course.fn'}) && (%newhash)) {
                   6255:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6256:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 6257: 	    foreach my $url (keys %newhash) {
                   6258: 		next if ($url eq 'last_known'
                   6259: 			 && $env{'form.no_update_last_known'});
                   6260: 		$hash{declutter($url)}=&encode_symb($mapname,
                   6261: 						    $newhash{$url}->[1],
                   6262: 						    $newhash{$url}->[0]);
1.191     harris41 6263:             }
1.31      www      6264:             if (untie(%hash)) {
                   6265: 		return 'ok';
                   6266:             }
                   6267:         }
                   6268:     }
                   6269:     return 'error';
1.212     www      6270: }
                   6271: 
                   6272: # --------------------------------------------------------------- Verify a symb
                   6273: 
                   6274: sub symbverify {
1.510     www      6275:     my ($symb,$thisurl)=@_;
                   6276:     my $thisfn=$thisurl;
1.439     www      6277:     $thisfn=&declutter($thisfn);
1.215     www      6278: # direct jump to resource in page or to a sequence - will construct own symbs
                   6279:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   6280: # check URL part
1.409     www      6281:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      6282: 
1.431     www      6283:     unless ($url eq $thisfn) { return 0; }
1.213     www      6284: 
1.216     www      6285:     $symb=&symbclean($symb);
1.510     www      6286:     $thisurl=&deversion($thisurl);
1.439     www      6287:     $thisfn=&deversion($thisfn);
1.213     www      6288: 
                   6289:     my %bighash;
                   6290:     my $okay=0;
1.431     www      6291: 
1.620     albertel 6292:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6293:                             &GDBM_READER(),0640)) {
1.510     www      6294:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      6295:         unless ($ids) { 
1.510     www      6296:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      6297:         }
                   6298:         if ($ids) {
                   6299: # ------------------------------------------------------------------- Has ID(s)
                   6300: 	    foreach (split(/\,/,$ids)) {
1.644     www      6301: 	       my ($mapid,$resid)=split(/\./,$_);
1.216     www      6302:                if (
                   6303:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   6304:    eq $symb) { 
1.620     albertel 6305: 		   if (($env{'request.role.adv'}) ||
                   6306: 		       $bighash{'encrypted_'.$_} eq $env{'request.enc'}) {
1.582     albertel 6307: 		       $okay=1; 
                   6308: 		   }
                   6309: 	       }
1.216     www      6310: 	   }
                   6311:         }
1.213     www      6312: 	untie(%bighash);
                   6313:     }
                   6314:     return $okay;
1.31      www      6315: }
                   6316: 
1.210     www      6317: # --------------------------------------------------------------- Clean-up symb
                   6318: 
                   6319: sub symbclean {
                   6320:     my $symb=shift;
1.568     albertel 6321:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      6322: # remove version from map
                   6323:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      6324: 
1.210     www      6325: # remove version from URL
                   6326:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      6327: 
1.507     www      6328: # remove wrapper
                   6329: 
1.510     www      6330:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 6331:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      6332:     return $symb;
1.409     www      6333: }
                   6334: 
                   6335: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 6336: 
                   6337: sub encode_symb {
                   6338:     my ($map,$resid,$url)=@_;
                   6339:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   6340: }
1.409     www      6341: 
                   6342: sub decode_symb {
1.568     albertel 6343:     my $symb=shift;
                   6344:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   6345:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      6346:     return (&fixversion($map),$resid,&fixversion($url));
                   6347: }
                   6348: 
                   6349: sub fixversion {
                   6350:     my $fn=shift;
1.609     banghart 6351:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      6352:     my %bighash;
                   6353:     my $uri=&clutter($fn);
1.620     albertel 6354:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      6355: # is this cached?
1.599     albertel 6356:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      6357:     if (defined($cached)) { return $result; }
                   6358: # unfortunately not cached, or expired
1.620     albertel 6359:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      6360: 	    &GDBM_READER(),0640)) {
                   6361:  	if ($bighash{'version_'.$uri}) {
                   6362:  	    my $version=$bighash{'version_'.$uri};
1.444     www      6363:  	    unless (($version eq 'mostrecent') || 
                   6364: 		    ($version==&getversion($uri))) {
1.440     www      6365:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   6366:  	    }
                   6367:  	}
                   6368:  	untie %bighash;
1.413     www      6369:     }
1.599     albertel 6370:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      6371: }
                   6372: 
                   6373: sub deversion {
                   6374:     my $url=shift;
                   6375:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   6376:     return $url;
1.210     www      6377: }
                   6378: 
1.31      www      6379: # ------------------------------------------------------ Return symb list entry
                   6380: 
                   6381: sub symbread {
1.249     www      6382:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 6383:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 6384:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      6385: # no filename provided? try from environment
1.44      www      6386:     unless ($thisfn) {
1.620     albertel 6387:         if ($env{'request.symb'}) {
                   6388: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 6389: 	}
1.620     albertel 6390: 	$thisfn=$env{'request.filename'};
1.44      www      6391:     }
1.569     albertel 6392:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      6393: # is that filename actually a symb? Verify, clean, and return
                   6394:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 6395: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 6396: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 6397: 	}
1.242     www      6398:     }
1.44      www      6399:     $thisfn=declutter($thisfn);
1.31      www      6400:     my %hash;
1.37      www      6401:     my %bighash;
                   6402:     my $syval='';
1.620     albertel 6403:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  6404:         my $targetfn = $thisfn;
1.609     banghart 6405:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  6406:             $targetfn = 'adm/wrapper/'.$thisfn;
                   6407:         }
1.687     albertel 6408: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   6409: 	    $targetfn=$1;
                   6410: 	}
1.620     albertel 6411:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6412:                       &GDBM_READER(),0640)) {
1.481     raeburn  6413: 	    $syval=$hash{$targetfn};
1.37      www      6414:             untie(%hash);
                   6415:         }
                   6416: # ---------------------------------------------------------- There was an entry
                   6417:         if ($syval) {
1.601     albertel 6418: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 6419: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.601     albertel 6420: 		    #&appenv('request.ambiguous' => $thisfn);
1.620     albertel 6421: 		    #return $env{$cache_str}='';
1.601     albertel 6422: 		#}    
                   6423: 		#$syval.=$1;
                   6424: 	    #}
1.37      www      6425:         } else {
                   6426: # ------------------------------------------------------- Was not in symb table
1.620     albertel 6427:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6428:                             &GDBM_READER(),0640)) {
1.37      www      6429: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      6430:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      6431:               unless ($ids) { 
                   6432:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      6433:               }
                   6434:               unless ($ids) {
                   6435: # alias?
                   6436: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      6437:               }
1.37      www      6438:               if ($ids) {
                   6439: # ------------------------------------------------------------------- Has ID(s)
                   6440:                  my @possibilities=split(/\,/,$ids);
1.39      www      6441:                  if ($#possibilities==0) {
                   6442: # ----------------------------------------------- There is only one possibility
1.37      www      6443: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 6444: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6445: 						    $resid,$thisfn);
1.249     www      6446:                  } elsif (!$donotrecurse) {
1.39      www      6447: # ------------------------------------------ There is more than one possibility
                   6448:                      my $realpossible=0;
1.191     harris41 6449:                      foreach (@possibilities) {
1.39      www      6450: 			 my $file=$bighash{'src_'.$_};
                   6451:                          if (&allowed('bre',$file)) {
                   6452:          		    my ($mapid,$resid)=split(/\./,$_);
                   6453:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   6454: 				$realpossible++;
1.626     albertel 6455:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6456: 						    $resid,$thisfn);
1.39      www      6457:                             }
                   6458: 			 }
1.191     harris41 6459:                      }
1.39      www      6460: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      6461:                  } else {
                   6462:                      $syval='';
1.37      www      6463:                  }
                   6464: 	      }
                   6465:               untie(%bighash)
1.481     raeburn  6466:            }
1.31      www      6467:         }
1.62      www      6468:         if ($syval) {
1.620     albertel 6469: 	    return $env{$cache_str}=$syval;
1.62      www      6470:         }
1.31      www      6471:     }
1.44      www      6472:     &appenv('request.ambiguous' => $thisfn);
1.620     albertel 6473:     return $env{$cache_str}='';
1.31      www      6474: }
                   6475: 
                   6476: # ---------------------------------------------------------- Return random seed
                   6477: 
1.32      www      6478: sub numval {
                   6479:     my $txt=shift;
                   6480:     $txt=~tr/A-J/0-9/;
                   6481:     $txt=~tr/a-j/0-9/;
                   6482:     $txt=~tr/K-T/0-9/;
                   6483:     $txt=~tr/k-t/0-9/;
                   6484:     $txt=~tr/U-Z/0-5/;
                   6485:     $txt=~tr/u-z/0-5/;
                   6486:     $txt=~s/\D//g;
1.564     albertel 6487:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      6488:     return int($txt);
1.368     albertel 6489: }
                   6490: 
1.484     albertel 6491: sub numval2 {
                   6492:     my $txt=shift;
                   6493:     $txt=~tr/A-J/0-9/;
                   6494:     $txt=~tr/a-j/0-9/;
                   6495:     $txt=~tr/K-T/0-9/;
                   6496:     $txt=~tr/k-t/0-9/;
                   6497:     $txt=~tr/U-Z/0-5/;
                   6498:     $txt=~tr/u-z/0-5/;
                   6499:     $txt=~s/\D//g;
                   6500:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   6501:     my $total;
                   6502:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 6503:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 6504:     return int($total);
                   6505: }
                   6506: 
1.575     albertel 6507: sub numval3 {
                   6508:     use integer;
                   6509:     my $txt=shift;
                   6510:     $txt=~tr/A-J/0-9/;
                   6511:     $txt=~tr/a-j/0-9/;
                   6512:     $txt=~tr/K-T/0-9/;
                   6513:     $txt=~tr/k-t/0-9/;
                   6514:     $txt=~tr/U-Z/0-5/;
                   6515:     $txt=~tr/u-z/0-5/;
                   6516:     $txt=~s/\D//g;
                   6517:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   6518:     my $total;
                   6519:     foreach my $val (@txts) { $total+=$val; }
                   6520:     if ($_64bit) { $total=(($total<<32)>>32); }
                   6521:     return $total;
                   6522: }
                   6523: 
1.675     albertel 6524: sub digest {
                   6525:     my ($data)=@_;
                   6526:     my $digest=&Digest::MD5::md5($data);
                   6527:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   6528:     my ($e,$f);
                   6529:     {
                   6530:         use integer;
                   6531:         $e=($a+$b);
                   6532:         $f=($c+$d);
                   6533:         if ($_64bit) {
                   6534:             $e=(($e<<32)>>32);
                   6535:             $f=(($f<<32)>>32);
                   6536:         }
                   6537:     }
                   6538:     if (wantarray) {
                   6539: 	return ($e,$f);
                   6540:     } else {
                   6541: 	my $g;
                   6542: 	{
                   6543: 	    use integer;
                   6544: 	    $g=($e+$f);
                   6545: 	    if ($_64bit) {
                   6546: 		$g=(($g<<32)>>32);
                   6547: 	    }
                   6548: 	}
                   6549: 	return $g;
                   6550:     }
                   6551: }
                   6552: 
1.368     albertel 6553: sub latest_rnd_algorithm_id {
1.675     albertel 6554:     return '64bit5';
1.366     albertel 6555: }
1.32      www      6556: 
1.503     albertel 6557: sub get_rand_alg {
                   6558:     my ($courseid)=@_;
1.790     albertel 6559:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 6560:     if ($courseid) {
1.620     albertel 6561: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 6562:     }
                   6563:     return &latest_rnd_algorithm_id();
                   6564: }
                   6565: 
1.562     albertel 6566: sub validCODE {
                   6567:     my ($CODE)=@_;
                   6568:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   6569:     return 0;
                   6570: }
                   6571: 
1.491     albertel 6572: sub getCODE {
1.620     albertel 6573:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 6574:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   6575: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   6576: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 6577: 	return $Apache::lonhomework::history{'resource.CODE'};
                   6578:     }
                   6579:     return undef;
                   6580: }
                   6581: 
1.31      www      6582: sub rndseed {
1.155     albertel 6583:     my ($symb,$courseid,$domain,$username)=@_;
1.366     albertel 6584: 
1.790     albertel 6585:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.155     albertel 6586:     if (!$symb) {
1.366     albertel 6587: 	unless ($symb=$wsymb) { return time; }
                   6588:     }
                   6589:     if (!$courseid) { $courseid=$wcourseid; }
                   6590:     if (!$domain) { $domain=$wdomain; }
                   6591:     if (!$username) { $username=$wusername }
1.503     albertel 6592:     my $which=&get_rand_alg();
1.491     albertel 6593:     if (defined(&getCODE())) {
1.675     albertel 6594: 	if ($which eq '64bit5') {
                   6595: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   6596: 	} elsif ($which eq '64bit4') {
1.575     albertel 6597: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   6598: 	} else {
                   6599: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   6600: 	}
1.675     albertel 6601:     } elsif ($which eq '64bit5') {
                   6602: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 6603:     } elsif ($which eq '64bit4') {
                   6604: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 6605:     } elsif ($which eq '64bit3') {
                   6606: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 6607:     } elsif ($which eq '64bit2') {
                   6608: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 6609:     } elsif ($which eq '64bit') {
                   6610: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   6611:     }
                   6612:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   6613: }
                   6614: 
                   6615: sub rndseed_32bit {
                   6616:     my ($symb,$courseid,$domain,$username)=@_;
                   6617:     {
                   6618: 	use integer;
                   6619: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   6620: 	my $symbseed=numval($symb) << 22;
                   6621: 	my $namechck=unpack("%32C*",$username) << 17;
                   6622: 	my $nameseed=numval($username) << 12;
                   6623: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   6624: 	my $courseseed=unpack("%32C*",$courseid);
                   6625: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 6626: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6627: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 6628: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 6629: 	return $num;
                   6630:     }
                   6631: }
                   6632: 
                   6633: sub rndseed_64bit {
                   6634:     my ($symb,$courseid,$domain,$username)=@_;
                   6635:     {
                   6636: 	use integer;
                   6637: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   6638: 	my $symbseed=numval($symb) << 10;
                   6639: 	my $namechck=unpack("%32S*",$username);
                   6640: 	
                   6641: 	my $nameseed=numval($username) << 21;
                   6642: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   6643: 	my $courseseed=unpack("%32S*",$courseid);
                   6644: 	
                   6645: 	my $num1=$symbchck+$symbseed+$namechck;
                   6646: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6647: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6648: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 6649: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6650: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 6651: 	return "$num1,$num2";
1.155     albertel 6652:     }
1.366     albertel 6653: }
                   6654: 
1.443     albertel 6655: sub rndseed_64bit2 {
                   6656:     my ($symb,$courseid,$domain,$username)=@_;
                   6657:     {
                   6658: 	use integer;
                   6659: 	# strings need to be an even # of cahracters long, it it is odd the
                   6660:         # last characters gets thrown away
                   6661: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6662: 	my $symbseed=numval($symb) << 10;
                   6663: 	my $namechck=unpack("%32S*",$username.' ');
                   6664: 	
                   6665: 	my $nameseed=numval($username) << 21;
1.501     albertel 6666: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6667: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6668: 	
                   6669: 	my $num1=$symbchck+$symbseed+$namechck;
                   6670: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6671: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6672: 	#&logthis("rndseed :$num:$symb");
1.501     albertel 6673: 	return "$num1,$num2";
                   6674:     }
                   6675: }
                   6676: 
                   6677: sub rndseed_64bit3 {
                   6678:     my ($symb,$courseid,$domain,$username)=@_;
                   6679:     {
                   6680: 	use integer;
                   6681: 	# strings need to be an even # of cahracters long, it it is odd the
                   6682:         # last characters gets thrown away
                   6683: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6684: 	my $symbseed=numval2($symb) << 10;
                   6685: 	my $namechck=unpack("%32S*",$username.' ');
                   6686: 	
                   6687: 	my $nameseed=numval2($username) << 21;
1.443     albertel 6688: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6689: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6690: 	
                   6691: 	my $num1=$symbchck+$symbseed+$namechck;
                   6692: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6693: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6694: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 6695: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6696: 	
1.503     albertel 6697: 	return "$num1:$num2";
1.443     albertel 6698:     }
                   6699: }
                   6700: 
1.575     albertel 6701: sub rndseed_64bit4 {
                   6702:     my ($symb,$courseid,$domain,$username)=@_;
                   6703:     {
                   6704: 	use integer;
                   6705: 	# strings need to be an even # of cahracters long, it it is odd the
                   6706:         # last characters gets thrown away
                   6707: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6708: 	my $symbseed=numval3($symb) << 10;
                   6709: 	my $namechck=unpack("%32S*",$username.' ');
                   6710: 	
                   6711: 	my $nameseed=numval3($username) << 21;
                   6712: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6713: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6714: 	
                   6715: 	my $num1=$symbchck+$symbseed+$namechck;
                   6716: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6717: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6718: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 6719: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6720: 	
                   6721: 	return "$num1:$num2";
                   6722:     }
                   6723: }
                   6724: 
1.675     albertel 6725: sub rndseed_64bit5 {
                   6726:     my ($symb,$courseid,$domain,$username)=@_;
                   6727:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   6728:     return "$num1:$num2";
                   6729: }
                   6730: 
1.366     albertel 6731: sub rndseed_CODE_64bit {
                   6732:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 6733:     {
1.366     albertel 6734: 	use integer;
1.443     albertel 6735: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 6736: 	my $symbseed=numval2($symb);
1.491     albertel 6737: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   6738: 	my $CODEseed=numval(&getCODE());
1.443     albertel 6739: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 6740: 	my $num1=$symbseed+$CODEchck;
                   6741: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 6742: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   6743: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 6744: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   6745: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 6746: 	return "$num1:$num2";
1.366     albertel 6747:     }
                   6748: }
                   6749: 
1.575     albertel 6750: sub rndseed_CODE_64bit4 {
                   6751:     my ($symb,$courseid,$domain,$username)=@_;
                   6752:     {
                   6753: 	use integer;
                   6754: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   6755: 	my $symbseed=numval3($symb);
                   6756: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   6757: 	my $CODEseed=numval3(&getCODE());
                   6758: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6759: 	my $num1=$symbseed+$CODEchck;
                   6760: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 6761: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   6762: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 6763: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   6764: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   6765: 	return "$num1:$num2";
                   6766:     }
                   6767: }
                   6768: 
1.675     albertel 6769: sub rndseed_CODE_64bit5 {
                   6770:     my ($symb,$courseid,$domain,$username)=@_;
                   6771:     my $code = &getCODE();
                   6772:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   6773:     return "$num1:$num2";
                   6774: }
                   6775: 
1.366     albertel 6776: sub setup_random_from_rndseed {
                   6777:     my ($rndseed)=@_;
1.503     albertel 6778:     if ($rndseed =~/([,:])/) {
                   6779: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 6780: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   6781:     } else {
                   6782: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 6783:     }
1.36      albertel 6784: }
                   6785: 
1.474     albertel 6786: sub latest_receipt_algorithm_id {
                   6787:     return 'receipt2';
                   6788: }
                   6789: 
1.480     www      6790: sub recunique {
                   6791:     my $fucourseid=shift;
                   6792:     my $unique;
1.620     albertel 6793:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   6794: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      6795:     } else {
                   6796: 	$unique=$perlvar{'lonReceipt'};
                   6797:     }
                   6798:     return unpack("%32C*",$unique);
                   6799: }
                   6800: 
                   6801: sub recprefix {
                   6802:     my $fucourseid=shift;
                   6803:     my $prefix;
1.620     albertel 6804:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   6805: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      6806:     } else {
                   6807: 	$prefix=$perlvar{'lonHostID'};
                   6808:     }
                   6809:     return unpack("%32C*",$prefix);
                   6810: }
                   6811: 
1.76      www      6812: sub ireceipt {
1.474     albertel 6813:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.76      www      6814:     my $cuname=unpack("%32C*",$funame);
                   6815:     my $cudom=unpack("%32C*",$fudom);
                   6816:     my $cucourseid=unpack("%32C*",$fucourseid);
                   6817:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      6818:     my $cunique=&recunique($fucourseid);
1.474     albertel 6819:     my $cpart=unpack("%32S*",$part);
1.480     www      6820:     my $return =&recprefix($fucourseid).'-';
1.620     albertel 6821:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   6822: 	$env{'request.state'} eq 'construct') {
1.790     albertel 6823: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 6824: 			       
                   6825: 	$return.= ($cunique%$cuname+
                   6826: 		   $cunique%$cudom+
                   6827: 		   $cusymb%$cuname+
                   6828: 		   $cusymb%$cudom+
                   6829: 		   $cucourseid%$cuname+
                   6830: 		   $cucourseid%$cudom+
                   6831: 		   $cpart%$cuname+
                   6832: 		   $cpart%$cudom);
                   6833:     } else {
                   6834: 	$return.= ($cunique%$cuname+
                   6835: 		   $cunique%$cudom+
                   6836: 		   $cusymb%$cuname+
                   6837: 		   $cusymb%$cudom+
                   6838: 		   $cucourseid%$cuname+
                   6839: 		   $cucourseid%$cudom);
                   6840:     }
                   6841:     return $return;
1.76      www      6842: }
                   6843: 
                   6844: sub receipt {
1.474     albertel 6845:     my ($part)=@_;
1.790     albertel 6846:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 6847:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      6848: }
1.260     ng       6849: 
1.790     albertel 6850: sub whichuser {
                   6851:     my ($passedsymb)=@_;
                   6852:     my ($symb,$courseid,$domain,$name,$publicuser);
                   6853:     if (defined($env{'form.grade_symb'})) {
                   6854: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   6855: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   6856: 	if (!$allowed &&
                   6857: 	    exists($env{'request.course.sec'}) &&
                   6858: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   6859: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   6860: 			      '/'.$env{'request.course.sec'});
                   6861: 	}
                   6862: 	if ($allowed) {
                   6863: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   6864: 	    $courseid=$tmp_courseid;
                   6865: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   6866: 	    ($name)=&get_env_multiple('form.grade_username');
                   6867: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   6868: 	}
                   6869:     }
                   6870:     if (!$passedsymb) {
                   6871: 	$symb=&symbread();
                   6872:     } else {
                   6873: 	$symb=$passedsymb;
                   6874:     }
                   6875:     $courseid=$env{'request.course.id'};
                   6876:     $domain=$env{'user.domain'};
                   6877:     $name=$env{'user.name'};
                   6878:     if ($name eq 'public' && $domain eq 'public') {
                   6879: 	if (!defined($env{'form.username'})) {
                   6880: 	    $env{'form.username'}.=time.rand(10000000);
                   6881: 	}
                   6882: 	$name.=$env{'form.username'};
                   6883:     }
                   6884:     return ($symb,$courseid,$domain,$name,$publicuser);
                   6885: 
                   6886: }
                   6887: 
1.36      albertel 6888: # ------------------------------------------------------------ Serves up a file
1.472     albertel 6889: # returns either the contents of the file or 
                   6890: # -1 if the file doesn't exist
1.481     raeburn  6891: #
                   6892: # if the target is a file that was uploaded via DOCS, 
                   6893: # a check will be made to see if a current copy exists on the local server,
                   6894: # if it does this will be served, otherwise a copy will be retrieved from
                   6895: # the home server for the course and stored in /home/httpd/html/userfiles on
                   6896: # the local server.   
1.472     albertel 6897: 
1.36      albertel 6898: sub getfile {
1.538     albertel 6899:     my ($file) = @_;
1.609     banghart 6900:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 6901:     &repcopy($file);
                   6902:     return &readfile($file);
                   6903: }
                   6904: 
                   6905: sub repcopy_userfile {
                   6906:     my ($file)=@_;
1.609     banghart 6907:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 6908:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 6909:     my ($cdom,$cnum,$filename) = 
                   6910: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+([^/]+)/+([^/]+)/+(.*)|);
                   6911:     my ($info,$rtncode);
                   6912:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   6913:     if (-e "$file") {
                   6914: 	my @fileinfo = stat($file);
                   6915: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 6916: 	if ($lwpresp ne 'ok') {
                   6917: 	    if ($rtncode eq '404') {
1.538     albertel 6918: 		unlink($file);
1.482     albertel 6919: 	    }
1.517     albertel 6920: 	    #my $ua=new LWP::UserAgent;
1.538     albertel 6921: 	    #my $request=new HTTP::Request('GET',&tokenwrapper($uri));
1.517     albertel 6922: 	    #my $response=$ua->request($request);
                   6923: 	    #if ($response->is_success()) {
                   6924: 	#	return $response->content;
                   6925: 	#    } else {
                   6926: 	#	return -1;
                   6927: 	#    }
1.482     albertel 6928: 	    return -1;
                   6929: 	}
                   6930: 	if ($info < $fileinfo[9]) {
1.607     raeburn  6931: 	    return 'ok';
1.482     albertel 6932: 	}
                   6933: 	$info = '';
1.538     albertel 6934: 	$lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 6935: 	if ($lwpresp ne 'ok') {
                   6936: 	    return -1;
                   6937: 	}
                   6938:     } else {
1.538     albertel 6939: 	my $lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 6940: 	if ($lwpresp ne 'ok') {
1.517     albertel 6941: 	    my $ua=new LWP::UserAgent;
1.538     albertel 6942: 	    my $request=new HTTP::Request('GET',&tokenwrapper($uri));
1.517     albertel 6943: 	    my $response=$ua->request($request);
                   6944: 	    if ($response->is_success()) {
1.538     albertel 6945: 		$info=$response->content;
1.517     albertel 6946: 	    } else {
                   6947: 		return -1;
                   6948: 	    }
1.482     albertel 6949: 	}
                   6950: 	my @parts = ($cdom,$cnum); 
                   6951: 	if ($filename =~ m|^(.+)/[^/]+$|) {
                   6952: 	    push @parts, split(/\//,$1);
1.518     albertel 6953: 	}
1.538     albertel 6954: 	my $path = $perlvar{'lonDocRoot'}.'/userfiles';
1.482     albertel 6955: 	foreach my $part (@parts) {
                   6956: 	    $path .= '/'.$part;
                   6957: 	    if (!-e $path) {
                   6958: 		mkdir($path,0770);
                   6959: 	    }
                   6960: 	}
                   6961:     }
1.538     albertel 6962:     open(FILE,">$file");
1.482     albertel 6963:     print FILE $info;
                   6964:     close(FILE);
1.607     raeburn  6965:     return 'ok';
1.481     raeburn  6966: }
                   6967: 
1.517     albertel 6968: sub tokenwrapper {
                   6969:     my $uri=shift;
1.552     albertel 6970:     $uri=~s|^http\://([^/]+)||;
                   6971:     $uri=~s|^/||;
1.620     albertel 6972:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 6973:     my $token=$1;
1.552     albertel 6974:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   6975:     if ($udom && $uname && $file) {
                   6976: 	$file=~s|(\?\.*)*$||;
1.620     albertel 6977:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
1.552     albertel 6978:         return 'http://'.$hostname{ &homeserver($uname,$udom)}.'/'.$uri.
1.517     albertel 6979:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   6980:                                '&tokenissued='.$perlvar{'lonHostID'};
                   6981:     } else {
                   6982:         return '/adm/notfound.html';
                   6983:     }
                   6984: }
                   6985: 
1.481     raeburn  6986: sub getuploaded {
                   6987:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   6988:     $uri=~s/^\///;
                   6989:     $uri = 'http://'.$hostname{ &homeserver($cnum,$cdom)}.'/raw/'.$uri;
                   6990:     my $ua=new LWP::UserAgent;
                   6991:     my $request=new HTTP::Request($reqtype,$uri);
                   6992:     my $response=$ua->request($request);
                   6993:     $$rtncode = $response->code;
1.482     albertel 6994:     if (! $response->is_success()) {
                   6995: 	return 'failed';
                   6996:     }      
                   6997:     if ($reqtype eq 'HEAD') {
1.486     www      6998: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 6999:     } elsif ($reqtype eq 'GET') {
                   7000: 	$$info = $response->content;
1.472     albertel 7001:     }
1.482     albertel 7002:     return 'ok';
1.36      albertel 7003: }
                   7004: 
1.481     raeburn  7005: sub readfile {
                   7006:     my $file = shift;
                   7007:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   7008:     my $fh;
                   7009:     open($fh,"<$file");
                   7010:     my $a='';
                   7011:     while (<$fh>) { $a .=$_; }
                   7012:     return $a;
                   7013: }
                   7014: 
1.36      albertel 7015: sub filelocation {
1.590     banghart 7016:     my ($dir,$file) = @_;
                   7017:     my $location;
                   7018:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 7019: 
                   7020:     if ($file =~ m-^/adm/-) {
                   7021: 	$file=~s-^/adm/wrapper/-/-;
                   7022: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   7023:     }
1.590     banghart 7024:     if ($file=~m:^/~:) { # is a contruction space reference
                   7025:         $location = $file;
                   7026:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.649     albertel 7027:     } elsif ($file=~m:^/home/[^/]*/public_html/:) {
                   7028: 	# is a correct contruction space reference
                   7029:         $location = $file;
1.609     banghart 7030:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 7031:         my ($udom,$uname,$filename)=
1.609     banghart 7032:   	    ($file=~m -^/+(?:uploaded|editupload)/+([^/]+)/+([^/]+)/+(.*)$-);
1.590     banghart 7033:         my $home=&homeserver($uname,$udom);
                   7034:         my $is_me=0;
                   7035:         my @ids=&current_machine_ids();
                   7036:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   7037:         if ($is_me) {
1.740     www      7038:   	    $location=&propath($udom,$uname).
1.590     banghart 7039:   	      '/userfiles/'.$filename;
                   7040:         } else {
                   7041:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   7042:   	      $udom.'/'.$uname.'/'.$filename;
                   7043:         }
                   7044:     } else {
                   7045:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   7046:         $file=~s:^/res/:/:;
                   7047:         if ( !( $file =~ m:^/:) ) {
                   7048:             $location = $dir. '/'.$file;
                   7049:         } else {
                   7050:             $location = '/home/httpd/html/res'.$file;
                   7051:         }
1.59      albertel 7052:     }
1.590     banghart 7053:     $location=~s://+:/:g; # remove duplicate /
                   7054:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
                   7055:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   7056:     return $location;
1.46      www      7057: }
1.36      albertel 7058: 
1.46      www      7059: sub hreflocation {
                   7060:     my ($dir,$file)=@_;
1.460     albertel 7061:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666     albertel 7062: 	$file=filelocation($dir,$file);
1.700     albertel 7063:     } elsif ($file=~m-^/adm/-) {
                   7064: 	$file=~s-^/adm/wrapper/-/-;
                   7065: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 7066:     }
                   7067:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   7068: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   7069:     } elsif ($file=~m-/home/(\w+)/public_html/-) {
1.462     albertel 7070: 	$file=~s-^/home/(\w+)/public_html/-/~$1/-;
1.666     albertel 7071:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
                   7072: 	$file=~s-^/home/httpd/lonUsers/([^/]*)/./././([^/]*)/userfiles/
                   7073: 	    -/uploaded/$1/$2/-x;
1.46      www      7074:     }
1.462     albertel 7075:     return $file;
1.465     albertel 7076: }
                   7077: 
                   7078: sub current_machine_domains {
                   7079:     my $hostname=$hostname{$perlvar{'lonHostID'}};
                   7080:     my @domains;
                   7081:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  7082: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 7083: 	if ($hostname eq $name) {
                   7084: 	    push(@domains,$hostdom{$id});
                   7085: 	}
                   7086:     }
                   7087:     return @domains;
                   7088: }
                   7089: 
                   7090: sub current_machine_ids {
                   7091:     my $hostname=$hostname{$perlvar{'lonHostID'}};
                   7092:     my @ids;
                   7093:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  7094: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 7095: 	if ($hostname eq $name) {
                   7096: 	    push(@ids,$id);
                   7097: 	}
                   7098:     }
                   7099:     return @ids;
1.31      www      7100: }
                   7101: 
                   7102: # ------------------------------------------------------------- Declutters URLs
                   7103: 
                   7104: sub declutter {
                   7105:     my $thisfn=shift;
1.569     albertel 7106:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 7107:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      7108:     $thisfn=~s/^\///;
1.697     albertel 7109:     $thisfn=~s|^adm/wrapper/||;
                   7110:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      7111:     $thisfn=~s/^res\///;
1.235     www      7112:     $thisfn=~s/\?.+$//;
1.268     www      7113:     return $thisfn;
                   7114: }
                   7115: 
                   7116: # ------------------------------------------------------------- Clutter up URLs
                   7117: 
                   7118: sub clutter {
                   7119:     my $thisfn='/'.&declutter(shift);
1.609     banghart 7120:     unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) { 
1.270     www      7121:        $thisfn='/res'.$thisfn; 
                   7122:     }
1.694     albertel 7123:     if ($thisfn !~m|/adm|) {
1.695     albertel 7124: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 7125: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 7126: 	} else {
                   7127: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   7128: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 7129: 	    if ($embstyle eq 'ssi'
                   7130: 		|| ($embstyle eq 'hdn')
                   7131: 		|| ($embstyle eq 'rat')
                   7132: 		|| ($embstyle eq 'prv')
                   7133: 		|| ($embstyle eq 'ign')) {
                   7134: 		#do nothing with these
                   7135: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 7136: 		|| ($embstyle eq 'emb')
                   7137: 		|| ($embstyle eq 'wrp')) {
                   7138: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 7139: 	    } elsif ($embstyle eq 'unk'
                   7140: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 7141: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 7142: 	    } else {
1.718     www      7143: #		&logthis("Got a blank emb style");
1.695     albertel 7144: 	    }
1.694     albertel 7145: 	}
                   7146:     }
1.31      www      7147:     return $thisfn;
1.12      www      7148: }
                   7149: 
1.787     albertel 7150: sub clutter_with_no_wrapper {
                   7151:     my $uri = &clutter(shift);
                   7152:     if ($uri =~ m-^/adm/-) {
                   7153: 	$uri =~ s-^/adm/wrapper/-/-;
                   7154: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   7155:     }
                   7156:     return $uri;
                   7157: }
                   7158: 
1.557     albertel 7159: sub freeze_escape {
                   7160:     my ($value)=@_;
                   7161:     if (ref($value)) {
                   7162: 	$value=&nfreeze($value);
                   7163: 	return '__FROZEN__'.&escape($value);
                   7164:     }
                   7165:     return &escape($value);
                   7166: }
                   7167: 
1.11      www      7168: 
1.557     albertel 7169: sub thaw_unescape {
                   7170:     my ($value)=@_;
                   7171:     if ($value =~ /^__FROZEN__/) {
                   7172: 	substr($value,0,10,undef);
                   7173: 	$value=&unescape($value);
                   7174: 	return &thaw($value);
                   7175:     }
                   7176:     return &unescape($value);
                   7177: }
                   7178: 
1.436     albertel 7179: sub correct_line_ends {
                   7180:     my ($result)=@_;
                   7181:     $$result =~s/\r\n/\n/mg;
                   7182:     $$result =~s/\r/\n/mg;
1.415     albertel 7183: }
1.1       albertel 7184: # ================================================================ Main Program
                   7185: 
1.184     www      7186: sub goodbye {
1.204     albertel 7187:    &logthis("Starting Shut down");
1.443     albertel 7188: #not converted to using infrastruture and probably shouldn't be
1.599     albertel 7189:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&freeze(\%badServerCache))));
1.443     albertel 7190: #converted
1.599     albertel 7191: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
                   7192:    &logthis(sprintf("%-20s is %s",'%homecache',length(&freeze(\%homecache))));
                   7193: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&freeze(\%titlecache))));
                   7194: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&freeze(\%courseresdatacache))));
1.425     albertel 7195: #1.1 only
1.599     albertel 7196: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&freeze(\%userresdatacache))));
                   7197: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&freeze(\%getsectioncache))));
                   7198: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&freeze(\%courseresversioncache))));
                   7199: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&freeze(\%resversioncache))));
                   7200:    &logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
                   7201:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   7202:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      7203:    &flushcourselogs();
                   7204:    &logthis("Shutting down");
                   7205: }
                   7206: 
1.179     www      7207: BEGIN {
1.228     harris41 7208: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
1.195     www      7209:     unless ($readit) {
1.217     harris41 7210: {
1.781     raeburn  7211:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   7212:     %perlvar = (%perlvar,%{$configvars});
1.227     harris41 7213: }
1.1       albertel 7214: 
1.327     albertel 7215: # ------------------------------------------------------------ Read domain file
                   7216: {
                   7217:     %domaindescription = ();
                   7218:     %domain_auth_def = ();
                   7219:     %domain_auth_arg_def = ();
1.448     albertel 7220:     my $fh;
                   7221:     if (open($fh,"<".$Apache::lonnet::perlvar{'lonTabDir'}.'/domain.tab')) {
1.327     albertel 7222:        while (<$fh>) {
1.390     matthew  7223:            next if (/^(\#|\s*$)/);
                   7224: #           next if /^\#/;
1.327     albertel 7225:            chomp;
1.403     www      7226:            my ($domain, $domain_description, $def_auth, $def_auth_arg,
1.685     raeburn  7227: 	       $def_lang, $city, $longi, $lati, $primary) = split(/:/,$_);
1.403     www      7228: 	   $domain_auth_def{$domain}=$def_auth;
1.327     albertel 7229:            $domain_auth_arg_def{$domain}=$def_auth_arg;
1.403     www      7230: 	   $domaindescription{$domain}=$domain_description;
                   7231: 	   $domain_lang_def{$domain}=$def_lang;
                   7232: 	   $domain_city{$domain}=$city;
                   7233: 	   $domain_longi{$domain}=$longi;
                   7234: 	   $domain_lati{$domain}=$lati;
1.685     raeburn  7235:            $domain_primary{$domain}=$primary;
1.403     www      7236: 
1.448     albertel 7237:  #         &logthis("Domain.tab: $domain, $domain_auth_def{$domain}, $domain_auth_arg_def{$domain},$domaindescription{$domain}");
1.327     albertel 7238: #          &logthis("Domain.tab: $domain ".$domaindescription{$domain} );
1.448     albertel 7239: 	}
1.327     albertel 7240:     }
1.448     albertel 7241:     close ($fh);
1.327     albertel 7242: }
                   7243: 
                   7244: 
1.1       albertel 7245: # ------------------------------------------------------------- Read hosts file
                   7246: {
1.448     albertel 7247:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
1.1       albertel 7248: 
                   7249:     while (my $configline=<$config>) {
1.303     matthew  7250:        next if ($configline =~ /^(\#|\s*$)/);
1.154     www      7251:        chomp($configline);
1.595     albertel 7252:        my ($id,$domain,$role,$name)=split(/:/,$configline);
1.597     albertel 7253:        $name=~s/\s//g;
1.595     albertel 7254:        if ($id && $domain && $role && $name) {
1.252     albertel 7255: 	 $hostname{$id}=$name;
                   7256: 	 $hostdom{$id}=$domain;
                   7257: 	 if ($role eq 'library') { $libserv{$id}=$name; }
1.245     www      7258:        }
1.1       albertel 7259:     }
1.448     albertel 7260:     close($config);
1.619     albertel 7261:     # FIXME: dev server don't want this, production servers _do_ want this
1.654     albertel 7262:     #&get_iphost();
1.1       albertel 7263: }
                   7264: 
1.598     albertel 7265: sub get_iphost {
                   7266:     if (%iphost) { return %iphost; }
1.653     albertel 7267:     my %name_to_ip;
1.598     albertel 7268:     foreach my $id (keys(%hostname)) {
                   7269: 	my $name=$hostname{$id};
1.653     albertel 7270: 	my $ip;
                   7271: 	if (!exists($name_to_ip{$name})) {
                   7272: 	    $ip = gethostbyname($name);
                   7273: 	    if (!$ip || length($ip) ne 4) {
                   7274: 		&logthis("Skipping host $id name $name no IP found\n");
                   7275: 		next;
                   7276: 	    }
                   7277: 	    $ip=inet_ntoa($ip);
                   7278: 	    $name_to_ip{$name} = $ip;
                   7279: 	} else {
                   7280: 	    $ip = $name_to_ip{$name};
1.598     albertel 7281: 	}
                   7282: 	push(@{$iphost{$ip}},$id);
                   7283:     }
                   7284:     return %iphost;
                   7285: }
                   7286: 
1.1       albertel 7287: # ------------------------------------------------------ Read spare server file
                   7288: {
1.448     albertel 7289:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 7290: 
                   7291:     while (my $configline=<$config>) {
                   7292:        chomp($configline);
1.284     matthew  7293:        if ($configline) {
1.784     albertel 7294: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 7295: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 7296: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 7297:        }
                   7298:     }
1.448     albertel 7299:     close($config);
1.1       albertel 7300: }
1.11      www      7301: # ------------------------------------------------------------ Read permissions
                   7302: {
1.448     albertel 7303:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      7304: 
                   7305:     while (my $configline=<$config>) {
1.448     albertel 7306: 	chomp($configline);
                   7307: 	if ($configline) {
                   7308: 	    my ($role,$perm)=split(/ /,$configline);
                   7309: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   7310: 	}
1.11      www      7311:     }
1.448     albertel 7312:     close($config);
1.11      www      7313: }
                   7314: 
                   7315: # -------------------------------------------- Read plain texts for permissions
                   7316: {
1.448     albertel 7317:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      7318: 
                   7319:     while (my $configline=<$config>) {
1.448     albertel 7320: 	chomp($configline);
                   7321: 	if ($configline) {
1.742     raeburn  7322: 	    my ($short,@plain)=split(/:/,$configline);
                   7323:             %{$prp{$short}} = ();
                   7324: 	    if (@plain > 0) {
                   7325:                 $prp{$short}{'std'} = $plain[0];
                   7326:                 for (my $i=1; $i<@plain; $i++) {
                   7327:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   7328:                 }
                   7329:             }
1.448     albertel 7330: 	}
1.135     www      7331:     }
1.448     albertel 7332:     close($config);
1.135     www      7333: }
                   7334: 
                   7335: # ---------------------------------------------------------- Read package table
                   7336: {
1.448     albertel 7337:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      7338: 
                   7339:     while (my $configline=<$config>) {
1.483     albertel 7340: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 7341: 	chomp($configline);
                   7342: 	my ($short,$plain)=split(/:/,$configline);
                   7343: 	my ($pack,$name)=split(/\&/,$short);
                   7344: 	if ($plain ne '') {
                   7345: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   7346: 	    $packagetab{$short}=$plain; 
                   7347: 	}
1.11      www      7348:     }
1.448     albertel 7349:     close($config);
1.329     matthew  7350: }
                   7351: 
                   7352: # ------------- set up temporary directory
                   7353: {
                   7354:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   7355: 
1.11      www      7356: }
                   7357: 
1.794   ! albertel 7358: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
        !          7359: 				'compress_threshold'=> 20_000,
        !          7360:  			        });
1.185     www      7361: 
1.281     www      7362: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      7363: $dumpcount=0;
1.22      www      7364: 
1.163     harris41 7365: &logtouch();
1.672     albertel 7366: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      7367: $readit=1;
1.564     albertel 7368:     {
                   7369: 	use integer;
                   7370: 	my $test=(2**32)+1;
1.568     albertel 7371: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 7372: 	&logthis(" Detected 64bit platform ($_64bit)");
                   7373:     }
1.195     www      7374: }
1.1       albertel 7375: }
1.179     www      7376: 
1.1       albertel 7377: 1;
1.191     harris41 7378: __END__
                   7379: 
1.243     albertel 7380: =pod
                   7381: 
1.191     harris41 7382: =head1 NAME
                   7383: 
1.243     albertel 7384: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 7385: 
                   7386: =head1 SYNOPSIS
                   7387: 
1.243     albertel 7388: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 7389: 
                   7390:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   7391: 
1.243     albertel 7392: Common parameters:
                   7393: 
                   7394: =over 4
                   7395: 
                   7396: =item *
                   7397: 
                   7398: $uname : an internal username (if $cname expecting a course Id specifically)
                   7399: 
                   7400: =item *
                   7401: 
                   7402: $udom : a domain (if $cdom expecting a course's domain specifically)
                   7403: 
                   7404: =item *
                   7405: 
                   7406: $symb : a resource instance identifier
                   7407: 
                   7408: =item *
                   7409: 
                   7410: $namespace : the name of a .db file that contains the data needed or
                   7411: being set.
                   7412: 
                   7413: =back
                   7414: 
1.394     bowersj2 7415: =head1 OVERVIEW
1.191     harris41 7416: 
1.394     bowersj2 7417: lonnet provides subroutines which interact with the
                   7418: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   7419: about classes, users, and resources.
1.243     albertel 7420: 
                   7421: For many of these objects you can also use this to store data about
                   7422: them or modify them in various ways.
1.191     harris41 7423: 
1.394     bowersj2 7424: =head2 Symbs
1.191     harris41 7425: 
1.394     bowersj2 7426: To identify a specific instance of a resource, LON-CAPA uses symbols
                   7427: or "symbs"X<symb>. These identifiers are built from the URL of the
                   7428: map, the resource number of the resource in the map, and the URL of
                   7429: the resource itself. The latter is somewhat redundant, but might help
                   7430: if maps change.
                   7431: 
                   7432: An example is
                   7433: 
                   7434:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   7435: 
                   7436: The respective map entry is
                   7437: 
                   7438:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   7439:   title="Problem 2">
                   7440:  </resource>
                   7441: 
                   7442: Symbs are used by the random number generator, as well as to store and
                   7443: restore data specific to a certain instance of for example a problem.
                   7444: 
                   7445: =head2 Storing And Retrieving Data
                   7446: 
                   7447: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   7448: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   7449: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   7450: is is the non-critical message twin of cstore. These functions are for
                   7451: handlers to store a perl hash to a user's permanent data space in an
                   7452: easy manner, and to retrieve it again on another call. It is expected
                   7453: that a handler would use this once at the beginning to retrieve data,
                   7454: and then again once at the end to send only the new data back.
                   7455: 
                   7456: The data is stored in the user's data directory on the user's
                   7457: homeserver under the ID of the course.
                   7458: 
                   7459: The hash that is returned by restore will have all of the previous
                   7460: value for all of the elements of the hash.
                   7461: 
                   7462: Example:
                   7463: 
                   7464:  #creating a hash
                   7465:  my %hash;
                   7466:  $hash{'foo'}='bar';
                   7467: 
                   7468:  #storing it
                   7469:  &Apache::lonnet::cstore(\%hash);
                   7470: 
                   7471:  #changing a value
                   7472:  $hash{'foo'}='notbar';
                   7473: 
                   7474:  #adding a new value
                   7475:  $hash{'bar'}='foo';
                   7476:  &Apache::lonnet::cstore(\%hash);
                   7477: 
                   7478:  #retrieving the hash
                   7479:  my %history=&Apache::lonnet::restore();
                   7480: 
                   7481:  #print the hash
                   7482:  foreach my $key (sort(keys(%history))) {
                   7483:    print("\%history{$key} = $history{$key}");
                   7484:  }
                   7485: 
                   7486: Will print out:
1.191     harris41 7487: 
1.394     bowersj2 7488:  %history{1:foo} = bar
                   7489:  %history{1:keys} = foo:timestamp
                   7490:  %history{1:timestamp} = 990455579
                   7491:  %history{2:bar} = foo
                   7492:  %history{2:foo} = notbar
                   7493:  %history{2:keys} = foo:bar:timestamp
                   7494:  %history{2:timestamp} = 990455580
                   7495:  %history{bar} = foo
                   7496:  %history{foo} = notbar
                   7497:  %history{timestamp} = 990455580
                   7498:  %history{version} = 2
                   7499: 
                   7500: Note that the special hash entries C<keys>, C<version> and
                   7501: C<timestamp> were added to the hash. C<version> will be equal to the
                   7502: total number of versions of the data that have been stored. The
                   7503: C<timestamp> attribute will be the UNIX time the hash was
                   7504: stored. C<keys> is available in every historical section to list which
                   7505: keys were added or changed at a specific historical revision of a
                   7506: hash.
                   7507: 
                   7508: B<Warning>: do not store the hash that restore returns directly. This
                   7509: will cause a mess since it will restore the historical keys as if the
                   7510: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 7511: 
1.394     bowersj2 7512: Calling convention:
1.191     harris41 7513: 
1.394     bowersj2 7514:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   7515:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 7516: 
1.394     bowersj2 7517: For more detailed information, see lonnet specific documentation.
1.191     harris41 7518: 
1.394     bowersj2 7519: =head1 RETURN MESSAGES
1.191     harris41 7520: 
1.394     bowersj2 7521: =over 4
1.191     harris41 7522: 
1.394     bowersj2 7523: =item * B<con_lost>: unable to contact remote host
1.191     harris41 7524: 
1.394     bowersj2 7525: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   7526: when the connection is brought back up
1.191     harris41 7527: 
1.394     bowersj2 7528: =item * B<con_failed>: unable to contact remote host and unable to save message
                   7529: for later delivery
1.191     harris41 7530: 
1.394     bowersj2 7531: =item * B<error:>: an error a occured, a description of the error follows the :
1.191     harris41 7532: 
1.394     bowersj2 7533: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 7534: that was requested
1.191     harris41 7535: 
1.243     albertel 7536: =back
1.191     harris41 7537: 
1.243     albertel 7538: =head1 PUBLIC SUBROUTINES
1.191     harris41 7539: 
1.243     albertel 7540: =head2 Session Environment Functions
1.191     harris41 7541: 
1.243     albertel 7542: =over 4
1.191     harris41 7543: 
1.394     bowersj2 7544: =item * 
                   7545: X<appenv()>
                   7546: B<appenv(%hash)>: the value of %hash is written to
                   7547: the user envirnoment file, and will be restored for each access this
1.620     albertel 7548: user makes during this session, also modifies the %env for the current
1.394     bowersj2 7549: process
1.191     harris41 7550: 
                   7551: =item *
1.394     bowersj2 7552: X<delenv()>
                   7553: B<delenv($regexp)>: removes all items from the session
                   7554: environment file that matches the regular expression in $regexp. The
1.620     albertel 7555: values are also delted from the current processes %env.
1.191     harris41 7556: 
1.243     albertel 7557: =back
                   7558: 
                   7559: =head2 User Information
1.191     harris41 7560: 
1.243     albertel 7561: =over 4
1.191     harris41 7562: 
                   7563: =item *
1.394     bowersj2 7564: X<queryauthenticate()>
                   7565: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 7566: authentication scheme
                   7567: 
                   7568: =item *
1.394     bowersj2 7569: X<authenticate()>
                   7570: B<authenticate($uname,$upass,$udom)>: try to
                   7571: authenticate user from domain's lib servers (first use the current
                   7572: one). C<$upass> should be the users password.
1.191     harris41 7573: 
                   7574: =item *
1.394     bowersj2 7575: X<homeserver()>
                   7576: B<homeserver($uname,$udom)>: find the server which has
                   7577: the user's directory and files (there must be only one), this caches
                   7578: the answer, and also caches if there is a borken connection.
1.191     harris41 7579: 
                   7580: =item *
1.394     bowersj2 7581: X<idget()>
                   7582: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   7583: (IDs are a unique resource in a domain, there must be only 1 ID per
                   7584: username, and only 1 username per ID in a specific domain) (returns
                   7585: hash: id=>name,id=>name)
1.191     harris41 7586: 
                   7587: =item *
1.394     bowersj2 7588: X<idrget()>
                   7589: B<idrget($udom,@unames)>: find the IDs behind a list of
                   7590: usernames (returns hash: name=>id,name=>id)
1.191     harris41 7591: 
                   7592: =item *
1.394     bowersj2 7593: X<idput()>
                   7594: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 7595: 
                   7596: =item *
1.394     bowersj2 7597: X<rolesinit()>
                   7598: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 7599: 
                   7600: =item *
1.551     albertel 7601: X<getsection()>
                   7602: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 7603: course $cname, return section name/number or '' for "not in course"
                   7604: and '-1' for "no section"
                   7605: 
                   7606: =item *
1.394     bowersj2 7607: X<userenvironment()>
                   7608: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 7609: passed in @what from the requested user's environment, returns a hash
                   7610: 
                   7611: =back
                   7612: 
                   7613: =head2 User Roles
                   7614: 
                   7615: =over 4
                   7616: 
                   7617: =item *
                   7618: 
                   7619: allowed($priv,$uri) : check for a user privilege; returns codes for allowed
                   7620: actions
                   7621:  F: full access
                   7622:  U,I,K: authentication modes (cxx only)
                   7623:  '': forbidden
                   7624:  1: user needs to choose course
                   7625:  2: browse allowed
1.766     albertel 7626:  A: passphrase authentication needed
1.243     albertel 7627: 
                   7628: =item *
                   7629: 
                   7630: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   7631: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   7632: and course level
                   7633: 
                   7634: =item *
                   7635: 
                   7636: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   7637: explanation of a user role term
                   7638: 
                   7639: =back
                   7640: 
                   7641: =head2 User Modification
                   7642: 
                   7643: =over 4
                   7644: 
                   7645: =item *
                   7646: 
                   7647: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
                   7648: user for the level given by URL.  Optional start and end dates (leave empty
                   7649: string or zero for "no date")
1.191     harris41 7650: 
                   7651: =item *
                   7652: 
1.243     albertel 7653: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   7654: change a users, password, possible return values are: ok,
                   7655: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   7656: refused
1.191     harris41 7657: 
                   7658: =item *
                   7659: 
1.243     albertel 7660: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 7661: 
                   7662: =item *
                   7663: 
1.243     albertel 7664: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
                   7665: modify user
1.191     harris41 7666: 
                   7667: =item *
                   7668: 
1.286     matthew  7669: modifystudent
                   7670: 
                   7671: modify a students enrollment and identification information.
                   7672: The course id is resolved based on the current users environment.  
                   7673: This means the envoking user must be a course coordinator or otherwise
                   7674: associated with a course.
                   7675: 
1.297     matthew  7676: This call is essentially a wrapper for lonnet::modifyuser and
                   7677: lonnet::modify_student_enrollment
1.286     matthew  7678: 
                   7679: Inputs: 
                   7680: 
                   7681: =over 4
                   7682: 
                   7683: =item B<$udom> Students loncapa domain
                   7684: 
                   7685: =item B<$uname> Students loncapa login name
                   7686: 
                   7687: =item B<$uid> Students id/student number
                   7688: 
                   7689: =item B<$umode> Students authentication mode
                   7690: 
                   7691: =item B<$upass> Students password
                   7692: 
                   7693: =item B<$first> Students first name
                   7694: 
                   7695: =item B<$middle> Students middle name
                   7696: 
                   7697: =item B<$last> Students last name
                   7698: 
                   7699: =item B<$gene> Students generation
                   7700: 
                   7701: =item B<$usec> Students section in course
                   7702: 
                   7703: =item B<$end> Unix time of the roles expiration
                   7704: 
                   7705: =item B<$start> Unix time of the roles start date
                   7706: 
                   7707: =item B<$forceid> If defined, allow $uid to be changed
                   7708: 
                   7709: =item B<$desiredhome> server to use as home server for student
                   7710: 
                   7711: =back
1.297     matthew  7712: 
                   7713: =item *
                   7714: 
                   7715: modify_student_enrollment
                   7716: 
                   7717: Change a students enrollment status in a class.  The environment variable
                   7718: 'role.request.course' must be defined for this function to proceed.
                   7719: 
                   7720: Inputs:
                   7721: 
                   7722: =over 4
                   7723: 
                   7724: =item $udom, students domain
                   7725: 
                   7726: =item $uname, students name
                   7727: 
                   7728: =item $uid, students user id
                   7729: 
                   7730: =item $first, students first name
                   7731: 
                   7732: =item $middle
                   7733: 
                   7734: =item $last
                   7735: 
                   7736: =item $gene
                   7737: 
                   7738: =item $usec
                   7739: 
                   7740: =item $end
                   7741: 
                   7742: =item $start
                   7743: 
                   7744: =back
                   7745: 
1.191     harris41 7746: 
                   7747: =item *
                   7748: 
1.243     albertel 7749: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   7750: custom role; give a custom role to a user for the level given by URL.  Specify
                   7751: name and domain of role author, and role name
1.191     harris41 7752: 
                   7753: =item *
                   7754: 
1.243     albertel 7755: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 7756: 
                   7757: =item *
                   7758: 
1.243     albertel 7759: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   7760: 
                   7761: =back
                   7762: 
                   7763: =head2 Course Infomation
                   7764: 
                   7765: =over 4
1.191     harris41 7766: 
                   7767: =item *
                   7768: 
1.631     albertel 7769: coursedescription($courseid) : returns a hash of information about the
                   7770: specified course id, including all environment settings for the
                   7771: course, the description of the course will be in the hash under the
                   7772: key 'description'
1.191     harris41 7773: 
                   7774: =item *
                   7775: 
1.624     albertel 7776: resdata($name,$domain,$type,@which) : request for current parameter
                   7777: setting for a specific $type, where $type is either 'course' or 'user',
                   7778: @what should be a list of parameters to ask about. This routine caches
                   7779: answers for 5 minutes.
1.243     albertel 7780: 
                   7781: =back
                   7782: 
                   7783: =head2 Course Modification
                   7784: 
                   7785: =over 4
1.191     harris41 7786: 
                   7787: =item *
                   7788: 
1.243     albertel 7789: writecoursepref($courseid,%prefs) : write preferences (environment
                   7790: database) for a course
1.191     harris41 7791: 
                   7792: =item *
                   7793: 
1.243     albertel 7794: createcourse($udom,$description,$url) : make/modify course
                   7795: 
                   7796: =back
                   7797: 
                   7798: =head2 Resource Subroutines
                   7799: 
                   7800: =over 4
1.191     harris41 7801: 
                   7802: =item *
                   7803: 
1.243     albertel 7804: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 7805: 
                   7806: =item *
                   7807: 
1.243     albertel 7808: repcopy($filename) : subscribes to the requested file, and attempts to
                   7809: replicate from the owning library server, Might return
1.607     raeburn  7810: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   7811: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 7812: resource. Expects the local filesystem pathname
                   7813: (/home/httpd/html/res/....)
                   7814: 
                   7815: =back
                   7816: 
                   7817: =head2 Resource Information
                   7818: 
                   7819: =over 4
1.191     harris41 7820: 
                   7821: =item *
                   7822: 
1.243     albertel 7823: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   7824: a vairety of different possible values, $varname should be a request
                   7825: string, and the other parameters can be used to specify who and what
                   7826: one is asking about.
                   7827: 
                   7828: Possible values for $varname are environment.lastname (or other item
                   7829: from the envirnment hash), user.name (or someother aspect about the
                   7830: user), resource.0.maxtries (or some other part and parameter of a
                   7831: resource)
1.204     albertel 7832: 
                   7833: =item *
                   7834: 
1.243     albertel 7835: directcondval($number) : get current value of a condition; reads from a state
                   7836: string
1.204     albertel 7837: 
                   7838: =item *
                   7839: 
1.243     albertel 7840: condval($condidx) : value of condition index based on state
1.204     albertel 7841: 
                   7842: =item *
                   7843: 
1.243     albertel 7844: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   7845: resource's metadata, $what should be either a specific key, or either
                   7846: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   7847: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   7848: 
                   7849: this function automatically caches all requests
1.191     harris41 7850: 
                   7851: =item *
                   7852: 
1.243     albertel 7853: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   7854: network of library servers; returns file handle of where SQL and regex results
                   7855: will be stored for query
1.191     harris41 7856: 
                   7857: =item *
                   7858: 
1.243     albertel 7859: symbread($filename) : return symbolic list entry (filename argument optional);
                   7860: returns the data handle
1.191     harris41 7861: 
                   7862: =item *
                   7863: 
1.243     albertel 7864: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 7865: a possible symb for the URL in $thisfn, and if is an encryypted
                   7866: resource that the user accessed using /enc/ returns a 1 on success, 0
                   7867: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 7868: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 7869: 
1.191     harris41 7870: 
                   7871: =item *
                   7872: 
1.243     albertel 7873: symbclean($symb) : removes versions numbers from a symb, returns the
                   7874: cleaned symb
1.191     harris41 7875: 
                   7876: =item *
                   7877: 
1.243     albertel 7878: is_on_map($uri) : checks if the $uri is somewhere on the current
                   7879: course map, user must be in a course for it to work.
1.191     harris41 7880: 
                   7881: =item *
                   7882: 
1.243     albertel 7883: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 7884: 
                   7885: =item *
                   7886: 
1.243     albertel 7887: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   7888: a random seed, all arguments are optional, if they aren't sent it uses the
                   7889: environment to derive them. Note: if symb isn't sent and it can't get one
                   7890: from &symbread it will use the current time as its return value
1.191     harris41 7891: 
                   7892: =item *
                   7893: 
1.243     albertel 7894: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   7895: unfakeable, receipt
1.191     harris41 7896: 
                   7897: =item *
                   7898: 
1.620     albertel 7899: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 7900: 
                   7901: =item *
                   7902: 
1.243     albertel 7903: countacc($url) : count the number of accesses to a given URL
1.191     harris41 7904: 
                   7905: =item *
                   7906: 
1.243     albertel 7907: 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 7908: 
                   7909: =item *
                   7910: 
1.243     albertel 7911: 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 7912: 
                   7913: =item *
                   7914: 
1.243     albertel 7915: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 7916: 
                   7917: =item *
                   7918: 
1.243     albertel 7919: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   7920: forcing spreadsheet to reevaluate the resource scores next time.
                   7921: 
                   7922: =back
                   7923: 
                   7924: =head2 Storing/Retreiving Data
                   7925: 
                   7926: =over 4
1.191     harris41 7927: 
                   7928: =item *
                   7929: 
1.243     albertel 7930: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   7931: for this url; hashref needs to be given and should be a \%hashname; the
                   7932: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 7933: be derived from the env
1.191     harris41 7934: 
                   7935: =item *
                   7936: 
1.243     albertel 7937: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   7938: uses critical subroutine
1.191     harris41 7939: 
                   7940: =item *
                   7941: 
1.243     albertel 7942: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   7943: all args are optional
1.191     harris41 7944: 
                   7945: =item *
                   7946: 
1.717     albertel 7947: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   7948: dumps the complete (or key matching regexp) namespace into a hash
                   7949: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   7950: normally &store()ed into
                   7951: 
                   7952: $range should be either an integer '100' (give me the first 100
                   7953:                                            matching records)
                   7954:               or be  two integers sperated by a - with no spaces
                   7955:                  '30-50' (give me the 30th through the 50th matching
                   7956:                           records)
                   7957: 
                   7958: 
                   7959: =item *
                   7960: 
                   7961: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   7962: replaces a &store() version of data with a replacement set of data
                   7963: for a particular resource in a namespace passed in the $storehash hash 
                   7964: reference
                   7965: 
                   7966: =item *
                   7967: 
1.243     albertel 7968: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   7969: works very similar to store/cstore, but all data is stored in a
                   7970: temporary location and can be reset using tmpreset, $storehash should
                   7971: be a hash reference, returns nothing on success
1.191     harris41 7972: 
                   7973: =item *
                   7974: 
1.243     albertel 7975: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   7976: similar to restore, but all data is stored in a temporary location and
                   7977: can be reset using tmpreset. Returns a hash of values on success,
                   7978: error string otherwise.
1.191     harris41 7979: 
                   7980: =item *
                   7981: 
1.243     albertel 7982: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   7983: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 7984: 
                   7985: =item *
                   7986: 
1.243     albertel 7987: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   7988: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 7989: 
                   7990: =item *
                   7991: 
1.243     albertel 7992: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   7993: namesp ($udom and $uname are optional)
1.191     harris41 7994: 
                   7995: =item *
                   7996: 
1.702     albertel 7997: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 7998: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 7999: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  8000: 
1.702     albertel 8001: $range should be either an integer '100' (give me the first 100
                   8002:                                            matching records)
                   8003:               or be  two integers sperated by a - with no spaces
                   8004:                  '30-50' (give me the 30th through the 50th matching
                   8005:                           records)
1.449     matthew  8006: =item *
                   8007: 
                   8008: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   8009: $store can be a scalar, an array reference, or if the amount to be 
                   8010: incremented is > 1, a hash reference.
                   8011: 
                   8012: ($udom and $uname are optional)
1.191     harris41 8013: 
                   8014: =item *
                   8015: 
1.243     albertel 8016: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   8017: ($udom and $uname are optional)
1.191     harris41 8018: 
                   8019: =item *
                   8020: 
1.243     albertel 8021: cput($namespace,$storehash,$udom,$uname) : critical put
                   8022: ($udom and $uname are optional)
1.191     harris41 8023: 
                   8024: =item *
                   8025: 
1.748     albertel 8026: newput($namespace,$storehash,$udom,$uname) :
                   8027: 
                   8028: Attempts to store the items in the $storehash, but only if they don't
                   8029: currently exist, if this succeeds you can be certain that you have 
                   8030: successfully created a new key value pair in the $namespace db.
                   8031: 
                   8032: 
                   8033: Args:
                   8034:  $namespace: name of database to store values to
                   8035:  $storehash: hashref to store to the db
                   8036:  $udom: (optional) domain of user containing the db
                   8037:  $uname: (optional) name of user caontaining the db
                   8038: 
                   8039: Returns:
                   8040:  'ok' -> succeeded in storing all keys of $storehash
                   8041:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   8042:                         least <key> already existed in the db (other
                   8043:                         requested keys may also already exist)
                   8044:  'error: <msg>' -> unable to tie the DB or other erorr occured
                   8045:  'con_lost' -> unable to contact request server
                   8046:  'refused' -> action was not allowed by remote machine
                   8047: 
                   8048: 
                   8049: =item *
                   8050: 
1.243     albertel 8051: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   8052: reference filled in from namesp (encrypts the return communication)
                   8053: ($udom and $uname are optional)
1.191     harris41 8054: 
                   8055: =item *
                   8056: 
1.243     albertel 8057: log($udom,$name,$home,$message) : write to permanent log for user; use
                   8058: critical subroutine
                   8059: 
                   8060: =back
                   8061: 
                   8062: =head2 Network Status Functions
                   8063: 
                   8064: =over 4
1.191     harris41 8065: 
                   8066: =item *
                   8067: 
                   8068: dirlist($uri) : return directory list based on URI
                   8069: 
                   8070: =item *
                   8071: 
1.243     albertel 8072: spareserver() : find server with least workload from spare.tab
                   8073: 
                   8074: =back
                   8075: 
                   8076: =head2 Apache Request
                   8077: 
                   8078: =over 4
1.191     harris41 8079: 
                   8080: =item *
                   8081: 
1.243     albertel 8082: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   8083: localhost, posts hash
                   8084: 
                   8085: =back
                   8086: 
                   8087: =head2 Data to String to Data
                   8088: 
                   8089: =over 4
1.191     harris41 8090: 
                   8091: =item *
                   8092: 
1.243     albertel 8093: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   8094: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 8095: 
                   8096: =item *
                   8097: 
1.243     albertel 8098: hashref2str($hashref) : convert a hashref into a string complete with
                   8099: escaping and '=' and '&' separators, supports elements that are
                   8100: arrayrefs and hashrefs
1.191     harris41 8101: 
                   8102: =item *
                   8103: 
1.243     albertel 8104: arrayref2str($arrayref) : convert an arrayref into a string complete
                   8105: with escaping and '&' separators, supports elements that are arrayrefs
                   8106: and hashrefs
1.191     harris41 8107: 
                   8108: =item *
                   8109: 
1.243     albertel 8110: str2hash($string) : convert string to hash using unescaping and
                   8111: splitting on '=' and '&', supports elements that are arrayrefs and
                   8112: hashrefs
1.191     harris41 8113: 
                   8114: =item *
                   8115: 
1.243     albertel 8116: str2array($string) : convert string to hash using unescaping and
                   8117: splitting on '&', supports elements that are arrayrefs and hashrefs
                   8118: 
                   8119: =back
                   8120: 
                   8121: =head2 Logging Routines
                   8122: 
                   8123: =over 4
                   8124: 
                   8125: These routines allow one to make log messages in the lonnet.log and
                   8126: lonnet.perm logfiles.
1.191     harris41 8127: 
                   8128: =item *
                   8129: 
1.243     albertel 8130: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 8131: 
                   8132: =item *
                   8133: 
1.243     albertel 8134: logthis() : append message to the normal lonnet.log file, it gets
                   8135: preiodically rolled over and deleted.
1.191     harris41 8136: 
                   8137: =item *
                   8138: 
1.243     albertel 8139: logperm() : append a permanent message to lonnet.perm.log, this log
                   8140: file never gets deleted by any automated portion of the system, only
                   8141: messages of critical importance should go in here.
                   8142: 
                   8143: =back
                   8144: 
                   8145: =head2 General File Helper Routines
                   8146: 
                   8147: =over 4
1.191     harris41 8148: 
                   8149: =item *
                   8150: 
1.481     raeburn  8151: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   8152: (a) files in /uploaded
                   8153:   (i) If a local copy of the file exists - 
                   8154:       compares modification date of local copy with last-modified date for 
                   8155:       definitive version stored on home server for course. If local copy is 
                   8156:       stale, requests a new version from the home server and stores it. 
                   8157:       If the original has been removed from the home server, then local copy 
                   8158:       is unlinked.
                   8159:   (ii) If local copy does not exist -
                   8160:       requests the file from the home server and stores it. 
                   8161:   
                   8162:   If $caller is 'uploadrep':  
                   8163:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   8164:     for request for files originally uploaded via DOCS. 
                   8165:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   8166:   
                   8167:   Otherwise:
                   8168:      This indicates a call from the content generation phase of the request.
                   8169:      -  returns the entire contents of the file or -1.
                   8170:      
                   8171: (b) files in /res
                   8172:    - returns the entire contents of a file or -1; 
                   8173:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 8174: 
1.712     albertel 8175: 
                   8176: =item *
                   8177: 
                   8178: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   8179:                   reference
                   8180: 
                   8181: returns either a stat() list of data about the file or an empty list
                   8182: if the file doesn't exist or couldn't find out about it (connection
                   8183: problems or user unknown)
                   8184: 
1.191     harris41 8185: =item *
                   8186: 
1.243     albertel 8187: filelocation($dir,$file) : returns file system location of a file
                   8188: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   8189: directory that relative $file lookups are to looked in ($dir of /a/dir
                   8190: and a file of ../bob will become /a/bob)
1.191     harris41 8191: 
                   8192: =item *
                   8193: 
                   8194: hreflocation($dir,$file) : returns file system location or a URL; same as
                   8195: filelocation except for hrefs
                   8196: 
                   8197: =item *
                   8198: 
                   8199: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   8200: 
1.243     albertel 8201: =back
                   8202: 
1.608     albertel 8203: =head2 Usererfile file routines (/uploaded*)
                   8204: 
                   8205: =over 4
                   8206: 
                   8207: =item *
                   8208: 
                   8209: userfileupload(): main rotine for putting a file in a user or course's
                   8210:                   filespace, arguments are,
                   8211: 
1.620     albertel 8212:  formname - required - this is the name of the element in $env where the
1.608     albertel 8213:            filename, and the contents of the file to create/modifed exist
1.620     albertel 8214:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   8215:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 8216:  coursedoc - if true, store the file in the course of the active role
                   8217:              of the current user
                   8218:  subdir - required - subdirectory to put the file in under ../userfiles/
                   8219:          if undefined, it will be placed in "unknown"
                   8220: 
                   8221:  (This routine calls clean_filename() to remove any dangerous
                   8222:  characters from the filename, and then calls finuserfileupload() to
                   8223:  complete the transaction)
                   8224: 
                   8225:  returns either the url of the uploaded file (/uploaded/....) if successful
                   8226:  and /adm/notfound.html if unsuccessful
                   8227: 
                   8228: =item *
                   8229: 
                   8230: clean_filename(): routine for cleaing a filename up for storage in
                   8231:                  userfile space, argument is:
                   8232: 
                   8233:  filename - proposed filename
                   8234: 
                   8235: returns: the new clean filename
                   8236: 
                   8237: =item *
                   8238: 
                   8239: finishuserfileupload(): routine that creaes and sends the file to
                   8240: userspace, probably shouldn't be called directly
                   8241: 
                   8242:   docuname: username or courseid of destination for the file
                   8243:   docudom: domain of user/course of destination for the file
                   8244:   formname: same as for userfileupload()
                   8245:   fname: filename (inculding subdirectories) for the file
                   8246: 
                   8247:  returns either the url of the uploaded file (/uploaded/....) if successful
                   8248:  and /adm/notfound.html if unsuccessful
                   8249: 
                   8250: =item *
                   8251: 
                   8252: renameuserfile(): renames an existing userfile to a new name
                   8253: 
                   8254:   Args:
                   8255:    docuname: username or courseid of destination for the file
                   8256:    docudom: domain of user/course of destination for the file
                   8257:    old: current file name (including any subdirs under userfiles)
                   8258:    new: desired file name (including any subdirs under userfiles)
                   8259: 
                   8260: =item *
                   8261: 
                   8262: mkdiruserfile(): creates a directory is a userfiles dir
                   8263: 
                   8264:   Args:
                   8265:    docuname: username or courseid of destination for the file
                   8266:    docudom: domain of user/course of destination for the file
                   8267:    dir: dir to create (including any subdirs under userfiles)
                   8268: 
                   8269: =item *
                   8270: 
                   8271: removeuserfile(): removes a file that exists in userfiles
                   8272: 
                   8273:   Args:
                   8274:    docuname: username or courseid of destination for the file
                   8275:    docudom: domain of user/course of destination for the file
                   8276:    fname: filname to delete (including any subdirs under userfiles)
                   8277: 
                   8278: =item *
                   8279: 
                   8280: removeuploadedurl(): convience function for removeuserfile()
                   8281: 
                   8282:   Args:
                   8283:    url:  a full /uploaded/... url to delete
                   8284: 
1.747     albertel 8285: =item * 
                   8286: 
                   8287: get_portfile_permissions():
                   8288:   Args:
                   8289:     domain: domain of user or course contain the portfolio files
                   8290:     user: name of user or num of course contain the portfolio files
                   8291:   Returns:
                   8292:     hashref of a dump of the proper file_permissions.db
                   8293:    
                   8294: 
                   8295: =item * 
                   8296: 
                   8297: get_access_controls():
                   8298: 
                   8299: Args:
                   8300:   current_permissions: the hash ref returned from get_portfile_permissions()
                   8301:   group: (optional) the group you want the files associated with
                   8302:   file: (optional) the file you want access info on
                   8303: 
                   8304: Returns:
1.749     raeburn  8305:     a hash (keys are file names) of hashes containing
                   8306:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   8307:         values are XML containing access control settings (see below) 
1.747     albertel 8308: 
                   8309: Internal notes:
                   8310: 
1.749     raeburn  8311:  access controls are stored in file_permissions.db as key=value pairs.
                   8312:     key -> path to file/file_name\0uniqueID:scope_end_start
                   8313:         where scope -> public,guest,course,group,domains or users.
                   8314:               end -> UNIX time for end of access (0 -> no end date)
                   8315:               start -> UNIX time for start of access
                   8316: 
                   8317:     value -> XML description of access control
                   8318:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   8319:             <start></start>
                   8320:             <end></end>
                   8321: 
                   8322:             <password></password>  for scope type = guest
                   8323: 
                   8324:             <domain></domain>     for scope type = course or group
                   8325:             <number></number>
                   8326:             <roles id="">
                   8327:              <role></role>
                   8328:              <access></access>
                   8329:              <section></section>
                   8330:              <group></group>
                   8331:             </roles>
                   8332: 
                   8333:             <dom></dom>         for scope type = domains
                   8334: 
                   8335:             <users>             for scope type = users
                   8336:              <user>
                   8337:               <uname></uname>
                   8338:               <udom></udom>
                   8339:              </user>
                   8340:             </users>
                   8341:            </scope> 
                   8342:               
                   8343:  Access data is also aggregated for each file in an additional key=value pair:
                   8344:  key -> path to file/file_name\0accesscontrol 
                   8345:  value -> reference to hash
                   8346:           hash contains key = value pairs
                   8347:           where key = uniqueID:scope_end_start
                   8348:                 value = UNIX time record was last updated
                   8349: 
                   8350:           Used to improve speed of look-ups of access controls for each file.  
                   8351:  
                   8352:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   8353: 
                   8354: modify_access_controls():
                   8355: 
                   8356: Modifies access controls for a portfolio file
                   8357: Args
                   8358: 1. file name
                   8359: 2. reference to hash of required changes,
                   8360: 3. domain
                   8361: 4. username
                   8362:   where domain,username are the domain of the portfolio owner 
                   8363:   (either a user or a course) 
                   8364: 
                   8365: Returns:
                   8366: 1. result of additions or updates ('ok' or 'error', with error message). 
                   8367: 2. result of deletions ('ok' or 'error', with error message).
                   8368: 3. reference to hash of any new or updated access controls.
                   8369: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   8370:    key = integer (inbound ID)
                   8371:    value = uniqueID  
1.747     albertel 8372: 
1.608     albertel 8373: =back
                   8374: 
1.243     albertel 8375: =head2 HTTP Helper Routines
                   8376: 
                   8377: =over 4
                   8378: 
1.191     harris41 8379: =item *
                   8380: 
                   8381: escape() : unpack non-word characters into CGI-compatible hex codes
                   8382: 
                   8383: =item *
                   8384: 
                   8385: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   8386: 
1.243     albertel 8387: =back
                   8388: 
                   8389: =head1 PRIVATE SUBROUTINES
                   8390: 
                   8391: =head2 Underlying communication routines (Shouldn't call)
                   8392: 
                   8393: =over 4
                   8394: 
                   8395: =item *
                   8396: 
                   8397: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   8398: 
                   8399: =item *
                   8400: 
                   8401: reply() : uses subreply to send a message to remote machine, logs all failures
                   8402: 
                   8403: =item *
                   8404: 
                   8405: critical() : passes a critical message to another server; if cannot
                   8406: get through then place message in connection buffer directory and
                   8407: returns con_delayed, if incapable of saving message, returns
                   8408: con_failed
                   8409: 
                   8410: =item *
                   8411: 
                   8412: reconlonc() : tries to reconnect lonc client processes.
                   8413: 
                   8414: =back
                   8415: 
                   8416: =head2 Resource Access Logging
                   8417: 
                   8418: =over 4
                   8419: 
                   8420: =item *
                   8421: 
                   8422: flushcourselogs() : flush (save) buffer logs and access logs
                   8423: 
                   8424: =item *
                   8425: 
                   8426: courselog($what) : save message for course in hash
                   8427: 
                   8428: =item *
                   8429: 
                   8430: courseacclog($what) : save message for course using &courselog().  Perform
                   8431: special processing for specific resource types (problems, exams, quizzes, etc).
                   8432: 
1.191     harris41 8433: =item *
                   8434: 
                   8435: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   8436: as a PerlChildExitHandler
1.243     albertel 8437: 
                   8438: =back
                   8439: 
                   8440: =head2 Other
                   8441: 
                   8442: =over 4
                   8443: 
                   8444: =item *
                   8445: 
                   8446: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 8447: 
                   8448: =back
                   8449: 
                   8450: =cut

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