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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.797   ! raeburn     4: # $Id: lonnet.pm,v 1.796 2006/10/18 02:39:12 raeburn Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.1       albertel   30: package Apache::lonnet;
                     31: 
                     32: use strict;
1.8       www        33: use LWP::UserAgent();
1.15      www        34: use HTTP::Headers;
1.486     www        35: use HTTP::Date;
                     36: # use Date::Parse;
1.11      www        37: use vars 
1.599     albertel   38: qw(%perlvar %hostname %badServerCache %iphost %spareid %hostdom 
                     39:    %libserv %pr %prp $memcache %packagetab 
1.662     raeburn    40:    %courselogs %accesshash %userrolehash %domainrolehash $processmarker $dumpcount 
1.741     raeburn    41:    %coursedombuf %coursenumbuf %coursehombuf %coursedescrbuf %courseinstcodebuf %courseownerbuf %coursetypebuf
1.599     albertel   42:    %domaindescription %domain_auth_def %domain_auth_arg_def 
1.685     raeburn    43:    %domain_lang_def %domain_city %domain_longi %domain_lati %domain_primary
                     44:    $tmpdir $_64bit %env);
1.403     www        45: 
1.1       albertel   46: use IO::Socket;
1.31      www        47: use GDBM_File;
1.208     albertel   48: use HTML::LCParser;
1.637     raeburn    49: use HTML::Parser;
1.88      www        50: use Fcntl qw(:flock);
1.557     albertel   51: use Storable qw(lock_store lock_nstore lock_retrieve freeze thaw nfreeze);
1.539     albertel   52: use Time::HiRes qw( gettimeofday tv_interval );
1.599     albertel   53: use Cache::Memcached;
1.676     albertel   54: use Digest::MD5;
1.790     albertel   55: use Math::Random;
1.740     www        56: use lib '/home/httpd/lib/perl';
                     57: use LONCAPA;
                     58: use LONCAPA::Configuration;
1.676     albertel   59: 
1.195     www        60: my $readit;
1.550     foxr       61: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel   62: 
1.619     albertel   63: require Exporter;
                     64: 
                     65: our @ISA = qw (Exporter);
                     66: our @EXPORT = qw(%env);
                     67: 
1.449     matthew    68: =pod
                     69: 
                     70: =head1 Package Variables
                     71: 
                     72: These are largely undocumented, so if you decipher one please note it here.
                     73: 
                     74: =over 4
                     75: 
                     76: =item $processmarker
                     77: 
                     78: Contains the time this process was started and this servers host id.
                     79: 
                     80: =item $dumpcount
                     81: 
                     82: Counts the number of times a message log flush has been attempted (regardless
                     83: of success) by this process.  Used as part of the filename when messages are
                     84: delayed.
                     85: 
                     86: =back
                     87: 
                     88: =cut
                     89: 
                     90: 
1.1       albertel   91: # --------------------------------------------------------------------- Logging
1.729     www        92: {
                     93:     my $logid;
                     94:     sub instructor_log {
                     95: 	my ($hash_name,$storehash,$delflag,$uname,$udom)=@_;
                     96: 	$logid++;
                     97: 	my $id=time().'00000'.$$.'00000'.$logid;
                     98: 	return &Apache::lonnet::put('nohist_'.$hash_name,
1.730     www        99: 				    { $id => {
                    100: 					'exe_uname' => $env{'user.name'},
                    101: 					'exe_udom'  => $env{'user.domain'},
                    102: 					'exe_time'  => time(),
                    103: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    104: 					'delflag'   => $delflag,
                    105: 					'logentry'  => $storehash,
                    106: 					'uname'     => $uname,
                    107: 					'udom'      => $udom,
                    108: 				    }
                    109: 				  },
1.729     www       110: 				    $env{'course.'.$env{'request.course.id'}.'.domain'},
                    111: 				    $env{'course.'.$env{'request.course.id'}.'.num'}
                    112: 				    );
                    113:     }
                    114: }
1.1       albertel  115: 
1.163     harris41  116: sub logtouch {
                    117:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  118:     unless (-e "$execdir/logs/lonnet.log") {	
                    119: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  120: 	close $fh;
                    121:     }
                    122:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    123:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    124: }
                    125: 
1.1       albertel  126: sub logthis {
                    127:     my $message=shift;
                    128:     my $execdir=$perlvar{'lonDaemons'};
                    129:     my $now=time;
                    130:     my $local=localtime($now);
1.448     albertel  131:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
                    132: 	print $fh "$local ($$): $message\n";
                    133: 	close($fh);
                    134:     }
1.1       albertel  135:     return 1;
                    136: }
                    137: 
                    138: sub logperm {
                    139:     my $message=shift;
                    140:     my $execdir=$perlvar{'lonDaemons'};
                    141:     my $now=time;
                    142:     my $local=localtime($now);
1.448     albertel  143:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    144: 	print $fh "$now:$message:$local\n";
                    145: 	close($fh);
                    146:     }
1.1       albertel  147:     return 1;
                    148: }
                    149: 
                    150: # -------------------------------------------------- Non-critical communication
                    151: sub subreply {
                    152:     my ($cmd,$server)=@_;
1.704     albertel  153:     my $peerfile="$perlvar{'lonSockDir'}/".$hostname{$server};
1.549     foxr      154:     #
                    155:     #  With loncnew process trimming, there's a timing hole between lonc server
                    156:     #  process exit and the master server picking up the listen on the AF_UNIX
                    157:     #  socket.  In that time interval, a lock file will exist:
                    158: 
                    159:     my $lockfile=$peerfile.".lock";
                    160:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    161: 	sleep(1);
                    162:     }
                    163:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      164:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      165:     #
1.550     foxr      166:     #   We'll give the connection a few tries before abandoning it.  If
                    167:     #   connection is not possible, we'll con_lost back to the client.
                    168:     #   
                    169:     my $client;
                    170:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    171: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    172: 				      Type    => SOCK_STREAM,
                    173: 				      Timeout => 10);
                    174: 	if($client) {
                    175: 	    last;		# Connected!
                    176: 	}
                    177: 	sleep(1);		# Try again later if failed connection.
                    178:     }
                    179:     my $answer;
                    180:     if ($client) {
1.704     albertel  181: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      182: 	$answer=<$client>;
                    183: 	if (!$answer) { $answer="con_lost"; }
                    184: 	chomp($answer);
                    185:     } else {
                    186: 	$answer = 'con_lost';	# Failed connection.
                    187:     }
1.1       albertel  188:     return $answer;
                    189: }
                    190: 
                    191: sub reply {
                    192:     my ($cmd,$server)=@_;
1.205     www       193:     unless (defined($hostname{$server})) { return 'no_such_host'; }
1.1       albertel  194:     my $answer=subreply($cmd,$server);
1.65      www       195:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  196:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       197:                 " $cmd to $server returned $answer</font>");
                    198:     }
1.1       albertel  199:     return $answer;
                    200: }
                    201: 
                    202: # ----------------------------------------------------------- Send USR1 to lonc
                    203: 
                    204: sub reconlonc {
                    205:     my $peerfile=shift;
                    206:     &logthis("Trying to reconnect for $peerfile");
                    207:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  208:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  209: 	my $loncpid=<$fh>;
                    210:         chomp($loncpid);
                    211:         if (kill 0 => $loncpid) {
                    212: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    213:             kill USR1 => $loncpid;
                    214:             sleep 1;
                    215:             if (-e "$peerfile") { return; }
                    216:             &logthis("$peerfile still not there, give it another try");
                    217:             sleep 5;
                    218:             if (-e "$peerfile") { return; }
1.12      www       219:             &logthis(
1.672     albertel  220:   "<font color=\"blue\">WARNING: $peerfile still not there, giving up</font>");
1.1       albertel  221:         } else {
1.12      www       222: 	    &logthis(
1.672     albertel  223:                "<font color=\"blue\">WARNING:".
1.12      www       224:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  225:         }
                    226:     } else {
1.672     albertel  227:      &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  228:     }
                    229: }
                    230: 
                    231: # ------------------------------------------------------ Critical communication
1.12      www       232: 
1.1       albertel  233: sub critical {
                    234:     my ($cmd,$server)=@_;
1.89      www       235:     unless ($hostname{$server}) {
1.672     albertel  236:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       237:                " Critical message to unknown server ($server)</font>");
                    238:         return 'no_such_host';
                    239:     }
1.1       albertel  240:     my $answer=reply($cmd,$server);
                    241:     if ($answer eq 'con_lost') {
                    242: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  243: 	my $answer=reply($cmd,$server);
1.1       albertel  244:         if ($answer eq 'con_lost') {
                    245:             my $now=time;
                    246:             my $middlename=$cmd;
1.5       www       247:             $middlename=substr($middlename,0,16);
1.1       albertel  248:             $middlename=~s/\W//g;
                    249:             my $dfilename=
1.305     www       250:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    251:             $dumpcount++;
1.1       albertel  252:             {
1.448     albertel  253: 		my $dfh;
                    254: 		if (open($dfh,">$dfilename")) {
                    255: 		    print $dfh "$cmd\n"; 
                    256: 		    close($dfh);
                    257: 		}
1.1       albertel  258:             }
                    259:             sleep 2;
                    260:             my $wcmd='';
                    261:             {
1.448     albertel  262: 		my $dfh;
                    263: 		if (open($dfh,"<$dfilename")) {
                    264: 		    $wcmd=<$dfh>; 
                    265: 		    close($dfh);
                    266: 		}
1.1       albertel  267:             }
                    268:             chomp($wcmd);
1.7       www       269:             if ($wcmd eq $cmd) {
1.672     albertel  270: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       271:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  272:                 &logperm("D:$server:$cmd");
                    273: 	        return 'con_delayed';
                    274:             } else {
1.672     albertel  275:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       276:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  277:                 &logperm("F:$server:$cmd");
                    278:                 return 'con_failed';
                    279:             }
                    280:         }
                    281:     }
                    282:     return $answer;
1.405     albertel  283: }
                    284: 
1.755     albertel  285: # ------------------------------------------- check if return value is an error
                    286: 
                    287: sub error {
                    288:     my ($result) = @_;
1.756     albertel  289:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  290: 	if ($2 == 2) { return undef; }
                    291: 	return $1;
                    292:     }
                    293:     return undef;
                    294: }
                    295: 
1.783     albertel  296: sub convert_and_load_session_env {
                    297:     my ($lonidsdir,$handle)=@_;
                    298:     my @profile;
                    299:     {
                    300: 	open(my $idf,"$lonidsdir/$handle.id");
                    301: 	flock($idf,LOCK_SH);
                    302: 	@profile=<$idf>;
                    303: 	close($idf);
                    304:     }
                    305:     my %temp_env;
                    306:     foreach my $line (@profile) {
1.786     albertel  307: 	if ($line !~ m/=/) {
                    308: 	    return 0;
                    309: 	}
1.783     albertel  310: 	chomp($line);
                    311: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    312: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    313:     }
                    314:     unlink("$lonidsdir/$handle.id");
                    315:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    316: 	    0640)) {
                    317: 	%disk_env = %temp_env;
                    318: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    319: 	untie(%disk_env);
                    320:     }
1.786     albertel  321:     return 1;
1.783     albertel  322: }
                    323: 
1.374     www       324: # ------------------------------------------- Transfer profile into environment
1.780     albertel  325: my $env_loaded;
                    326: sub transfer_profile_to_env {
1.788     albertel  327:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    328:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       329: 
1.720     albertel  330:     if (!defined($lonidsdir)) {
                    331: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    332:     }
                    333:     if (!defined($handle)) {
                    334:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    335:     }
                    336: 
1.786     albertel  337:     my $convert;
                    338:     {
                    339:     	open(my $idf,"$lonidsdir/$handle.id");
                    340: 	flock($idf,LOCK_SH);
                    341: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    342: 		&GDBM_READER(),0640)) {
                    343: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    344: 	    untie(%disk_env);
                    345: 	} else {
                    346: 	    $convert = 1;
                    347: 	}
                    348:     }
                    349:     if ($convert) {
                    350: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    351: 	    &logthis("Failed to load session, or convert session.");
                    352: 	}
1.374     www       353:     }
1.783     albertel  354: 
1.786     albertel  355:     my %remove;
1.783     albertel  356:     while ( my $envname = each(%env) ) {
1.433     matthew   357:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    358:             if ($time < time-300) {
1.783     albertel  359:                 $remove{$key}++;
1.433     matthew   360:             }
                    361:         }
                    362:     }
1.783     albertel  363: 
1.619     albertel  364:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  365:     $env_loaded=1;
1.783     albertel  366:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   367:         &delenv($expired_key);
1.374     www       368:     }
1.1       albertel  369: }
                    370: 
1.5       www       371: # ---------------------------------------------------------- Append Environment
                    372: 
                    373: sub appenv {
1.6       www       374:     my %newenv=@_;
1.692     albertel  375:     foreach my $key (keys(%newenv)) {
                    376: 	if (($newenv{$key}=~/^user\.role/) || ($newenv{$key}=~/^user\.priv/)) {
1.672     albertel  377:             &logthis("<font color=\"blue\">WARNING: ".
1.692     albertel  378:                 "Attempt to modify environment ".$key." to ".$newenv{$key}
1.151     www       379:                 .'</font>');
1.692     albertel  380: 	    delete($newenv{$key});
1.35      www       381:         } else {
1.692     albertel  382:             $env{$key}=$newenv{$key};
1.35      www       383:         }
1.191     harris41  384:     }
1.783     albertel  385:     if (tie(my %disk_env,'GDBM_File',$env{'user.environment'},&GDBM_WRITER(),
                    386: 	    0640)) {
                    387: 	while (my ($key,$value) = each(%newenv)) {
                    388: 	    $disk_env{$key} = $value;
1.448     albertel  389: 	}
1.783     albertel  390: 	untie(%disk_env);
1.56      www       391:     }
                    392:     return 'ok';
                    393: }
                    394: # ----------------------------------------------------- Delete from Environment
                    395: 
                    396: sub delenv {
                    397:     my $delthis=shift;
                    398:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672     albertel  399:         &logthis("<font color=\"blue\">WARNING: ".
1.56      www       400:                 "Attempt to delete from environment ".$delthis);
                    401:         return 'error';
                    402:     }
1.783     albertel  403:     if (tie(my %disk_env,'GDBM_File',$env{'user.environment'},&GDBM_WRITER(),
                    404: 	    0640)) {
                    405: 	foreach my $key (keys(%disk_env)) {
                    406: 	    if ($key=~/^$delthis/) { 
1.619     albertel  407:                 delete($env{$key});
1.783     albertel  408:                 delete($disk_env{$key});
1.473     matthew   409:             }
1.448     albertel  410: 	}
1.783     albertel  411: 	untie(%disk_env);
1.5       www       412:     }
                    413:     return 'ok';
1.369     albertel  414: }
                    415: 
1.790     albertel  416: sub get_env_multiple {
                    417:     my ($name) = @_;
                    418:     my @values;
                    419:     if (defined($env{$name})) {
                    420:         # exists is it an array
                    421:         if (ref($env{$name})) {
                    422:             @values=@{ $env{$name} };
                    423:         } else {
                    424:             $values[0]=$env{$name};
                    425:         }
                    426:     }
                    427:     return(@values);
                    428: }
                    429: 
1.369     albertel  430: # ------------------------------------------ Find out current server userload
                    431: # there is a copy in lond
                    432: sub userload {
                    433:     my $numusers=0;
                    434:     {
                    435: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    436: 	my $filename;
                    437: 	my $curtime=time;
                    438: 	while ($filename=readdir(LONIDS)) {
                    439: 	    if ($filename eq '.' || $filename eq '..') {next;}
1.404     albertel  440: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  441: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  442: 	}
                    443: 	closedir(LONIDS);
                    444:     }
                    445:     my $userloadpercent=0;
                    446:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    447:     if ($maxuserload) {
1.371     albertel  448: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  449:     }
1.372     albertel  450:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  451:     return $userloadpercent;
1.283     www       452: }
                    453: 
                    454: # ------------------------------------------ Fight off request when overloaded
                    455: 
                    456: sub overloaderror {
                    457:     my ($r,$checkserver)=@_;
                    458:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
                    459:     my $loadavg;
                    460:     if ($checkserver eq $perlvar{'lonHostID'}) {
1.448     albertel  461:        open(my $loadfile,'/proc/loadavg');
1.283     www       462:        $loadavg=<$loadfile>;
                    463:        $loadavg =~ s/\s.*//g;
1.285     matthew   464:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448     albertel  465:        close($loadfile);
1.283     www       466:     } else {
                    467:        $loadavg=&reply('load',$checkserver);
                    468:     }
1.285     matthew   469:     my $overload=$loadavg-100;
1.283     www       470:     if ($overload>0) {
1.285     matthew   471: 	$r->err_headers_out->{'Retry-After'}=$overload;
1.283     www       472:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554     www       473:         return 413;
1.283     www       474:     }    
                    475:     return '';
1.5       www       476: }
1.1       albertel  477: 
                    478: # ------------------------------ Find server with least workload from spare.tab
1.11      www       479: 
1.1       albertel  480: sub spareserver {
1.670     albertel  481:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.784     albertel  482:     my $spare_server;
1.370     albertel  483:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  484:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    485:                                                      :  $userloadpercent;
                    486:     
                    487:     foreach my $try_server (@{ $spareid{'primary'} }) {
                    488: 	($spare_server, $lowest_load) =
                    489: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
                    490:     }
                    491: 
                    492:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    493: 
                    494:     if (!$found_server) {
                    495: 	foreach my $try_server (@{ $spareid{'default'} }) {
                    496: 	    ($spare_server, $lowest_load) =
                    497: 		&compare_server_load($try_server, $spare_server, $lowest_load);
                    498: 	}
                    499:     }
                    500: 
                    501:     if (!$want_server_name) {
                    502: 	$spare_server="http://$hostname{$spare_server}";
                    503:     }
                    504:     return $spare_server;
                    505: }
                    506: 
                    507: sub compare_server_load {
                    508:     my ($try_server, $spare_server, $lowest_load) = @_;
                    509: 
                    510:     my $loadans     = &reply('load',    $try_server);
                    511:     my $userloadans = &reply('userload',$try_server);
                    512: 
                    513:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
                    514: 	next; #didn't get a number from the server
                    515:     }
                    516: 
                    517:     my $load;
                    518:     if ($loadans =~ /\d/) {
                    519: 	if ($userloadans =~ /\d/) {
                    520: 	    #both are numbers, pick the bigger one
                    521: 	    $load = ($loadans > $userloadans) ? $loadans 
                    522: 		                              : $userloadans;
1.411     albertel  523: 	} else {
1.784     albertel  524: 	    $load = $loadans;
1.411     albertel  525: 	}
1.784     albertel  526:     } else {
                    527: 	$load = $userloadans;
                    528:     }
                    529: 
                    530:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    531: 	$spare_server = $try_server;
                    532: 	$lowest_load  = $load;
1.370     albertel  533:     }
1.784     albertel  534:     return ($spare_server,$lowest_load);
1.202     matthew   535: }
                    536: # --------------------------------------------- Try to change a user's password
                    537: 
                    538: sub changepass {
                    539:     my ($uname,$udom,$currentpass,$newpass,$server)=@_;
                    540:     $currentpass = &escape($currentpass);
                    541:     $newpass     = &escape($newpass);
                    542:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass",
                    543: 		       $server);
                    544:     if (! $answer) {
                    545: 	&logthis("No reply on password change request to $server ".
                    546: 		 "by $uname in domain $udom.");
                    547:     } elsif ($answer =~ "^ok") {
                    548:         &logthis("$uname in $udom successfully changed their password ".
                    549: 		 "on $server.");
                    550:     } elsif ($answer =~ "^pwchange_failure") {
                    551: 	&logthis("$uname in $udom was unable to change their password ".
                    552: 		 "on $server.  The action was blocked by either lcpasswd ".
                    553: 		 "or pwchange");
                    554:     } elsif ($answer =~ "^non_authorized") {
                    555:         &logthis("$uname in $udom did not get their password correct when ".
                    556: 		 "attempting to change it on $server.");
                    557:     } elsif ($answer =~ "^auth_mode_error") {
                    558:         &logthis("$uname in $udom attempted to change their password despite ".
                    559: 		 "not being locally or internally authenticated on $server.");
                    560:     } elsif ($answer =~ "^unknown_user") {
                    561:         &logthis("$uname in $udom attempted to change their password ".
                    562: 		 "on $server but were unable to because $server is not ".
                    563: 		 "their home server.");
                    564:     } elsif ($answer =~ "^refused") {
                    565: 	&logthis("$server refused to change $uname in $udom password because ".
                    566: 		 "it was sent an unencrypted request to change the password.");
                    567:     }
                    568:     return $answer;
1.1       albertel  569: }
                    570: 
1.169     harris41  571: # ----------------------- Try to determine user's current authentication scheme
                    572: 
                    573: sub queryauthenticate {
                    574:     my ($uname,$udom)=@_;
1.456     albertel  575:     my $uhome=&homeserver($uname,$udom);
                    576:     if (!$uhome) {
                    577: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                    578: 	return 'no_host';
                    579:     }
                    580:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                    581:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                    582: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41  583:     }
1.456     albertel  584:     return $answer;
1.169     harris41  585: }
                    586: 
1.1       albertel  587: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       588: 
1.1       albertel  589: sub authenticate {
                    590:     my ($uname,$upass,$udom)=@_;
1.12      www       591:     $upass=escape($upass);
1.199     www       592:     $uname=~s/\W//g;
1.471     albertel  593:     my $uhome=&homeserver($uname,$udom);
                    594:     if (!$uhome) {
                    595: 	&logthis("User $uname at $udom is unknown in authenticate");
                    596: 	return 'no_host';
1.1       albertel  597:     }
1.471     albertel  598:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
                    599:     if ($answer eq 'authorized') {
                    600: 	&logthis("User $uname at $udom authorized by $uhome"); 
                    601: 	return $uhome; 
                    602:     }
                    603:     if ($answer eq 'non_authorized') {
                    604: 	&logthis("User $uname at $udom rejected by $uhome");
                    605: 	return 'no_host'; 
1.9       www       606:     }
1.471     albertel  607:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel  608:     return 'no_host';
                    609: }
                    610: 
                    611: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www       612: 
1.599     albertel  613: my %homecache;
1.1       albertel  614: sub homeserver {
1.230     stredwic  615:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel  616:     my $index="$uname:$udom";
1.426     albertel  617: 
1.599     albertel  618:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.1       albertel  619:     my $tryserver;
                    620:     foreach $tryserver (keys %libserv) {
1.230     stredwic  621:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic  622: 		 exists($badServerCache{$tryserver}));
1.1       albertel  623: 	if ($hostdom{$tryserver} eq $udom) {
                    624:            my $answer=reply("home:$udom:$uname",$tryserver);
                    625:            if ($answer eq 'found') { 
1.599     albertel  626: 	       return $homecache{$index}=$tryserver;
1.231     stredwic  627:            } elsif ($answer eq 'no_host') {
                    628: 	       $badServerCache{$tryserver}=1;
1.221     matthew   629:            }
1.1       albertel  630:        }
                    631:     }    
                    632:     return 'no_host';
1.70      www       633: }
                    634: 
                    635: # ------------------------------------- Find the usernames behind a list of IDs
                    636: 
                    637: sub idget {
                    638:     my ($udom,@ids)=@_;
                    639:     my %returnhash=();
                    640:     
                    641:     my $tryserver;
                    642:     foreach $tryserver (keys %libserv) {
                    643:        if ($hostdom{$tryserver} eq $udom) {
                    644: 	  my $idlist=join('&',@ids);
                    645:           $idlist=~tr/A-Z/a-z/; 
                    646: 	  my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                    647:           my @answer=();
1.76      www       648:           if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1.70      www       649: 	      @answer=split(/\&/,$reply);
                    650:           }                    ;
                    651:           my $i;
                    652:           for ($i=0;$i<=$#ids;$i++) {
                    653:               if ($answer[$i]) {
                    654: 		  $returnhash{$ids[$i]}=$answer[$i];
                    655:               } 
                    656:           }
                    657:        }
                    658:     }    
                    659:     return %returnhash;
                    660: }
                    661: 
                    662: # ------------------------------------- Find the IDs behind a list of usernames
                    663: 
                    664: sub idrget {
                    665:     my ($udom,@unames)=@_;
                    666:     my %returnhash=();
1.191     harris41  667:     foreach (@unames) {
1.70      www       668:         $returnhash{$_}=(&userenvironment($udom,$_,'id'))[1];
1.191     harris41  669:     }
1.70      www       670:     return %returnhash;
                    671: }
                    672: 
                    673: # ------------------------------- Store away a list of names and associated IDs
                    674: 
                    675: sub idput {
                    676:     my ($udom,%ids)=@_;
                    677:     my %servers=();
1.191     harris41  678:     foreach (keys %ids) {
1.487     albertel  679: 	&cput('environment',{'id'=>$ids{$_}},$udom,$_);
1.70      www       680:         my $uhom=&homeserver($_,$udom);
                    681:         if ($uhom ne 'no_host') {
                    682:             my $id=&escape($ids{$_});
                    683:             $id=~tr/A-Z/a-z/;
                    684:             my $unam=&escape($_);
                    685: 	    if ($servers{$uhom}) {
                    686: 		$servers{$uhom}.='&'.$id.'='.$unam;
                    687:             } else {
                    688:                 $servers{$uhom}=$id.'='.$unam;
                    689:             }
                    690:         }
1.191     harris41  691:     }
                    692:     foreach (keys %servers) {
1.70      www       693:         &critical('idput:'.$udom.':'.$servers{$_},$_);
1.191     harris41  694:     }
1.344     www       695: }
                    696: 
                    697: # --------------------------------------------------- Assign a key to a student
                    698: 
                    699: sub assign_access_key {
1.364     www       700: #
                    701: # a valid key looks like uname:udom#comments
                    702: # comments are being appended
                    703: #
1.498     www       704:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                    705:     $kdom=
1.620     albertel  706:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www       707:     $knum=
1.620     albertel  708:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www       709:     $cdom=
1.620     albertel  710:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       711:     $cnum=
1.620     albertel  712:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    713:     $udom=$env{'user.name'} unless (defined($udom));
                    714:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www       715:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www       716:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel  717:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www       718:                                                   # assigned to this person
                    719:                                                   # - this should not happen,
1.345     www       720:                                                   # unless something went wrong
                    721:                                                   # the first time around
                    722: # ready to assign
1.364     www       723:         $logentry=$1.'; '.$logentry;
1.496     www       724:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www       725:                                                  $kdom,$knum) eq 'ok') {
1.345     www       726: # key now belongs to user
1.346     www       727: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www       728:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
                    729:                 &appenv('environment.'.$envkey => $ckey);
                    730:                 return 'ok';
                    731:             } else {
                    732:                 return 
                    733:   'error: Count not permanently assign key, will need to be re-entered later.';
                    734: 	    }
                    735:         } else {
                    736:             return 'error: Could not assign key, try again later.';
                    737:         }
1.364     www       738:     } elsif (!$existing{$ckey}) {
1.345     www       739: # the key does not exist
                    740: 	return 'error: The key does not exist';
                    741:     } else {
                    742: # the key is somebody else's
                    743: 	return 'error: The key is already in use';
                    744:     }
1.344     www       745: }
                    746: 
1.364     www       747: # ------------------------------------------ put an additional comment on a key
                    748: 
                    749: sub comment_access_key {
                    750: #
                    751: # a valid key looks like uname:udom#comments
                    752: # comments are being appended
                    753: #
                    754:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                    755:     $cdom=
1.620     albertel  756:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www       757:     $cnum=
1.620     albertel  758:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www       759:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                    760:     if ($existing{$ckey}) {
                    761:         $existing{$ckey}.='; '.$logentry;
                    762: # ready to assign
1.367     www       763:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www       764:                                                  $cdom,$cnum) eq 'ok') {
                    765: 	    return 'ok';
                    766:         } else {
                    767: 	    return 'error: Count not store comment.';
                    768:         }
                    769:     } else {
                    770: # the key does not exist
                    771: 	return 'error: The key does not exist';
                    772:     }
                    773: }
                    774: 
1.344     www       775: # ------------------------------------------------------ Generate a set of keys
                    776: 
                    777: sub generate_access_keys {
1.364     www       778:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www       779:     $cdom=
1.620     albertel  780:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       781:     $cnum=
1.620     albertel  782:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www       783:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www       784:     unless (($cdom) && ($cnum)) { return 0; }
                    785:     if ($number>10000) { return 0; }
                    786:     sleep(2); # make sure don't get same seed twice
                    787:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                    788:     my $total=0;
                    789:     for (my $i=1;$i<=$number;$i++) {
                    790:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                    791:                   sprintf("%lx",int(100000*rand)).'-'.
                    792:                   sprintf("%lx",int(100000*rand));
                    793:        $newkey=~s/1/g/g; # folks mix up 1 and l
                    794:        $newkey=~s/0/h/g; # and also 0 and O
                    795:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                    796:        if ($existing{$newkey}) {
                    797:            $i--;
                    798:        } else {
1.364     www       799: 	  if (&put('accesskeys',
                    800:               { $newkey => '# generated '.localtime().
1.620     albertel  801:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www       802:                            '; '.$logentry },
                    803: 		   $cdom,$cnum) eq 'ok') {
1.344     www       804:               $total++;
                    805: 	  }
                    806:        }
                    807:     }
1.620     albertel  808:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www       809:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                    810:     return $total;
                    811: }
                    812: 
                    813: # ------------------------------------------------------- Validate an accesskey
                    814: 
                    815: sub validate_access_key {
                    816:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                    817:     $cdom=
1.620     albertel  818:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       819:     $cnum=
1.620     albertel  820:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    821:     $udom=$env{'user.domain'} unless (defined($udom));
                    822:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www       823:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel  824:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www       825: }
                    826: 
                    827: # ------------------------------------- Find the section of student in a course
1.652     albertel  828: sub devalidate_getsection_cache {
                    829:     my ($udom,$unam,$courseid)=@_;
                    830:     $courseid=~s/\_/\//g;
                    831:     $courseid=~s/^(\w)/\/$1/;
                    832:     my $hashid="$udom:$unam:$courseid";
                    833:     &devalidate_cache_new('getsection',$hashid);
                    834: }
1.298     matthew   835: 
                    836: sub getsection {
                    837:     my ($udom,$unam,$courseid)=@_;
1.599     albertel  838:     my $cachetime=1800;
1.298     matthew   839:     $courseid=~s/\_/\//g;
                    840:     $courseid=~s/^(\w)/\/$1/;
1.551     albertel  841: 
                    842:     my $hashid="$udom:$unam:$courseid";
1.599     albertel  843:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel  844:     if (defined($cached)) { return $result; }
                    845: 
1.298     matthew   846:     my %Pending; 
                    847:     my %Expired;
                    848:     #
                    849:     # Each role can either have not started yet (pending), be active, 
                    850:     #    or have expired.
                    851:     #
                    852:     # If there is an active role, we are done.
                    853:     #
                    854:     # If there is more than one role which has not started yet, 
                    855:     #     choose the one which will start sooner
                    856:     # If there is one role which has not started yet, return it.
                    857:     #
                    858:     # If there is more than one expired role, choose the one which ended last.
                    859:     # If there is a role which has expired, return it.
                    860:     #
                    861:     foreach (split(/\&/,&reply('dump:'.$udom.':'.$unam.':roles',
                    862:                         &homeserver($unam,$udom)))) {
                    863:         my ($key,$value)=split(/\=/,$_);
                    864:         $key=&unescape($key);
1.479     albertel  865:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew   866:         my $section=$1;
                    867:         if ($key eq $courseid.'_st') { $section=''; }
                    868:         my ($dummy,$end,$start)=split(/\_/,&unescape($value));
                    869:         my $now=time;
1.548     albertel  870:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew   871:             $Expired{$end}=$section;
                    872:             next;
                    873:         }
1.548     albertel  874:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew   875:             $Pending{$start}=$section;
                    876:             next;
                    877:         }
1.599     albertel  878:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew   879:     }
                    880:     #
                    881:     # Presumedly there will be few matching roles from the above
                    882:     # loop and the sorting time will be negligible.
                    883:     if (scalar(keys(%Pending))) {
                    884:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel  885:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew   886:     } 
                    887:     if (scalar(keys(%Expired))) {
                    888:         my @sorted = sort {$a <=> $b} keys(%Expired);
                    889:         my $time = pop(@sorted);
1.599     albertel  890:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew   891:     }
1.599     albertel  892:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew   893: }
1.70      www       894: 
1.599     albertel  895: sub save_cache {
                    896:     &purge_remembered();
1.722     albertel  897:     #&Apache::loncommon::validate_page();
1.620     albertel  898:     undef(%env);
1.780     albertel  899:     undef($env_loaded);
1.599     albertel  900: }
1.452     albertel  901: 
1.599     albertel  902: my $to_remember=-1;
                    903: my %remembered;
                    904: my %accessed;
                    905: my $kicks=0;
                    906: my $hits=0;
                    907: sub devalidate_cache_new {
                    908:     my ($name,$id,$debug) = @_;
                    909:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
                    910:     $id=&escape($name.':'.$id);
                    911:     $memcache->delete($id);
                    912:     delete($remembered{$id});
                    913:     delete($accessed{$id});
                    914: }
                    915: 
                    916: sub is_cached_new {
                    917:     my ($name,$id,$debug) = @_;
                    918:     $id=&escape($name.':'.$id);
                    919:     if (exists($remembered{$id})) {
                    920: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                    921: 	$accessed{$id}=[&gettimeofday()];
                    922: 	$hits++;
                    923: 	return ($remembered{$id},1);
                    924:     }
                    925:     my $value = $memcache->get($id);
                    926:     if (!(defined($value))) {
                    927: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel  928: 	return (undef,undef);
1.416     albertel  929:     }
1.599     albertel  930:     if ($value eq '__undef__') {
                    931: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                    932: 	$value=undef;
                    933:     }
                    934:     &make_room($id,$value,$debug);
                    935:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                    936:     return ($value,1);
                    937: }
                    938: 
                    939: sub do_cache_new {
                    940:     my ($name,$id,$value,$time,$debug) = @_;
                    941:     $id=&escape($name.':'.$id);
                    942:     my $setvalue=$value;
                    943:     if (!defined($setvalue)) {
                    944: 	$setvalue='__undef__';
                    945:     }
1.623     albertel  946:     if (!defined($time) ) {
                    947: 	$time=600;
                    948:     }
1.599     albertel  949:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.600     albertel  950:     $memcache->set($id,$setvalue,$time);
                    951:     # need to make a copy of $value
                    952:     #&make_room($id,$value,$debug);
1.599     albertel  953:     return $value;
                    954: }
                    955: 
                    956: sub make_room {
                    957:     my ($id,$value,$debug)=@_;
                    958:     $remembered{$id}=$value;
                    959:     if ($to_remember<0) { return; }
                    960:     $accessed{$id}=[&gettimeofday()];
                    961:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                    962:     my $to_kick;
                    963:     my $max_time=0;
                    964:     foreach my $other (keys(%accessed)) {
                    965: 	if (&tv_interval($accessed{$other}) > $max_time) {
                    966: 	    $to_kick=$other;
                    967: 	    $max_time=&tv_interval($accessed{$other});
                    968: 	}
                    969:     }
                    970:     delete($remembered{$to_kick});
                    971:     delete($accessed{$to_kick});
                    972:     $kicks++;
                    973:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel  974:     return;
                    975: }
                    976: 
1.599     albertel  977: sub purge_remembered {
1.604     albertel  978:     #&logthis("Tossing ".scalar(keys(%remembered)));
                    979:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel  980:     undef(%remembered);
                    981:     undef(%accessed);
1.428     albertel  982: }
1.70      www       983: # ------------------------------------- Read an entry from a user's environment
                    984: 
                    985: sub userenvironment {
                    986:     my ($udom,$unam,@what)=@_;
                    987:     my %returnhash=();
                    988:     my @answer=split(/\&/,
                    989:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
                    990:                       &homeserver($unam,$udom)));
                    991:     my $i;
                    992:     for ($i=0;$i<=$#what;$i++) {
                    993: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                    994:     }
                    995:     return %returnhash;
1.1       albertel  996: }
                    997: 
1.617     albertel  998: # ---------------------------------------------------------- Get a studentphoto
                    999: sub studentphoto {
                   1000:     my ($udom,$unam,$ext) = @_;
                   1001:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1002:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1003:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1004:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1005:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1006:             } else {
                   1007:                 my ($result,$perm_reqd)=
1.707     albertel 1008: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1009:                 if ($result eq 'ok') {
                   1010:                     if (!($perm_reqd eq 'yes')) {
                   1011:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1012:                     }
                   1013:                 }
                   1014:             }
                   1015:         }
                   1016:     } else {
                   1017:         my ($result,$perm_reqd) = 
1.707     albertel 1018: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1019:         if ($result eq 'ok') {
                   1020:             if (!($perm_reqd eq 'yes')) {
                   1021:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1022:             }
                   1023:         }
                   1024:     }
                   1025:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1026: }
                   1027: 
                   1028: sub retrievestudentphoto {
                   1029:     my ($udom,$unam,$ext,$type) = @_;
                   1030:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1031:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1032:     if ($ret eq 'ok') {
                   1033:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1034:         if ($type eq 'thumbnail') {
                   1035:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1036:         }
                   1037:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1038:         return $tokenurl;
                   1039:     } else {
                   1040:         if ($type eq 'thumbnail') {
                   1041:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1042:         } else { 
                   1043:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1044:         }
1.617     albertel 1045:     }
                   1046: }
                   1047: 
1.263     www      1048: # -------------------------------------------------------------------- New chat
                   1049: 
                   1050: sub chatsend {
1.724     raeburn  1051:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1052:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1053:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1054:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1055:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1056: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1057: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1058: }
                   1059: 
                   1060: # ------------------------------------------ Find current version of a resource
                   1061: 
                   1062: sub getversion {
                   1063:     my $fname=&clutter(shift);
                   1064:     unless ($fname=~/^\/res\//) { return -1; }
                   1065:     return &currentversion(&filelocation('',$fname));
                   1066: }
                   1067: 
                   1068: sub currentversion {
                   1069:     my $fname=shift;
1.599     albertel 1070:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1071:     if (defined($cached)) { return $result; }
1.292     www      1072:     my $author=$fname;
                   1073:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1074:     my ($udom,$uname)=split(/\//,$author);
                   1075:     my $home=homeserver($uname,$udom);
                   1076:     if ($home eq 'no_host') { 
                   1077:         return -1; 
                   1078:     }
                   1079:     my $answer=reply("currentversion:$fname",$home);
                   1080:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1081: 	return -1;
                   1082:     }
1.599     albertel 1083:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1084: }
                   1085: 
1.1       albertel 1086: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1087: 
1.1       albertel 1088: sub subscribe {
                   1089:     my $fname=shift;
1.761     raeburn  1090:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1091:     $fname=~s/[\n\r]//g;
1.1       albertel 1092:     my $author=$fname;
                   1093:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1094:     my ($udom,$uname)=split(/\//,$author);
                   1095:     my $home=homeserver($uname,$udom);
1.335     albertel 1096:     if ($home eq 'no_host') {
                   1097:         return 'not_found';
1.1       albertel 1098:     }
                   1099:     my $answer=reply("sub:$fname",$home);
1.64      www      1100:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1101: 	$answer.=' by '.$home;
                   1102:     }
1.1       albertel 1103:     return $answer;
                   1104: }
                   1105:     
1.8       www      1106: # -------------------------------------------------------------- Replicate file
                   1107: 
                   1108: sub repcopy {
                   1109:     my $filename=shift;
1.23      www      1110:     $filename=~s/\/+/\//g;
1.607     raeburn  1111:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1112:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1113:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1114: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1115: 	return &repcopy_userfile($filename);
                   1116:     }
1.532     albertel 1117:     $filename=~s/[\n\r]//g;
1.8       www      1118:     my $transname="$filename.in.transfer";
1.607     raeburn  1119:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1120:     my $remoteurl=subscribe($filename);
1.64      www      1121:     if ($remoteurl =~ /^con_lost by/) {
                   1122: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1123:            return 'unavailable';
1.8       www      1124:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1125: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1126: 	   return 'not_found';
1.64      www      1127:     } elsif ($remoteurl =~ /^rejected by/) {
                   1128: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1129:            return 'forbidden';
1.20      www      1130:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1131:            return 'ok';
1.8       www      1132:     } else {
1.290     www      1133:         my $author=$filename;
                   1134:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1135:         my ($udom,$uname)=split(/\//,$author);
                   1136:         my $home=homeserver($uname,$udom);
                   1137:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1138:            my @parts=split(/\//,$filename);
                   1139:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1140:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1141:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1142: 	       return 'bad_request';
1.8       www      1143:            }
                   1144:            my $count;
                   1145:            for ($count=5;$count<$#parts;$count++) {
                   1146:                $path.="/$parts[$count]";
                   1147:                if ((-e $path)!=1) {
                   1148: 		   mkdir($path,0777);
                   1149:                }
                   1150:            }
                   1151:            my $ua=new LWP::UserAgent;
                   1152:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1153:            my $response=$ua->request($request,$transname);
                   1154:            if ($response->is_error()) {
                   1155: 	       unlink($transname);
                   1156:                my $message=$response->status_line;
1.672     albertel 1157:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      1158:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1159:                return 'unavailable';
1.8       www      1160:            } else {
1.16      www      1161: 	       if ($remoteurl!~/\.meta$/) {
                   1162:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1163:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1164:                   if ($mresponse->is_error()) {
                   1165: 		      unlink($filename.'.meta');
                   1166:                       &logthis(
1.672     albertel 1167:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      1168:                   }
                   1169: 	       }
1.8       www      1170:                rename($transname,$filename);
1.607     raeburn  1171:                return 'ok';
1.8       www      1172:            }
1.290     www      1173:        }
1.8       www      1174:     }
1.330     www      1175: }
                   1176: 
                   1177: # ------------------------------------------------ Get server side include body
                   1178: sub ssi_body {
1.381     albertel 1179:     my ($filelink,%form)=@_;
1.606     matthew  1180:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1181:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1182:     }
1.330     www      1183:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
1.381     albertel 1184:                                      &ssi($filelink,%form));
1.778     albertel 1185:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1186:     $output=~s/^.*?\<body[^\>]*\>//si;
                   1187:     $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
1.330     www      1188:     return $output;
1.8       www      1189: }
                   1190: 
1.15      www      1191: # --------------------------------------------------------- Server Side Include
                   1192: 
1.782     albertel 1193: sub absolute_url {
                   1194:     my ($host_name) = @_;
                   1195:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   1196:     if ($host_name eq '') {
                   1197: 	$host_name = $ENV{'SERVER_NAME'};
                   1198:     }
                   1199:     return $protocol.$host_name;
                   1200: }
                   1201: 
1.15      www      1202: sub ssi {
                   1203: 
1.23      www      1204:     my ($fn,%form)=@_;
1.15      www      1205: 
                   1206:     my $ua=new LWP::UserAgent;
1.23      www      1207:     
                   1208:     my $request;
1.711     albertel 1209: 
                   1210:     $form{'no_update_last_known'}=1;
                   1211: 
1.23      www      1212:     if (%form) {
1.782     albertel 1213:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.201     albertel 1214:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www      1215:     } else {
1.782     albertel 1216:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      1217:     }
                   1218: 
1.15      www      1219:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1220:     my $response=$ua->request($request);
                   1221: 
1.324     www      1222:     return $response->content;
                   1223: }
                   1224: 
                   1225: sub externalssi {
                   1226:     my ($url)=@_;
                   1227:     my $ua=new LWP::UserAgent;
                   1228:     my $request=new HTTP::Request('GET',$url);
                   1229:     my $response=$ua->request($request);
1.15      www      1230:     return $response->content;
                   1231: }
1.254     www      1232: 
1.492     albertel 1233: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1234: 
                   1235: sub allowuploaded {
                   1236:     my ($srcurl,$url)=@_;
                   1237:     $url=&clutter(&declutter($url));
                   1238:     my $dir=$url;
                   1239:     $dir=~s/\/[^\/]+$//;
                   1240:     my %httpref=();
                   1241:     my $httpurl=&hreflocation('',$url);
                   1242:     $httpref{'httpref.'.$httpurl}=$srcurl;
                   1243:     &Apache::lonnet::appenv(%httpref);
1.254     www      1244: }
1.477     raeburn  1245: 
1.478     albertel 1246: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 1247: # input: action, courseID, current domain, intended
1.637     raeburn  1248: #        path to file, source of file, instruction to parse file for objects,
                   1249: #        ref to hash for embedded objects,
                   1250: #        ref to hash for codebase of java objects.
                   1251: #
1.485     raeburn  1252: # output: url to file (if action was uploaddoc), 
                   1253: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  1254: #
1.478     albertel 1255: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   1256: # course.
1.477     raeburn  1257: #
1.478     albertel 1258: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1259: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   1260: #          course's home server.
1.477     raeburn  1261: #
1.478     albertel 1262: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   1263: #          be copied from $source (current location) to 
                   1264: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1265: #         and will then be copied to
                   1266: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   1267: #         course's home server.
1.485     raeburn  1268: #
1.481     raeburn  1269: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 1270: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  1271: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1272: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   1273: #         in course's home server.
1.637     raeburn  1274: #
1.477     raeburn  1275: 
                   1276: sub process_coursefile {
1.638     albertel 1277:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  1278:     my $fetchresult;
1.638     albertel 1279:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  1280:     if ($action eq 'propagate') {
1.638     albertel 1281:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1282: 			     $home);
1.481     raeburn  1283:     } else {
1.477     raeburn  1284:         my $fpath = '';
                   1285:         my $fname = $file;
1.478     albertel 1286:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  1287:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  1288:         my $filepath = &build_filepath($fpath);
1.481     raeburn  1289:         if ($action eq 'copy') {
                   1290:             if ($source eq '') {
                   1291:                 $fetchresult = 'no source file';
                   1292:                 return $fetchresult;
                   1293:             } else {
                   1294:                 my $destination = $filepath.'/'.$fname;
                   1295:                 rename($source,$destination);
                   1296:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1297:                                  $home);
1.481     raeburn  1298:             }
                   1299:         } elsif ($action eq 'uploaddoc') {
                   1300:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 1301:             print $fh $env{'form.'.$source};
1.481     raeburn  1302:             close($fh);
1.637     raeburn  1303:             if ($parser eq 'parse') {
                   1304:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
                   1305:                 unless ($parse_result eq 'ok') {
                   1306:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   1307:                 }
                   1308:             }
1.477     raeburn  1309:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1310:                                  $home);
1.481     raeburn  1311:             if ($fetchresult eq 'ok') {
                   1312:                 return '/uploaded/'.$fpath.'/'.$fname;
                   1313:             } else {
                   1314:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1315:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  1316:                 return '/adm/notfound.html';
                   1317:             }
1.477     raeburn  1318:         }
                   1319:     }
1.485     raeburn  1320:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  1321:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1322:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  1323:     }
                   1324:     return $fetchresult;
                   1325: }
                   1326: 
1.637     raeburn  1327: sub build_filepath {
                   1328:     my ($fpath) = @_;
                   1329:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   1330:     unless ($fpath eq '') {
                   1331:         my @parts=split('/',$fpath);
                   1332:         foreach my $part (@parts) {
                   1333:             $filepath.= '/'.$part;
                   1334:             if ((-e $filepath)!=1) {
                   1335:                 mkdir($filepath,0777);
                   1336:             }
                   1337:         }
                   1338:     }
                   1339:     return $filepath;
                   1340: }
                   1341: 
                   1342: sub store_edited_file {
1.638     albertel 1343:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  1344:     my $file = $primary_url;
                   1345:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   1346:     my $fpath = '';
                   1347:     my $fname = $file;
                   1348:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   1349:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   1350:     my $filepath = &build_filepath($fpath);
                   1351:     open(my $fh,'>'.$filepath.'/'.$fname);
                   1352:     print $fh $content;
                   1353:     close($fh);
1.638     albertel 1354:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  1355:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1356: 			  $home);
1.637     raeburn  1357:     if ($$fetchresult eq 'ok') {
                   1358:         return '/uploaded/'.$fpath.'/'.$fname;
                   1359:     } else {
1.638     albertel 1360:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   1361: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  1362:         return '/adm/notfound.html';
                   1363:     }
                   1364: }
                   1365: 
1.531     albertel 1366: sub clean_filename {
                   1367:     my ($fname)=@_;
1.315     www      1368: # Replace Windows backslashes by forward slashes
1.257     www      1369:     $fname=~s/\\/\//g;
1.315     www      1370: # Get rid of everything but the actual filename
1.257     www      1371:     $fname=~s/^.*\/([^\/]+)$/$1/;
1.315     www      1372: # Replace spaces by underscores
                   1373:     $fname=~s/\s+/\_/g;
                   1374: # Replace all other weird characters by nothing
1.317     www      1375:     $fname=~s/[^\w\.\-]//g;
1.540     albertel 1376: # Replace all .\d. sequences with _\d. so they no longer look like version
                   1377: # numbers
                   1378:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 1379:     return $fname;
                   1380: }
                   1381: 
1.608     albertel 1382: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 1383: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 1384: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 1385: #        $coursedoc - if true up to the current course
                   1386: #                     if false
                   1387: #        $subdir - directory in userfile to store the file into
                   1388: #        $parser, $allfiles, $codebase - unknown
                   1389: #
                   1390: # output: url of file in userspace, or error: <message> 
                   1391: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 1392: 
                   1393: 
1.531     albertel 1394: sub userfileupload {
1.719     banghart 1395:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,$destudom)=@_;
1.531     albertel 1396:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 1397:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 1398:     $fname=&clean_filename($fname);
1.315     www      1399: # See if there is anything left
1.257     www      1400:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 1401:     chop($env{'form.'.$formname});
1.523     raeburn  1402:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   1403:         my $now = time;
                   1404:         my $filepath = 'tmp/helprequests/'.$now;
                   1405:         my @parts=split(/\//,$filepath);
                   1406:         my $fullpath = $perlvar{'lonDaemons'};
                   1407:         for (my $i=0;$i<@parts;$i++) {
                   1408:             $fullpath .= '/'.$parts[$i];
                   1409:             if ((-e $fullpath)!=1) {
                   1410:                 mkdir($fullpath,0777);
                   1411:             }
                   1412:         }
                   1413:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 1414:         print $fh $env{'form.'.$formname};
1.523     raeburn  1415:         close($fh);
1.741     raeburn  1416:         return $fullpath.'/'.$fname;
                   1417:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   1418:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   1419:                        '_'.$env{'user.domain'}.'/pending';
                   1420:         my @parts=split(/\//,$filepath);
                   1421:         my $fullpath = $perlvar{'lonDaemons'};
                   1422:         for (my $i=0;$i<@parts;$i++) {
                   1423:             $fullpath .= '/'.$parts[$i];
                   1424:             if ((-e $fullpath)!=1) {
                   1425:                 mkdir($fullpath,0777);
                   1426:             }
                   1427:         }
                   1428:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   1429:         print $fh $env{'form.'.$formname};
                   1430:         close($fh);
                   1431:         return $fullpath.'/'.$fname;
1.523     raeburn  1432:     }
1.719     banghart 1433:     
1.258     www      1434: # Create the directory if not present
1.493     albertel 1435:     $fname="$subdir/$fname";
1.259     www      1436:     if ($coursedoc) {
1.638     albertel 1437: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1438: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  1439:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 1440:             return &finishuserfileupload($docuname,$docudom,
                   1441: 					 $formname,$fname,$parser,$allfiles,
                   1442: 					 $codebase);
1.481     raeburn  1443:         } else {
1.620     albertel 1444:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 1445:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   1446: 				       $fname,$formname,$parser,
                   1447: 				       $allfiles,$codebase);
1.481     raeburn  1448:         }
1.719     banghart 1449:     } elsif (defined($destuname)) {
                   1450:         my $docuname=$destuname;
                   1451:         my $docudom=$destudom;
                   1452: 	return &finishuserfileupload($docuname,$docudom,$formname,
                   1453: 				     $fname,$parser,$allfiles,$codebase);
                   1454:         
1.259     www      1455:     } else {
1.638     albertel 1456:         my $docuname=$env{'user.name'};
                   1457:         my $docudom=$env{'user.domain'};
1.714     raeburn  1458:         if (exists($env{'form.group'})) {
                   1459:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1460:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1461:         }
1.638     albertel 1462: 	return &finishuserfileupload($docuname,$docudom,$formname,
                   1463: 				     $fname,$parser,$allfiles,$codebase);
1.259     www      1464:     }
1.271     www      1465: }
                   1466: 
                   1467: sub finishuserfileupload {
1.638     albertel 1468:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase) = @_;
1.477     raeburn  1469:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      1470:     my $filepath=$perlvar{'lonDocRoot'};
1.494     albertel 1471:     my ($fnamepath,$file);
                   1472:     $file=$fname;
                   1473:     if ($fname=~m|/|) {
                   1474:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   1475: 	$path.=$fnamepath.'/';
                   1476:     }
1.259     www      1477:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      1478:     my $count;
                   1479:     for ($count=4;$count<=$#parts;$count++) {
                   1480:         $filepath.="/$parts[$count]";
                   1481:         if ((-e $filepath)!=1) {
                   1482: 	    mkdir($filepath,0777);
                   1483:         }
                   1484:     }
                   1485: # Save the file
                   1486:     {
1.701     albertel 1487: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   1488: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   1489: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   1490: 	    return '/adm/notfound.html';
                   1491: 	}
                   1492: 	if (!print FH ($env{'form.'.$formname})) {
                   1493: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   1494: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   1495: 	    return '/adm/notfound.html';
                   1496: 	}
1.570     albertel 1497: 	close(FH);
1.258     www      1498:     }
1.637     raeburn  1499:     if ($parser eq 'parse') {
1.638     albertel 1500:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
                   1501: 						   $codebase);
1.637     raeburn  1502:         unless ($parse_result eq 'ok') {
1.638     albertel 1503:             &logthis('Failed to parse '.$filepath.$file.
                   1504: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  1505:         }
                   1506:     }
1.259     www      1507: # Notify homeserver to grep it
                   1508: #
1.638     albertel 1509:     my $docuhome=&homeserver($docuname,$docudom);
1.494     albertel 1510:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      1511:     if ($fetchresult eq 'ok') {
1.259     www      1512: #
1.258     www      1513: # Return the URL to it
1.494     albertel 1514:         return '/uploaded/'.$path.$file;
1.263     www      1515:     } else {
1.494     albertel 1516:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   1517: 		 ': '.$fetchresult);
1.263     www      1518:         return '/adm/notfound.html';
                   1519:     }    
1.493     albertel 1520: }
                   1521: 
1.637     raeburn  1522: sub extract_embedded_items {
1.648     raeburn  1523:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
1.637     raeburn  1524:     my @state = ();
                   1525:     my %javafiles = (
                   1526:                       codebase => '',
                   1527:                       code => '',
                   1528:                       archive => ''
                   1529:                     );
                   1530:     my %mediafiles = (
                   1531:                       src => '',
                   1532:                       movie => '',
                   1533:                      );
1.648     raeburn  1534:     my $p;
                   1535:     if ($content) {
                   1536:         $p = HTML::LCParser->new($content);
                   1537:     } else {
                   1538:         $p = HTML::LCParser->new($filepath.'/'.$file);
                   1539:     }
1.641     albertel 1540:     while (my $t=$p->get_token()) {
1.640     albertel 1541: 	if ($t->[0] eq 'S') {
                   1542: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
                   1543: 	    push (@state, $tagname);
1.648     raeburn  1544:             if (lc($tagname) eq 'allow') {
                   1545:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   1546:             }
1.640     albertel 1547: 	    if (lc($tagname) eq 'img') {
                   1548: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   1549: 	    }
1.645     raeburn  1550:             if (lc($tagname) eq 'script') {
                   1551:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   1552:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   1553:                 } else {
                   1554:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   1555:                 }
                   1556:             }
                   1557:             if (lc($tagname) eq 'link') {
                   1558:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   1559:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   1560:                 }
                   1561:             }
1.640     albertel 1562: 	    if (lc($tagname) eq 'object' ||
                   1563: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   1564: 		foreach my $item (keys(%javafiles)) {
                   1565: 		    $javafiles{$item} = '';
                   1566: 		}
                   1567: 	    }
                   1568: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   1569: 		my $name = lc($attr->{'name'});
                   1570: 		foreach my $item (keys(%javafiles)) {
                   1571: 		    if ($name eq $item) {
                   1572: 			$javafiles{$item} = $attr->{'value'};
                   1573: 			last;
                   1574: 		    }
                   1575: 		}
                   1576: 		foreach my $item (keys(%mediafiles)) {
                   1577: 		    if ($name eq $item) {
                   1578: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   1579: 			last;
                   1580: 		    }
                   1581: 		}
                   1582: 	    }
                   1583: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   1584: 		foreach my $item (keys(%javafiles)) {
                   1585: 		    if ($attr->{$item}) {
                   1586: 			$javafiles{$item} = $attr->{$item};
                   1587: 			last;
                   1588: 		    }
                   1589: 		}
                   1590: 		foreach my $item (keys(%mediafiles)) {
                   1591: 		    if ($attr->{$item}) {
                   1592: 			&add_filetype($allfiles,$attr->{$item},$item);
                   1593: 			last;
                   1594: 		    }
                   1595: 		}
                   1596: 	    }
                   1597: 	} elsif ($t->[0] eq 'E') {
                   1598: 	    my ($tagname) = ($t->[1]);
                   1599: 	    if ($javafiles{'codebase'} ne '') {
                   1600: 		$javafiles{'codebase'} .= '/';
                   1601: 	    }  
                   1602: 	    if (lc($tagname) eq 'applet' ||
                   1603: 		lc($tagname) eq 'object' ||
                   1604: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   1605: 		) {
                   1606: 		foreach my $item (keys(%javafiles)) {
                   1607: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   1608: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   1609: 			&add_filetype($allfiles,$file,$item);
                   1610: 		    }
                   1611: 		}
                   1612: 	    } 
                   1613: 	    pop @state;
                   1614: 	}
                   1615:     }
1.637     raeburn  1616:     return 'ok';
                   1617: }
                   1618: 
1.639     albertel 1619: sub add_filetype {
                   1620:     my ($allfiles,$file,$type)=@_;
                   1621:     if (exists($allfiles->{$file})) {
                   1622: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   1623: 	    push(@{$allfiles->{$file}}, &escape($type));
                   1624: 	}
                   1625:     } else {
                   1626: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  1627:     }
                   1628: }
                   1629: 
1.493     albertel 1630: sub removeuploadedurl {
                   1631:     my ($url)=@_;
                   1632:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613     albertel 1633:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 1634: }
                   1635: 
                   1636: sub removeuserfile {
                   1637:     my ($docuname,$docudom,$fname)=@_;
                   1638:     my $home=&homeserver($docuname,$docudom);
                   1639:     return &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.257     www      1640: }
1.15      www      1641: 
1.530     albertel 1642: sub mkdiruserfile {
                   1643:     my ($docuname,$docudom,$dir)=@_;
                   1644:     my $home=&homeserver($docuname,$docudom);
                   1645:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   1646: }
                   1647: 
1.531     albertel 1648: sub renameuserfile {
                   1649:     my ($docuname,$docudom,$old,$new)=@_;
                   1650:     my $home=&homeserver($docuname,$docudom);
                   1651:     return &reply("renameuserfile:$docudom:$docuname:".&escape("$old").':'.
                   1652: 		  &escape("$new"),$home);
                   1653: }
                   1654: 
1.14      www      1655: # ------------------------------------------------------------------------- Log
                   1656: 
                   1657: sub log {
                   1658:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      1659:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      1660: }
                   1661: 
                   1662: # ------------------------------------------------------------------ Course Log
1.352     www      1663: #
                   1664: # This routine flushes several buffers of non-mission-critical nature
                   1665: #
1.157     www      1666: 
                   1667: sub flushcourselogs {
1.352     www      1668:     &logthis('Flushing log buffers');
                   1669: #
                   1670: # course logs
                   1671: # This is a log of all transactions in a course, which can be used
                   1672: # for data mining purposes
                   1673: #
                   1674: # It also collects the courseid database, which lists last transaction
                   1675: # times and course titles for all courseids
                   1676: #
                   1677:     my %courseidbuffer=();
1.191     harris41 1678:     foreach (keys %courselogs) {
1.157     www      1679:         my $crsid=$_;
1.352     www      1680:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      1681: 		          &escape($courselogs{$crsid}),
                   1682: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      1683: 	    delete $courselogs{$crsid};
                   1684:         } else {
                   1685:             &logthis('Failed to flush log buffer for '.$crsid);
                   1686:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 1687:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      1688:                         " exceeded maximum size, deleting.</font>");
                   1689:                delete $courselogs{$crsid};
                   1690:             }
1.352     www      1691:         }
                   1692:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
                   1693:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
1.516     raeburn  1694: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  1695:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.352     www      1696:         } else {
                   1697:            $courseidbuffer{$coursehombuf{$crsid}}=
1.516     raeburn  1698: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  1699:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.571     raeburn  1700:         }
1.191     harris41 1701:     }
1.352     www      1702: #
                   1703: # Write course id database (reverse lookup) to homeserver of courses 
                   1704: # Is used in pickcourse
                   1705: #
                   1706:     foreach (keys %courseidbuffer) {
1.353     www      1707:         &courseidput($hostdom{$_},$courseidbuffer{$_},$_);
1.352     www      1708:     }
                   1709: #
                   1710: # File accesses
                   1711: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   1712: #
1.449     matthew  1713:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  1714:         if ($entry =~ /___count$/) {
                   1715:             my ($dom,$name);
                   1716:             ($dom,$name,undef)=($entry=~m:___(\w+)/(\w+)/(.*)___count$:);
                   1717:             if (! defined($dom) || $dom eq '' || 
                   1718:                 ! defined($name) || $name eq '') {
1.620     albertel 1719:                 my $cid = $env{'request.course.id'};
                   1720:                 $dom  = $env{'request.'.$cid.'.domain'};
                   1721:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  1722:             }
1.450     matthew  1723:             my $value = $accesshash{$entry};
                   1724:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   1725:             my %temphash=($url => $value);
1.449     matthew  1726:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   1727:             if ($result eq 'ok') {
                   1728:                 delete $accesshash{$entry};
                   1729:             } elsif ($result eq 'unknown_cmd') {
                   1730:                 # Target server has old code running on it.
1.450     matthew  1731:                 my %temphash=($entry => $value);
1.449     matthew  1732:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1733:                     delete $accesshash{$entry};
                   1734:                 }
                   1735:             }
                   1736:         } else {
1.458     matthew  1737:             my ($dom,$name) = ($entry=~m:___(\w+)/(\w+)/(.*)___(\w+)$:);
1.450     matthew  1738:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  1739:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1740:                 delete $accesshash{$entry};
                   1741:             }
1.185     www      1742:         }
1.191     harris41 1743:     }
1.352     www      1744: #
                   1745: # Roles
                   1746: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   1747: #
1.349     www      1748:     foreach (keys %userrolehash) {
                   1749:         my $entry=$_;
1.351     www      1750:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      1751: 	    split(/\:/,$entry);
                   1752:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      1753:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      1754:                 $rudom,$runame) eq 'ok') {
                   1755: 	    delete $userrolehash{$entry};
                   1756:         }
                   1757:     }
1.662     raeburn  1758: #
                   1759: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   1760: #
                   1761:     my %domrolebuffer = ();
                   1762:     foreach my $entry (keys %domainrolehash) {
                   1763:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split/:/,$entry;
                   1764:         if ($domrolebuffer{$rudom}) {
                   1765:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   1766:                       '='.&escape($domainrolehash{$entry});
                   1767:         } else {
                   1768:             $domrolebuffer{$rudom}.=&escape($entry).
                   1769:                       '='.&escape($domainrolehash{$entry});
                   1770:         }
                   1771:         delete $domainrolehash{$entry};
                   1772:     }
                   1773:     foreach my $dom (keys(%domrolebuffer)) {
                   1774:         foreach my $tryserver (keys %libserv) {
                   1775:             if ($hostdom{$tryserver} eq $dom) {
                   1776:                 unless (&reply('domroleput:'.$dom.':'.
                   1777:                   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   1778:                     &logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   1779:                 }
                   1780:             }
                   1781:         }
                   1782:     }
1.186     www      1783:     $dumpcount++;
1.157     www      1784: }
                   1785: 
                   1786: sub courselog {
                   1787:     my $what=shift;
1.158     www      1788:     $what=time.':'.$what;
1.620     albertel 1789:     unless ($env{'request.course.id'}) { return ''; }
                   1790:     $coursedombuf{$env{'request.course.id'}}=
                   1791:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   1792:     $coursenumbuf{$env{'request.course.id'}}=
                   1793:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   1794:     $coursehombuf{$env{'request.course.id'}}=
                   1795:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   1796:     $coursedescrbuf{$env{'request.course.id'}}=
                   1797:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   1798:     $courseinstcodebuf{$env{'request.course.id'}}=
                   1799:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   1800:     $courseownerbuf{$env{'request.course.id'}}=
                   1801:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  1802:     $coursetypebuf{$env{'request.course.id'}}=
                   1803:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 1804:     if (defined $courselogs{$env{'request.course.id'}}) {
                   1805: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      1806:     } else {
1.620     albertel 1807: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      1808:     }
1.620     albertel 1809:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      1810: 	&flushcourselogs();
                   1811:     }
1.158     www      1812: }
                   1813: 
                   1814: sub courseacclog {
                   1815:     my $fnsymb=shift;
1.620     albertel 1816:     unless ($env{'request.course.id'}) { return ''; }
                   1817:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 1818:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      1819:         $what.=':POST';
1.583     matthew  1820:         # FIXME: Probably ought to escape things....
1.620     albertel 1821: 	foreach (keys %env) {
1.158     www      1822:             if ($_=~/^form\.(.*)/) {
1.620     albertel 1823: 		$what.=':'.$1.'='.$env{$_};
1.158     www      1824:             }
1.191     harris41 1825:         }
1.583     matthew  1826:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   1827:         # FIXME: We should not be depending on a form parameter that someone
                   1828:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 1829:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  1830:             $what.= ':POST';
                   1831:             # FIXME: Probably ought to escape things....
                   1832:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   1833:                                  'crsdiscuss') {
1.620     albertel 1834:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  1835:             }
                   1836:         }
1.158     www      1837:     }
                   1838:     &courselog($what);
1.149     www      1839: }
                   1840: 
1.185     www      1841: sub countacc {
                   1842:     my $url=&declutter(shift);
1.458     matthew  1843:     return if (! defined($url) || $url eq '');
1.620     albertel 1844:     unless ($env{'request.course.id'}) { return ''; }
                   1845:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      1846:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  1847:     $accesshash{$key}++;
1.185     www      1848: }
1.349     www      1849: 
1.361     www      1850: sub linklog {
                   1851:     my ($from,$to)=@_;
                   1852:     $from=&declutter($from);
                   1853:     $to=&declutter($to);
                   1854:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   1855:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   1856: }
                   1857:   
1.349     www      1858: sub userrolelog {
                   1859:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  1860:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  1861:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  1862:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   1863:         ($trole=~/^ta/)) {
1.350     www      1864:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   1865:        $userrolehash
                   1866:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      1867:                     =$tend.':'.$tstart;
1.662     raeburn  1868:     }
                   1869:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   1870:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   1871:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   1872:         ($trole=~/^sc/)) {
                   1873:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   1874:        $domainrolehash
                   1875:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   1876:                     = $tend.':'.$tstart;
                   1877:     }
1.351     www      1878: }
                   1879: 
                   1880: sub get_course_adv_roles {
                   1881:     my $cid=shift;
1.620     albertel 1882:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      1883:     my %coursehash=&coursedescription($cid);
1.470     www      1884:     my %nothide=();
                   1885:     foreach (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   1886: 	$nothide{join(':',split(/[\@\:]/,$_))}=1;
                   1887:     }
1.351     www      1888:     my %returnhash=();
                   1889:     my %dumphash=
                   1890:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   1891:     my $now=time;
                   1892:     foreach (keys %dumphash) {
                   1893: 	my ($tend,$tstart)=split(/\:/,$dumphash{$_});
                   1894:         if (($tstart) && ($tstart<0)) { next; }
                   1895:         if (($tend) && ($tend<$now)) { next; }
                   1896:         if (($tstart) && ($now<$tstart)) { next; }
                   1897:         my ($role,$username,$domain,$section)=split(/\:/,$_);
1.576     albertel 1898: 	if ($username eq '' || $domain eq '') { next; }
1.470     www      1899: 	if ((&privileged($username,$domain)) && 
                   1900: 	    (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 1901: 	if ($role eq 'cr') { next; }
1.351     www      1902:         my $key=&plaintext($role);
                   1903:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
                   1904:         if ($returnhash{$key}) {
                   1905: 	    $returnhash{$key}.=','.$username.':'.$domain;
                   1906:         } else {
                   1907:             $returnhash{$key}=$username.':'.$domain;
                   1908:         }
1.400     www      1909:      }
                   1910:     return %returnhash;
                   1911: }
                   1912: 
                   1913: sub get_my_roles {
                   1914:     my ($uname,$udom)=@_;
1.620     albertel 1915:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   1916:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.400     www      1917:     my %dumphash=
                   1918:             &dump('nohist_userroles',$udom,$uname);
                   1919:     my %returnhash=();
                   1920:     my $now=time;
                   1921:     foreach (keys %dumphash) {
                   1922: 	my ($tend,$tstart)=split(/\:/,$dumphash{$_});
                   1923:         if (($tstart) && ($tstart<0)) { next; }
                   1924:         if (($tend) && ($tend<$now)) { next; }
                   1925:         if (($tstart) && ($now<$tstart)) { next; }
                   1926:         my ($role,$username,$domain,$section)=split(/\:/,$_);
                   1927: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
1.373     www      1928:      }
                   1929:     return %returnhash;
1.399     www      1930: }
                   1931: 
                   1932: # ----------------------------------------------------- Frontpage Announcements
                   1933: #
                   1934: #
                   1935: 
                   1936: sub postannounce {
                   1937:     my ($server,$text)=@_;
                   1938:     unless (&allowed('psa',$hostdom{$server})) { return 'refused'; }
                   1939:     unless ($text=~/\w/) { $text=''; }
                   1940:     return &reply('setannounce:'.&escape($text),$server);
                   1941: }
                   1942: 
                   1943: sub getannounce {
1.448     albertel 1944: 
                   1945:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      1946: 	my $announcement='';
                   1947: 	while (<$fh>) { $announcement .=$_; }
1.448     albertel 1948: 	close($fh);
1.399     www      1949: 	if ($announcement=~/\w/) { 
                   1950: 	    return 
                   1951:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 1952:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      1953: 	} else {
                   1954: 	    return '';
                   1955: 	}
                   1956:     } else {
                   1957: 	return '';
                   1958:     }
1.351     www      1959: }
1.353     www      1960: 
                   1961: # ---------------------------------------------------------- Course ID routines
                   1962: # Deal with domain's nohist_courseid.db files
                   1963: #
                   1964: 
                   1965: sub courseidput {
                   1966:     my ($domain,$what,$coursehome)=@_;
                   1967:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   1968: }
                   1969: 
                   1970: sub courseiddump {
1.791     raeburn  1971:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok)=@_;
1.353     www      1972:     my %returnhash=();
1.355     www      1973:     unless ($domfilter) { $domfilter=''; }
1.353     www      1974:     foreach my $tryserver (keys %libserv) {
1.511     raeburn  1975:         if ( ($hostidflag == 1 && grep/^$tryserver$/,@{$hostidref}) || (!defined($hostidflag)) ) {
1.506     raeburn  1976: 	    if ((!$domfilter) || ($hostdom{$tryserver} eq $domfilter)) {
                   1977: 	        foreach (
                   1978:                  split(/\&/,&reply('courseiddump:'.$hostdom{$tryserver}.':'.
1.571     raeburn  1979: 			       $sincefilter.':'.&escape($descfilter).':'.
1.791     raeburn  1980:                                &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter).':'.&escape($typefilter).':'.&escape($regexp_ok),
1.354     www      1981:                                $tryserver))) {
1.506     raeburn  1982: 		    my ($key,$value)=split(/\=/,$_);
                   1983:                     if (($key) && ($value)) {
1.516     raeburn  1984: 		        $returnhash{&unescape($key)}=$value;
1.506     raeburn  1985:                     }
1.353     www      1986:                 }
                   1987:             }
                   1988:         }
                   1989:     }
                   1990:     return %returnhash;
                   1991: }
                   1992: 
1.658     raeburn  1993: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  1994: 
                   1995: sub dcmailput {
1.685     raeburn  1996:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  1997:     my $status = &Apache::lonnet::critical(
1.740     www      1998:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   1999:        &escape($message),$server);
1.662     raeburn  2000:     return $status;
                   2001: }
                   2002: 
1.658     raeburn  2003: sub dcmaildump {
                   2004:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  2005:     my %returnhash=();
                   2006:     if (exists($domain_primary{$dom})) {
                   2007:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   2008:                                                          &escape($enddate).':';
                   2009: 	my @esc_senders=map { &escape($_)} @$senders;
                   2010: 	$cmd.=&escape(join('&',@esc_senders));
                   2011: 	foreach (split(/\&/,&reply($cmd,$domain_primary{$dom}))) {
                   2012:             my ($key,$value) = split(/\=/,$_);
                   2013:             if (($key) && ($value)) {
                   2014:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  2015:             }
                   2016:         }
                   2017:     }
                   2018:     return %returnhash;
                   2019: }
1.662     raeburn  2020: # ---------------------------------------------------------- Domain roles
                   2021: 
                   2022: sub get_domain_roles {
                   2023:     my ($dom,$roles,$startdate,$enddate)=@_;
                   2024:     if (undef($startdate) || $startdate eq '') {
                   2025:         $startdate = '.';
                   2026:     }
                   2027:     if (undef($enddate) || $enddate eq '') {
                   2028:         $enddate = '.';
                   2029:     }
                   2030:     my $rolelist = join(':',@{$roles});
                   2031:     my %personnel = ();
                   2032:     foreach my $tryserver (keys(%libserv)) {
                   2033:         if ($hostdom{$tryserver} eq $dom) {
                   2034:             %{$personnel{$tryserver}}=();
                   2035:             foreach (
                   2036:                 split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   2037:                    &escape($startdate).':'.&escape($enddate).':'.
                   2038:                    &escape($rolelist), $tryserver))) {
                   2039:                 my($key,$value) = split(/\=/,$_);
                   2040:                 if (($key) && ($value)) {
                   2041:                     $personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   2042:                 }
                   2043:             }
                   2044:         }
                   2045:     }
                   2046:     return %personnel;
                   2047: }
1.658     raeburn  2048: 
1.149     www      2049: # ----------------------------------------------------------- Check out an item
                   2050: 
1.504     albertel 2051: sub get_first_access {
                   2052:     my ($type,$argsymb)=@_;
1.790     albertel 2053:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2054:     if ($argsymb) { $symb=$argsymb; }
                   2055:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2056:     if ($type eq 'map') {
                   2057: 	$res=&symbread($map);
                   2058:     } else {
                   2059: 	$res=$symb;
                   2060:     }
                   2061:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   2062:     return $times{"$courseid\0$res"};
1.504     albertel 2063: }
                   2064: 
                   2065: sub set_first_access {
                   2066:     my ($type)=@_;
1.790     albertel 2067:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2068:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2069:     if ($type eq 'map') {
                   2070: 	$res=&symbread($map);
                   2071:     } else {
                   2072: 	$res=$symb;
                   2073:     }
                   2074:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 2075:     if (!$firstaccess) {
1.588     albertel 2076: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 2077:     }
                   2078:     return 'already_set';
1.504     albertel 2079: }
                   2080: 
1.149     www      2081: sub checkout {
                   2082:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   2083:     my $now=time;
                   2084:     my $lonhost=$perlvar{'lonHostID'};
                   2085:     my $infostr=&escape(
1.234     www      2086:                  'CHECKOUTTOKEN&'.
1.149     www      2087:                  $tuname.'&'.
                   2088:                  $tudom.'&'.
                   2089:                  $tcrsid.'&'.
                   2090:                  $symb.'&'.
                   2091: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   2092:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      2093:     if ($token=~/^error\:/) { 
1.672     albertel 2094:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2095:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2096:                  "</font>");
                   2097:         return ''; 
                   2098:     }
                   2099: 
1.149     www      2100:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   2101:     $token=~tr/a-z/A-Z/;
                   2102: 
1.153     www      2103:     my %infohash=('resource.0.outtoken' => $token,
                   2104:                   'resource.0.checkouttime' => $now,
                   2105:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      2106: 
                   2107:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2108:        return '';
1.151     www      2109:     } else {
1.672     albertel 2110:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2111:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2112:                  "</font>");
1.149     www      2113:     }    
                   2114: 
                   2115:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2116:                          &escape('Checkout '.$infostr.' - '.
                   2117:                                                  $token)) ne 'ok') {
                   2118: 	return '';
1.151     www      2119:     } else {
1.672     albertel 2120:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2121:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2122:                  "</font>");
1.149     www      2123:     }
1.151     www      2124:     return $token;
1.149     www      2125: }
                   2126: 
                   2127: # ------------------------------------------------------------ Check in an item
                   2128: 
                   2129: sub checkin {
                   2130:     my $token=shift;
1.150     www      2131:     my $now=time;
                   2132:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   2133:     $lonhost=~tr/A-Z/a-z/;
1.595     albertel 2134:     my $dtoken=$ta.'_'.$hostname{$lonhost}.'_'.$tb;
1.150     www      2135:     $dtoken=~s/\W/\_/g;
1.234     www      2136:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      2137:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   2138: 
1.154     www      2139:     unless (($tuname) && ($tudom)) {
                   2140:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   2141:         return '';
                   2142:     }
                   2143:     
                   2144:     unless (&allowed('mgr',$tcrsid)) {
                   2145:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 2146:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      2147:         return '';
                   2148:     }
                   2149: 
1.153     www      2150:     my %infohash=('resource.0.intoken' => $token,
                   2151:                   'resource.0.checkintime' => $now,
                   2152:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      2153: 
                   2154:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2155:        return '';
                   2156:     }    
                   2157: 
                   2158:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2159:                          &escape('Checkin - '.$token)) ne 'ok') {
                   2160: 	return '';
                   2161:     }
                   2162: 
                   2163:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      2164: }
                   2165: 
                   2166: # --------------------------------------------- Set Expire Date for Spreadsheet
                   2167: 
                   2168: sub expirespread {
                   2169:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 2170:     my $cid=$env{'request.course.id'}; 
1.110     www      2171:     if ($cid) {
                   2172:        my $now=time;
                   2173:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 2174:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   2175:                             $env{'course.'.$cid.'.num'}.
1.110     www      2176: 	        	    ':nohist_expirationdates:'.
                   2177:                             &escape($key).'='.$now,
1.620     albertel 2178:                             $env{'course.'.$cid.'.home'})
1.110     www      2179:     }
                   2180:     return 'ok';
1.14      www      2181: }
                   2182: 
1.109     www      2183: # ----------------------------------------------------- Devalidate Spreadsheets
                   2184: 
                   2185: sub devalidate {
1.325     www      2186:     my ($symb,$uname,$udom)=@_;
1.620     albertel 2187:     my $cid=$env{'request.course.id'}; 
1.109     www      2188:     if ($cid) {
1.391     matthew  2189:         # delete the stored spreadsheets for
                   2190:         # - the student level sheet of this user in course's homespace
                   2191:         # - the assessment level sheet for this resource 
                   2192:         #   for this user in user's homespace
1.553     albertel 2193: 	# - current conditional state info
1.325     www      2194: 	my $key=$uname.':'.$udom.':';
1.109     www      2195:         my $status=
1.299     matthew  2196: 	    &del('nohist_calculatedsheets',
1.391     matthew  2197: 		 [$key.'studentcalc:'],
1.620     albertel 2198: 		 $env{'course.'.$cid.'.domain'},
                   2199: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 2200: 		.' '.
                   2201: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  2202: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      2203:         unless ($status eq 'ok ok') {
                   2204:            &logthis('Could not devalidate spreadsheet '.
1.325     www      2205:                     $uname.' at '.$udom.' for '.
1.109     www      2206: 		    $symb.': '.$status);
1.133     albertel 2207:         }
1.553     albertel 2208: 	&delenv('user.state.'.$cid);
1.109     www      2209:     }
                   2210: }
                   2211: 
1.265     albertel 2212: sub get_scalar {
                   2213:     my ($string,$end) = @_;
                   2214:     my $value;
                   2215:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   2216: 	$value = $1;
                   2217:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   2218: 	$value = $1;
                   2219:     }
                   2220:     return &unescape($value);
                   2221: }
                   2222: 
                   2223: sub array2str {
                   2224:   my (@array) = @_;
                   2225:   my $result=&arrayref2str(\@array);
                   2226:   $result=~s/^__ARRAY_REF__//;
                   2227:   $result=~s/__END_ARRAY_REF__$//;
                   2228:   return $result;
                   2229: }
                   2230: 
1.204     albertel 2231: sub arrayref2str {
                   2232:   my ($arrayref) = @_;
1.265     albertel 2233:   my $result='__ARRAY_REF__';
1.204     albertel 2234:   foreach my $elem (@$arrayref) {
1.265     albertel 2235:     if(ref($elem) eq 'ARRAY') {
                   2236:       $result.=&arrayref2str($elem).'&';
                   2237:     } elsif(ref($elem) eq 'HASH') {
                   2238:       $result.=&hashref2str($elem).'&';
                   2239:     } elsif(ref($elem)) {
                   2240:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 2241:     } else {
                   2242:       $result.=&escape($elem).'&';
                   2243:     }
                   2244:   }
                   2245:   $result=~s/\&$//;
1.265     albertel 2246:   $result .= '__END_ARRAY_REF__';
1.204     albertel 2247:   return $result;
                   2248: }
                   2249: 
1.168     albertel 2250: sub hash2str {
1.204     albertel 2251:   my (%hash) = @_;
                   2252:   my $result=&hashref2str(\%hash);
1.265     albertel 2253:   $result=~s/^__HASH_REF__//;
                   2254:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 2255:   return $result;
                   2256: }
                   2257: 
                   2258: sub hashref2str {
                   2259:   my ($hashref)=@_;
1.265     albertel 2260:   my $result='__HASH_REF__';
1.495     albertel 2261:   foreach (sort(keys(%$hashref))) {
1.204     albertel 2262:     if (ref($_) eq 'ARRAY') {
1.265     albertel 2263:       $result.=&arrayref2str($_).'=';
1.204     albertel 2264:     } elsif (ref($_) eq 'HASH') {
1.265     albertel 2265:       $result.=&hashref2str($_).'=';
1.204     albertel 2266:     } elsif (ref($_)) {
1.265     albertel 2267:       $result.='=';
                   2268:       #print("Got a ref of ".(ref($_))." skipping.");
1.204     albertel 2269:     } else {
1.265     albertel 2270: 	if ($_) {$result.=&escape($_).'=';} else { last; }
1.204     albertel 2271:     }
                   2272: 
1.265     albertel 2273:     if(ref($hashref->{$_}) eq 'ARRAY') {
                   2274:       $result.=&arrayref2str($hashref->{$_}).'&';
                   2275:     } elsif(ref($hashref->{$_}) eq 'HASH') {
                   2276:       $result.=&hashref2str($hashref->{$_}).'&';
                   2277:     } elsif(ref($hashref->{$_})) {
                   2278:        $result.='&';
                   2279:       #print("Got a ref of ".(ref($hashref->{$_}))." skipping.");
1.204     albertel 2280:     } else {
1.265     albertel 2281:       $result.=&escape($hashref->{$_}).'&';
1.204     albertel 2282:     }
                   2283:   }
1.168     albertel 2284:   $result=~s/\&$//;
1.265     albertel 2285:   $result .= '__END_HASH_REF__';
1.168     albertel 2286:   return $result;
                   2287: }
                   2288: 
                   2289: sub str2hash {
1.265     albertel 2290:     my ($string)=@_;
                   2291:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   2292:     return %$hash;
                   2293: }
                   2294: 
                   2295: sub str2hashref {
1.168     albertel 2296:   my ($string) = @_;
1.265     albertel 2297: 
                   2298:   my %hash;
                   2299: 
                   2300:   if($string !~ /^__HASH_REF__/) {
                   2301:       if (! ($string eq '' || !defined($string))) {
                   2302: 	  $hash{'error'}='Not hash reference';
                   2303:       }
                   2304:       return (\%hash, $string);
                   2305:   }
                   2306: 
                   2307:   $string =~ s/^__HASH_REF__//;
                   2308: 
                   2309:   while($string !~ /^__END_HASH_REF__/) {
                   2310:       #key
                   2311:       my $key='';
                   2312:       if($string =~ /^__HASH_REF__/) {
                   2313:           ($key, $string)=&str2hashref($string);
                   2314:           if(defined($key->{'error'})) {
                   2315:               $hash{'error'}='Bad data';
                   2316:               return (\%hash, $string);
                   2317:           }
                   2318:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2319:           ($key, $string)=&str2arrayref($string);
                   2320:           if($key->[0] eq 'Array reference error') {
                   2321:               $hash{'error'}='Bad data';
                   2322:               return (\%hash, $string);
                   2323:           }
                   2324:       } else {
                   2325:           $string =~ s/^(.*?)=//;
1.267     albertel 2326: 	  $key=&unescape($1);
1.265     albertel 2327:       }
                   2328:       $string =~ s/^=//;
                   2329: 
                   2330:       #value
                   2331:       my $value='';
                   2332:       if($string =~ /^__HASH_REF__/) {
                   2333:           ($value, $string)=&str2hashref($string);
                   2334:           if(defined($value->{'error'})) {
                   2335:               $hash{'error'}='Bad data';
                   2336:               return (\%hash, $string);
                   2337:           }
                   2338:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2339:           ($value, $string)=&str2arrayref($string);
                   2340:           if($value->[0] eq 'Array reference error') {
                   2341:               $hash{'error'}='Bad data';
                   2342:               return (\%hash, $string);
                   2343:           }
                   2344:       } else {
                   2345: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   2346:       }
                   2347:       $string =~ s/^&//;
                   2348: 
                   2349:       $hash{$key}=$value;
1.204     albertel 2350:   }
1.265     albertel 2351: 
                   2352:   $string =~ s/^__END_HASH_REF__//;
                   2353: 
                   2354:   return (\%hash, $string);
1.204     albertel 2355: }
                   2356: 
                   2357: sub str2array {
1.265     albertel 2358:     my ($string)=@_;
                   2359:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   2360:     return @$array;
                   2361: }
                   2362: 
                   2363: sub str2arrayref {
1.204     albertel 2364:   my ($string) = @_;
1.265     albertel 2365:   my @array;
                   2366: 
                   2367:   if($string !~ /^__ARRAY_REF__/) {
                   2368:       if (! ($string eq '' || !defined($string))) {
                   2369: 	  $array[0]='Array reference error';
                   2370:       }
                   2371:       return (\@array, $string);
                   2372:   }
                   2373: 
                   2374:   $string =~ s/^__ARRAY_REF__//;
                   2375: 
                   2376:   while($string !~ /^__END_ARRAY_REF__/) {
                   2377:       my $value='';
                   2378:       if($string =~ /^__HASH_REF__/) {
                   2379:           ($value, $string)=&str2hashref($string);
                   2380:           if(defined($value->{'error'})) {
                   2381:               $array[0] ='Array reference error';
                   2382:               return (\@array, $string);
                   2383:           }
                   2384:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2385:           ($value, $string)=&str2arrayref($string);
                   2386:           if($value->[0] eq 'Array reference error') {
                   2387:               $array[0] ='Array reference error';
                   2388:               return (\@array, $string);
                   2389:           }
                   2390:       } else {
                   2391: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   2392:       }
                   2393:       $string =~ s/^&//;
                   2394: 
                   2395:       push(@array, $value);
1.191     harris41 2396:   }
1.265     albertel 2397: 
                   2398:   $string =~ s/^__END_ARRAY_REF__//;
                   2399: 
                   2400:   return (\@array, $string);
1.168     albertel 2401: }
                   2402: 
1.167     albertel 2403: # -------------------------------------------------------------------Temp Store
                   2404: 
1.168     albertel 2405: sub tmpreset {
                   2406:   my ($symb,$namespace,$domain,$stuname) = @_;
                   2407:   if (!$symb) {
                   2408:     $symb=&symbread();
1.620     albertel 2409:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2410:   }
                   2411:   $symb=escape($symb);
                   2412: 
1.620     albertel 2413:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 2414:   $namespace=~s/\//\_/g;
                   2415:   $namespace=~s/\W//g;
                   2416: 
1.620     albertel 2417:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2418:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2419:   if ($domain eq 'public' && $stuname eq 'public') {
                   2420:       $stuname=$ENV{'REMOTE_ADDR'};
                   2421:   }
1.168     albertel 2422:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2423:   my %hash;
                   2424:   if (tie(%hash,'GDBM_File',
                   2425: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2426: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2427:     foreach my $key (keys %hash) {
1.180     albertel 2428:       if ($key=~ /:$symb/) {
1.168     albertel 2429: 	delete($hash{$key});
                   2430:       }
                   2431:     }
                   2432:   }
                   2433: }
                   2434: 
1.167     albertel 2435: sub tmpstore {
1.168     albertel 2436:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2437: 
                   2438:   if (!$symb) {
                   2439:     $symb=&symbread();
1.620     albertel 2440:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2441:   }
                   2442:   $symb=escape($symb);
                   2443: 
                   2444:   if (!$namespace) {
                   2445:     # I don't think we would ever want to store this for a course.
                   2446:     # it seems this will only be used if we don't have a course.
1.620     albertel 2447:     #$namespace=$env{'request.course.id'};
1.168     albertel 2448:     #if (!$namespace) {
1.620     albertel 2449:       $namespace=$env{'request.state'};
1.168     albertel 2450:     #}
                   2451:   }
                   2452:   $namespace=~s/\//\_/g;
                   2453:   $namespace=~s/\W//g;
1.620     albertel 2454:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2455:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2456:   if ($domain eq 'public' && $stuname eq 'public') {
                   2457:       $stuname=$ENV{'REMOTE_ADDR'};
                   2458:   }
1.168     albertel 2459:   my $now=time;
                   2460:   my %hash;
                   2461:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2462:   if (tie(%hash,'GDBM_File',
                   2463: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2464: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2465:     $hash{"version:$symb"}++;
                   2466:     my $version=$hash{"version:$symb"};
                   2467:     my $allkeys=''; 
                   2468:     foreach my $key (keys(%$storehash)) {
                   2469:       $allkeys.=$key.':';
1.591     albertel 2470:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 2471:     }
                   2472:     $hash{"$version:$symb:timestamp"}=$now;
                   2473:     $allkeys.='timestamp';
                   2474:     $hash{"$version:keys:$symb"}=$allkeys;
                   2475:     if (untie(%hash)) {
                   2476:       return 'ok';
                   2477:     } else {
                   2478:       return "error:$!";
                   2479:     }
                   2480:   } else {
                   2481:     return "error:$!";
                   2482:   }
                   2483: }
1.167     albertel 2484: 
1.168     albertel 2485: # -----------------------------------------------------------------Temp Restore
1.167     albertel 2486: 
1.168     albertel 2487: sub tmprestore {
                   2488:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 2489: 
1.168     albertel 2490:   if (!$symb) {
                   2491:     $symb=&symbread();
1.620     albertel 2492:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2493:   }
                   2494:   $symb=escape($symb);
                   2495: 
1.620     albertel 2496:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 2497: 
1.620     albertel 2498:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2499:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2500:   if ($domain eq 'public' && $stuname eq 'public') {
                   2501:       $stuname=$ENV{'REMOTE_ADDR'};
                   2502:   }
1.168     albertel 2503:   my %returnhash;
                   2504:   $namespace=~s/\//\_/g;
                   2505:   $namespace=~s/\W//g;
                   2506:   my %hash;
                   2507:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2508:   if (tie(%hash,'GDBM_File',
                   2509: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2510: 	  &GDBM_READER(),0640)) {
1.168     albertel 2511:     my $version=$hash{"version:$symb"};
                   2512:     $returnhash{'version'}=$version;
                   2513:     my $scope;
                   2514:     for ($scope=1;$scope<=$version;$scope++) {
                   2515:       my $vkeys=$hash{"$scope:keys:$symb"};
                   2516:       my @keys=split(/:/,$vkeys);
                   2517:       my $key;
                   2518:       $returnhash{"$scope:keys"}=$vkeys;
                   2519:       foreach $key (@keys) {
1.591     albertel 2520: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   2521: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 2522:       }
                   2523:     }
1.168     albertel 2524:     if (!(untie(%hash))) {
                   2525:       return "error:$!";
                   2526:     }
                   2527:   } else {
                   2528:     return "error:$!";
                   2529:   }
                   2530:   return %returnhash;
1.167     albertel 2531: }
                   2532: 
1.9       www      2533: # ----------------------------------------------------------------------- Store
                   2534: 
                   2535: sub store {
1.124     www      2536:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2537:     my $home='';
                   2538: 
1.168     albertel 2539:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2540: 
1.213     www      2541:     $symb=&symbclean($symb);
1.122     albertel 2542:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2543: 
1.620     albertel 2544:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2545:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2546: 
                   2547:     &devalidate($symb,$stuname,$domain);
1.109     www      2548: 
                   2549:     $symb=escape($symb);
1.187     www      2550:     if (!$namespace) { 
1.620     albertel 2551:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2552:           return ''; 
                   2553:        } 
                   2554:     }
1.620     albertel 2555:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2556: 
                   2557:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2558:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   2559: 
1.12      www      2560:     my $namevalue='';
1.191     harris41 2561:     foreach (keys %$storehash) {
1.591     albertel 2562:         $namevalue.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191     harris41 2563:     }
1.12      www      2564:     $namevalue=~s/\&$//;
1.187     www      2565:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      2566:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      2567: }
                   2568: 
1.47      www      2569: # -------------------------------------------------------------- Critical Store
                   2570: 
                   2571: sub cstore {
1.124     www      2572:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2573:     my $home='';
                   2574: 
1.168     albertel 2575:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2576: 
1.213     www      2577:     $symb=&symbclean($symb);
1.122     albertel 2578:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2579: 
1.620     albertel 2580:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2581:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2582: 
                   2583:     &devalidate($symb,$stuname,$domain);
1.109     www      2584: 
                   2585:     $symb=escape($symb);
1.187     www      2586:     if (!$namespace) { 
1.620     albertel 2587:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2588:           return ''; 
                   2589:        } 
                   2590:     }
1.620     albertel 2591:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2592: 
                   2593:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2594:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 2595: 
1.47      www      2596:     my $namevalue='';
1.191     harris41 2597:     foreach (keys %$storehash) {
1.591     albertel 2598:         $namevalue.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191     harris41 2599:     }
1.47      www      2600:     $namevalue=~s/\&$//;
1.187     www      2601:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      2602:     return critical
                   2603:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      2604: }
                   2605: 
1.9       www      2606: # --------------------------------------------------------------------- Restore
                   2607: 
                   2608: sub restore {
1.124     www      2609:     my ($symb,$namespace,$domain,$stuname) = @_;
                   2610:     my $home='';
                   2611: 
1.168     albertel 2612:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2613: 
1.122     albertel 2614:     if (!$symb) {
                   2615:       unless ($symb=escape(&symbread())) { return ''; }
                   2616:     } else {
1.213     www      2617:       $symb=&escape(&symbclean($symb));
1.122     albertel 2618:     }
1.188     www      2619:     if (!$namespace) { 
1.620     albertel 2620:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      2621:           return ''; 
                   2622:        } 
                   2623:     }
1.620     albertel 2624:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2625:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   2626:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 2627:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   2628: 
1.12      www      2629:     my %returnhash=();
1.191     harris41 2630:     foreach (split(/\&/,$answer)) {
1.12      www      2631: 	my ($name,$value)=split(/\=/,$_);
1.591     albertel 2632:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 2633:     }
1.75      www      2634:     my $version;
                   2635:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.191     harris41 2636:        foreach (split(/\:/,$returnhash{$version.':keys'})) {
1.75      www      2637:           $returnhash{$_}=$returnhash{$version.':'.$_};
1.191     harris41 2638:        }
1.75      www      2639:     }
1.13      www      2640:     return %returnhash;
1.34      www      2641: }
                   2642: 
                   2643: # ---------------------------------------------------------- Course Description
                   2644: 
                   2645: sub coursedescription {
1.731     albertel 2646:     my ($courseid,$args)=@_;
1.34      www      2647:     $courseid=~s/^\///;
1.49      www      2648:     $courseid=~s/\_/\//g;
1.34      www      2649:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 2650:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 2651:     my $normalid=$cdomain.'_'.$cnum;
                   2652:     # need to always cache even if we get errors otherwise we keep 
                   2653:     # trying and trying and trying to get the course description.
                   2654:     my %envhash=();
                   2655:     my %returnhash=();
1.731     albertel 2656:     
                   2657:     my $expiretime=600;
                   2658:     if ($env{'request.course.id'} eq $normalid) {
                   2659: 	$expiretime=120;
                   2660:     }
                   2661: 
                   2662:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   2663:     if (!$args->{'freshen_cache'}
                   2664: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   2665: 	foreach my $key (keys(%env)) {
                   2666: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   2667: 	    my ($setting) = $1;
                   2668: 	    $returnhash{$setting} = $env{$key};
                   2669: 	}
                   2670: 	return %returnhash;
                   2671:     }
                   2672: 
                   2673:     # get the data agin
                   2674:     if (!$args->{'one_time'}) {
                   2675: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   2676:     }
1.34      www      2677:     if ($chome ne 'no_host') {
1.302     albertel 2678:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 2679:        if (!exists($returnhash{'con_lost'})) {
                   2680:            $returnhash{'home'}= $chome;
                   2681: 	   $returnhash{'domain'} = $cdomain;
                   2682: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  2683:            if (!defined($returnhash{'type'})) {
                   2684:                $returnhash{'type'} = 'Course';
                   2685:            }
1.130     albertel 2686:            while (my ($name,$value) = each %returnhash) {
1.53      www      2687:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 2688:            }
1.270     www      2689:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      2690:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 2691: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      2692:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   2693:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   2694:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      2695:        }
                   2696:     }
1.731     albertel 2697:     if (!$args->{'one_time'}) {
                   2698: 	&appenv(%envhash);
                   2699:     }
1.302     albertel 2700:     return %returnhash;
1.461     www      2701: }
                   2702: 
                   2703: # -------------------------------------------------See if a user is privileged
                   2704: 
                   2705: sub privileged {
                   2706:     my ($username,$domain)=@_;
                   2707:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   2708: 			&homeserver($username,$domain));
                   2709:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   2710:     my $now=time;
                   2711:     if ($rolesdump ne '') {
                   2712:         foreach (split(/&/,$rolesdump)) {
1.586     albertel 2713: 	    if ($_!~/^rolesdef_/) {
1.461     www      2714: 		my ($area,$role)=split(/=/,$_);
                   2715: 		$area=~s/\_\w\w$//;
                   2716: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   2717: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   2718: 		    my $active=1;
                   2719: 		    if ($tend) {
                   2720: 			if ($tend<$now) { $active=0; }
                   2721: 		    }
                   2722: 		    if ($tstart) {
                   2723: 			if ($tstart>$now) { $active=0; }
                   2724: 		    }
                   2725: 		    if ($active) { return 1; }
                   2726: 		}
                   2727: 	    }
                   2728: 	}
                   2729:     }
                   2730:     return 0;
1.9       www      2731: }
1.1       albertel 2732: 
1.103     harris41 2733: # -------------------------------------------------------- Get user privileges
1.11      www      2734: 
                   2735: sub rolesinit {
                   2736:     my ($domain,$username,$authhost)=@_;
                   2737:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12      www      2738:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11      www      2739:     my %allroles=();
1.678     raeburn  2740:     my %allgroups=();   
1.11      www      2741:     my $now=time;
1.743     albertel 2742:     my %userroles = ('user.login.time' => $now);
1.678     raeburn  2743:     my $group_privs;
1.11      www      2744: 
                   2745:     if ($rolesdump ne '') {
1.191     harris41 2746:         foreach (split(/&/,$rolesdump)) {
1.586     albertel 2747: 	  if ($_!~/^rolesdef_/) {
1.11      www      2748:             my ($area,$role)=split(/=/,$_);
1.587     albertel 2749: 	    $area=~s/\_\w\w$//;
1.678     raeburn  2750:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 2751: 	    if ($role=~/^cr/) { 
1.655     albertel 2752: 		if ($role=~m|^(cr/\w+/\w+/[a-zA-Z0-9]+)_(.*)$|) {
                   2753: 		    ($trole,my $trest)=($role=~m|^(cr/\w+/\w+/[a-zA-Z0-9]+)_(.*)$|);
                   2754: 		    ($tend,$tstart)=split('_',$trest);
                   2755: 		} else {
                   2756: 		    $trole=$role;
                   2757: 		}
1.678     raeburn  2758:             } elsif ($role =~ m|^gr/|) {
                   2759:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   2760:                 ($trole,$group_privs) = split(/\//,$trole);
                   2761:                 $group_privs = &unescape($group_privs);
1.587     albertel 2762: 	    } else {
                   2763: 		($trole,$tend,$tstart)=split(/_/,$role);
                   2764: 	    }
1.743     albertel 2765: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   2766: 					 $username);
                   2767: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  2768:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   2769:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      2770:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 2771: 		my $spec=$trole.'.'.$area;
                   2772: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   2773: 		if ($trole =~ /^cr\//) {
1.567     raeburn  2774:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  2775:                 } elsif ($trole eq 'gr') {
                   2776:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 2777: 		} else {
1.567     raeburn  2778:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 2779: 		}
1.12      www      2780:             }
1.662     raeburn  2781:           }
1.191     harris41 2782:         }
1.743     albertel 2783:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   2784:         $userroles{'user.adv'}    = $adv;
                   2785: 	$userroles{'user.author'} = $author;
1.620     albertel 2786:         $env{'user.adv'}=$adv;
1.11      www      2787:     }
1.743     albertel 2788:     return \%userroles;  
1.11      www      2789: }
                   2790: 
1.567     raeburn  2791: sub set_arearole {
                   2792:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   2793: # log the associated role with the area
                   2794:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 2795:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  2796: }
                   2797: 
                   2798: sub custom_roleprivs {
                   2799:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   2800:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   2801:     my $homsvr=homeserver($rauthor,$rdomain);
                   2802:     if ($hostname{$homsvr} ne '') {
                   2803:         my ($rdummy,$roledef)=
                   2804:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   2805:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   2806:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   2807:             if (defined($syspriv)) {
                   2808:                 $$allroles{'cm./'}.=':'.$syspriv;
                   2809:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   2810:             }
                   2811:             if ($tdomain ne '') {
                   2812:                 if (defined($dompriv)) {
                   2813:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   2814:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   2815:                 }
                   2816:                 if (($trest ne '') && (defined($coursepriv))) {
                   2817:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   2818:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   2819:                 }
                   2820:             }
                   2821:         }
                   2822:     }
                   2823: }
                   2824: 
1.678     raeburn  2825: sub group_roleprivs {
                   2826:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   2827:     my $access = 1;
                   2828:     my $now = time;
                   2829:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   2830:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   2831:     if ($access) {
                   2832:         my ($course,$group) = ($area =~ m|(/\w+/\w+)/([^/]+)$|);
                   2833:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   2834:     }
                   2835: }
1.567     raeburn  2836: 
                   2837: sub standard_roleprivs {
                   2838:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   2839:     if (defined($pr{$trole.':s'})) {
                   2840:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   2841:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   2842:     }
                   2843:     if ($tdomain ne '') {
                   2844:         if (defined($pr{$trole.':d'})) {
                   2845:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   2846:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   2847:         }
                   2848:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   2849:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   2850:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   2851:         }
                   2852:     }
                   2853: }
                   2854: 
                   2855: sub set_userprivs {
1.678     raeburn  2856:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  2857:     my $author=0;
                   2858:     my $adv=0;
1.678     raeburn  2859:     my %grouproles = ();
                   2860:     if (keys(%{$allgroups}) > 0) {
                   2861:         foreach my $role (keys %{$allroles}) {
1.681     raeburn  2862:             my ($trole,$area,$sec,$extendedarea);
1.771     raeburn  2863:             if ($role =~ m-^(\w+|cr/\w+/\w+/\w+)\.(/\w+/\w+)(/?\w*)-) {
1.678     raeburn  2864:                 $trole = $1;
                   2865:                 $area = $2;
1.681     raeburn  2866:                 $sec = $3;
                   2867:                 $extendedarea = $area.$sec;
                   2868:                 if (exists($$allgroups{$area})) {
                   2869:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   2870:                         my $spec = $trole.'.'.$extendedarea;
                   2871:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   2872:                                                 $$allgroups{$area}{$group};
1.678     raeburn  2873:                     }
                   2874:                 }
                   2875:             }
                   2876:         }
                   2877:     }
                   2878:     foreach (keys(%grouproles)) {
                   2879:         $$allroles{$_} = $grouproles{$_};
                   2880:     }
1.567     raeburn  2881:     foreach (keys %{$allroles}) {
                   2882:         my %thesepriv=();
                   2883:         if (($_=~/^au/) || ($_=~/^ca/)) { $author=1; }
                   2884:         foreach (split(/:/,$$allroles{$_})) {
                   2885:             if ($_ ne '') {
                   2886:                 my ($privilege,$restrictions)=split(/&/,$_);
                   2887:                 if ($restrictions eq '') {
                   2888:                     $thesepriv{$privilege}='F';
                   2889:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   2890:                     $thesepriv{$privilege}.=$restrictions;
                   2891:                 }
                   2892:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   2893:             }
                   2894:         }
                   2895:         my $thesestr='';
                   2896:         foreach (keys %thesepriv) { $thesestr.=':'.$_.'&'.$thesepriv{$_}; }
1.743     albertel 2897:         $userroles->{'user.priv.'.$_} = $thesestr;
1.567     raeburn  2898:     }
                   2899:     return ($author,$adv);
                   2900: }
                   2901: 
1.12      www      2902: # --------------------------------------------------------------- get interface
                   2903: 
                   2904: sub get {
1.131     albertel 2905:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      2906:    my $items='';
1.191     harris41 2907:    foreach (@$storearr) {
1.12      www      2908:        $items.=escape($_).'&';
1.191     harris41 2909:    }
1.12      www      2910:    $items=~s/\&$//;
1.620     albertel 2911:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2912:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 2913:    my $uhome=&homeserver($uname,$udomain);
                   2914: 
1.133     albertel 2915:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      2916:    my @pairs=split(/\&/,$rep);
1.273     albertel 2917:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   2918:      return @pairs;
                   2919:    }
1.15      www      2920:    my %returnhash=();
1.42      www      2921:    my $i=0;
1.191     harris41 2922:    foreach (@$storearr) {
1.557     albertel 2923:       $returnhash{$_}=&thaw_unescape($pairs[$i]);
1.42      www      2924:       $i++;
1.191     harris41 2925:    }
1.15      www      2926:    return %returnhash;
1.27      www      2927: }
                   2928: 
                   2929: # --------------------------------------------------------------- del interface
                   2930: 
                   2931: sub del {
1.133     albertel 2932:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      2933:    my $items='';
1.191     harris41 2934:    foreach (@$storearr) {
1.27      www      2935:        $items.=escape($_).'&';
1.191     harris41 2936:    }
1.27      www      2937:    $items=~s/\&$//;
1.620     albertel 2938:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2939:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 2940:    my $uhome=&homeserver($uname,$udomain);
                   2941: 
                   2942:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      2943: }
                   2944: 
                   2945: # -------------------------------------------------------------- dump interface
                   2946: 
                   2947: sub dump {
1.755     albertel 2948:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   2949:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2950:     if (!$uname) { $uname=$env{'user.name'}; }
                   2951:     my $uhome=&homeserver($uname,$udomain);
                   2952:     if ($regexp) {
                   2953: 	$regexp=&escape($regexp);
                   2954:     } else {
                   2955: 	$regexp='.';
                   2956:     }
                   2957:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   2958:     my @pairs=split(/\&/,$rep);
                   2959:     my %returnhash=();
                   2960:     foreach my $item (@pairs) {
                   2961: 	my ($key,$value)=split(/=/,$item,2);
                   2962: 	$key = &unescape($key);
                   2963: 	next if ($key =~ /^error: 2 /);
                   2964: 	$returnhash{$key}=&thaw_unescape($value);
                   2965:     }
                   2966:     return %returnhash;
1.407     www      2967: }
                   2968: 
1.717     albertel 2969: # --------------------------------------------------------- dumpstore interface
                   2970: 
                   2971: sub dumpstore {
                   2972:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   2973:    return &dump($namespace,$udomain,$uname,$regexp,$range);
                   2974: }
                   2975: 
1.407     www      2976: # -------------------------------------------------------------- keys interface
                   2977: 
                   2978: sub getkeys {
                   2979:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 2980:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2981:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      2982:    my $uhome=&homeserver($uname,$udomain);
                   2983:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   2984:    my @keyarray=();
                   2985:    foreach (split(/\&/,$rep)) {
                   2986:       push (@keyarray,&unescape($_));
                   2987:    }
                   2988:    return @keyarray;
1.318     matthew  2989: }
                   2990: 
1.319     matthew  2991: # --------------------------------------------------------------- currentdump
                   2992: sub currentdump {
1.328     matthew  2993:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 2994:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   2995:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   2996:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  2997:    my $uhome = &homeserver($sname,$sdom);
                   2998:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  2999:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  3000:    #
1.318     matthew  3001:    my %returnhash=();
1.319     matthew  3002:    #
                   3003:    if ($rep eq "unknown_cmd") { 
                   3004:        # an old lond will not know currentdump
                   3005:        # Do a dump and make it look like a currentdump
1.326     matthew  3006:        my @tmp = &dump($courseid,$sdom,$sname,'.');
1.319     matthew  3007:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   3008:        my %hash = @tmp;
                   3009:        @tmp=();
1.424     matthew  3010:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  3011:    } else {
                   3012:        my @pairs=split(/\&/,$rep);
                   3013:        foreach (@pairs) {
                   3014:            my ($key,$value)=split(/=/,$_);
                   3015:            my ($symb,$param) = split(/:/,$key);
                   3016:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 3017:                                                         &thaw_unescape($value);
1.319     matthew  3018:        }
1.191     harris41 3019:    }
1.12      www      3020:    return %returnhash;
1.424     matthew  3021: }
                   3022: 
                   3023: sub convert_dump_to_currentdump{
                   3024:     my %hash = %{shift()};
                   3025:     my %returnhash;
                   3026:     # Code ripped from lond, essentially.  The only difference
                   3027:     # here is the unescaping done by lonnet::dump().  Conceivably
                   3028:     # we might run in to problems with parameter names =~ /^v\./
                   3029:     while (my ($key,$value) = each(%hash)) {
                   3030:         my ($v,$symb,$param) = split(/:/,$key);
                   3031:         next if ($v eq 'version' || $symb eq 'keys');
                   3032:         next if (exists($returnhash{$symb}) &&
                   3033:                  exists($returnhash{$symb}->{$param}) &&
                   3034:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   3035:         $returnhash{$symb}->{$param}=$value;
                   3036:         $returnhash{$symb}->{'v.'.$param}=$v;
                   3037:     }
                   3038:     #
                   3039:     # Remove all of the keys in the hashes which keep track of
                   3040:     # the version of the parameter.
                   3041:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   3042:         # use a foreach because we are going to delete from the hash.
                   3043:         foreach my $key (keys(%$param_hash)) {
                   3044:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   3045:         }
                   3046:     }
                   3047:     return \%returnhash;
1.12      www      3048: }
                   3049: 
1.627     albertel 3050: # ------------------------------------------------------ critical inc interface
                   3051: 
                   3052: sub cinc {
                   3053:     return &inc(@_,'critical');
                   3054: }
                   3055: 
1.449     matthew  3056: # --------------------------------------------------------------- inc interface
                   3057: 
                   3058: sub inc {
1.627     albertel 3059:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 3060:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3061:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  3062:     my $uhome=&homeserver($uname,$udomain);
                   3063:     my $items='';
                   3064:     if (! ref($store)) {
                   3065:         # got a single value, so use that instead
                   3066:         $items = &escape($store).'=&';
                   3067:     } elsif (ref($store) eq 'SCALAR') {
                   3068:         $items = &escape($$store).'=&';        
                   3069:     } elsif (ref($store) eq 'ARRAY') {
                   3070:         $items = join('=&',map {&escape($_);} @{$store});
                   3071:     } elsif (ref($store) eq 'HASH') {
                   3072:         while (my($key,$value) = each(%{$store})) {
                   3073:             $items.= &escape($key).'='.&escape($value).'&';
                   3074:         }
                   3075:     }
                   3076:     $items=~s/\&$//;
1.627     albertel 3077:     if ($critical) {
                   3078: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3079:     } else {
                   3080: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3081:     }
1.449     matthew  3082: }
                   3083: 
1.12      www      3084: # --------------------------------------------------------------- put interface
                   3085: 
                   3086: sub put {
1.134     albertel 3087:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3088:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3089:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3090:    my $uhome=&homeserver($uname,$udomain);
1.12      www      3091:    my $items='';
1.191     harris41 3092:    foreach (keys %$storehash) {
1.557     albertel 3093:        $items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191     harris41 3094:    }
1.12      www      3095:    $items=~s/\&$//;
1.134     albertel 3096:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      3097: }
                   3098: 
1.631     albertel 3099: # ------------------------------------------------------------ newput interface
                   3100: 
                   3101: sub newput {
                   3102:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   3103:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3104:    if (!$uname) { $uname=$env{'user.name'}; }
                   3105:    my $uhome=&homeserver($uname,$udomain);
                   3106:    my $items='';
                   3107:    foreach my $key (keys(%$storehash)) {
                   3108:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   3109:    }
                   3110:    $items=~s/\&$//;
                   3111:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   3112: }
                   3113: 
                   3114: # ---------------------------------------------------------  putstore interface
                   3115: 
1.524     raeburn  3116: sub putstore {
1.715     albertel 3117:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 3118:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3119:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  3120:    my $uhome=&homeserver($uname,$udomain);
                   3121:    my $items='';
1.715     albertel 3122:    foreach my $key (keys(%$storehash)) {
                   3123:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  3124:    }
1.715     albertel 3125:    $items=~s/\&$//;
1.716     albertel 3126:    my $esc_symb=&escape($symb);
                   3127:    my $esc_v=&escape($version);
1.715     albertel 3128:    my $reply =
1.716     albertel 3129:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 3130: 	      $uhome);
                   3131:    if ($reply eq 'unknown_cmd') {
1.716     albertel 3132:        # gfall back to way things use to be done
1.715     albertel 3133:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   3134: 			    $uname);
1.524     raeburn  3135:    }
1.715     albertel 3136:    return $reply;
                   3137: }
                   3138: 
                   3139: sub old_putstore {
1.716     albertel 3140:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   3141:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3142:     if (!$uname) { $uname=$env{'user.name'}; }
                   3143:     my $uhome=&homeserver($uname,$udomain);
                   3144:     my %newstorehash;
                   3145:     foreach (keys %$storehash) {
                   3146: 	my $key = $version.':'.&escape($symb).':'.$_;
                   3147: 	$newstorehash{$key} = $storehash->{$_};
                   3148:     }
                   3149:     my $items='';
                   3150:     my %allitems = ();
                   3151:     foreach (keys %newstorehash) {
                   3152: 	if ($_ =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
                   3153: 	    my $key = $1.':keys:'.$2;
                   3154: 	    $allitems{$key} .= $3.':';
                   3155: 	}
                   3156: 	$items.=$_.'='.&freeze_escape($newstorehash{$_}).'&';
                   3157:     }
                   3158:     foreach (keys %allitems) {
                   3159: 	$allitems{$_} =~ s/\:$//;
                   3160: 	$items.= $_.'='.$allitems{$_}.'&';
                   3161:     }
                   3162:     $items=~s/\&$//;
                   3163:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  3164: }
                   3165: 
1.47      www      3166: # ------------------------------------------------------ critical put interface
                   3167: 
                   3168: sub cput {
1.134     albertel 3169:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3170:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3171:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3172:    my $uhome=&homeserver($uname,$udomain);
1.47      www      3173:    my $items='';
1.191     harris41 3174:    foreach (keys %$storehash) {
1.715     albertel 3175:        $items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
1.191     harris41 3176:    }
1.47      www      3177:    $items=~s/\&$//;
1.134     albertel 3178:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3179: }
                   3180: 
                   3181: # -------------------------------------------------------------- eget interface
                   3182: 
                   3183: sub eget {
1.133     albertel 3184:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3185:    my $items='';
1.191     harris41 3186:    foreach (@$storearr) {
1.12      www      3187:        $items.=escape($_).'&';
1.191     harris41 3188:    }
1.12      www      3189:    $items=~s/\&$//;
1.620     albertel 3190:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3191:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3192:    my $uhome=&homeserver($uname,$udomain);
                   3193:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3194:    my @pairs=split(/\&/,$rep);
                   3195:    my %returnhash=();
1.42      www      3196:    my $i=0;
1.191     harris41 3197:    foreach (@$storearr) {
1.557     albertel 3198:       $returnhash{$_}=&thaw_unescape($pairs[$i]);
1.42      www      3199:       $i++;
1.191     harris41 3200:    }
1.12      www      3201:    return %returnhash;
                   3202: }
                   3203: 
1.667     albertel 3204: # ------------------------------------------------------------ tmpput interface
                   3205: sub tmpput {
                   3206:     my ($storehash,$server)=@_;
                   3207:     my $items='';
                   3208:     foreach (keys(%$storehash)) {
                   3209: 	$items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
                   3210:     }
                   3211:     $items=~s/\&$//;
                   3212:     return &reply("tmpput:$items",$server);
                   3213: }
                   3214: 
                   3215: # ------------------------------------------------------------ tmpget interface
                   3216: sub tmpget {
1.688     albertel 3217:     my ($token,$server)=@_;
                   3218:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3219:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 3220:     my %returnhash;
                   3221:     foreach my $item (split(/\&/,$rep)) {
                   3222: 	my ($key,$value)=split(/=/,$item);
                   3223: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   3224:     }
                   3225:     return %returnhash;
                   3226: }
                   3227: 
1.688     albertel 3228: # ------------------------------------------------------------ tmpget interface
                   3229: sub tmpdel {
                   3230:     my ($token,$server)=@_;
                   3231:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3232:     return &reply("tmpdel:$token",$server);
                   3233: }
                   3234: 
1.765     albertel 3235: # -------------------------------------------------- portfolio access checking
                   3236: 
                   3237: sub portfolio_access {
1.766     albertel 3238:     my ($requrl) = @_;
1.765     albertel 3239:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   3240:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
                   3241:     if ($result eq 'ok') {
1.766     albertel 3242:        return 'F';
1.765     albertel 3243:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 3244:        return 'A';
1.765     albertel 3245:     }
1.766     albertel 3246:     return '';
1.765     albertel 3247: }
                   3248: 
                   3249: sub get_portfolio_access {
1.767     albertel 3250:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   3251: 
                   3252:     if (!ref($access_hash)) {
                   3253: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   3254: 	my %access_controls = &get_access_controls($current_perms,$group,
                   3255: 						   $file_name);
                   3256: 	$access_hash = $access_controls{$file_name};
                   3257:     }
                   3258: 
1.765     albertel 3259:     my ($public,$guest,@domains,@users,@courses,@groups);
                   3260:     my $now = time;
                   3261:     if (ref($access_hash) eq 'HASH') {
                   3262:         foreach my $key (keys(%{$access_hash})) {
                   3263:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   3264:             if ($start > $now) {
                   3265:                 next;
                   3266:             }
                   3267:             if ($end && $end<$now) {
                   3268:                 next;
                   3269:             }
                   3270:             if ($scope eq 'public') {
                   3271:                 $public = $key;
                   3272:                 last;
                   3273:             } elsif ($scope eq 'guest') {
                   3274:                 $guest = $key;
                   3275:             } elsif ($scope eq 'domains') {
                   3276:                 push(@domains,$key);
                   3277:             } elsif ($scope eq 'users') {
                   3278:                 push(@users,$key);
                   3279:             } elsif ($scope eq 'course') {
                   3280:                 push(@courses,$key);
                   3281:             } elsif ($scope eq 'group') {
                   3282:                 push(@groups,$key);
                   3283:             }
                   3284:         }
                   3285:         if ($public) {
                   3286:             return 'ok';
                   3287:         }
                   3288:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3289:             if ($guest) {
                   3290:                 return $guest;
                   3291:             }
                   3292:         } else {
                   3293:             if (@domains > 0) {
                   3294:                 foreach my $domkey (@domains) {
                   3295:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   3296:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   3297:                             return 'ok';
                   3298:                         }
                   3299:                     }
                   3300:                 }
                   3301:             }
                   3302:             if (@users > 0) {
                   3303:                 foreach my $userkey (@users) {
                   3304:                     if (exists($access_hash->{$userkey}{'users'}{$env{'user.name'}.':'.$env{'user.domain'}})) {
                   3305:                         return 'ok';
                   3306:                     }
                   3307:                 }
                   3308:             }
                   3309:             my %roleshash;
                   3310:             my @courses_and_groups = @courses;
                   3311:             push(@courses_and_groups,@groups); 
                   3312:             if (@courses_and_groups > 0) {
                   3313:                 my (%allgroups,%allroles); 
                   3314:                 my ($start,$end,$role,$sec,$group);
                   3315:                 foreach my $envkey (%env) {
                   3316:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./([^/]+)/([^/]+)/?([^/]*)$-) {
                   3317:                         my $cid = $2.'_'.$3; 
                   3318:                         if ($1 eq 'gr') {
                   3319:                             $group = $4;
                   3320:                             $allgroups{$cid}{$group} = $env{$envkey};
                   3321:                         } else {
                   3322:                             if ($4 eq '') {
                   3323:                                 $sec = 'none';
                   3324:                             } else {
                   3325:                                 $sec = $4;
                   3326:                             }
                   3327:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3328:                         }
                   3329:                     } elsif ($envkey =~ m-^user\.role\./cr/(\w+/\w+/\w*)./([^/]+)/([^/]+)/?([^/]*)$-) {
                   3330:                         my $cid = $2.'_'.$3;
                   3331:                         if ($4 eq '') {
                   3332:                             $sec = 'none';
                   3333:                         } else {
                   3334:                             $sec = $4;
                   3335:                         }
                   3336:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3337:                     }
                   3338:                 }
                   3339:                 if (keys(%allroles) == 0) {
                   3340:                     return;
                   3341:                 }
                   3342:                 foreach my $key (@courses_and_groups) {
                   3343:                     my %content = %{$$access_hash{$key}};
                   3344:                     my $cnum = $content{'number'};
                   3345:                     my $cdom = $content{'domain'};
                   3346:                     my $cid = $cdom.'_'.$cnum;
                   3347:                     if (!exists($allroles{$cid})) {
                   3348:                         next;
                   3349:                     }    
                   3350:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   3351:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   3352:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   3353:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   3354:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   3355:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   3356:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   3357:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   3358:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   3359:                                         if (grep/^all$/,@sections) {
                   3360:                                             return 'ok';
                   3361:                                         } else {
                   3362:                                             if (grep/^$sec$/,@sections) {
                   3363:                                                 return 'ok';
                   3364:                                             }
                   3365:                                         }
                   3366:                                     }
                   3367:                                 }
                   3368:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   3369:                                     if (grep/^none$/,@groups) {
                   3370:                                         return 'ok';
                   3371:                                     }
                   3372:                                 } else {
                   3373:                                     if (grep/^all$/,@groups) {
                   3374:                                         return 'ok';
                   3375:                                     } 
                   3376:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   3377:                                         if (grep/^$group$/,@groups) {
                   3378:                                             return 'ok';
                   3379:                                         }
                   3380:                                     }
                   3381:                                 } 
                   3382:                             }
                   3383:                         }
                   3384:                     }
                   3385:                 }
                   3386:             }
                   3387:             if ($guest) {
                   3388:                 return $guest;
                   3389:             }
                   3390:         }
                   3391:     }
                   3392:     return;
                   3393: }
                   3394: 
                   3395: sub course_group_datechecker {
                   3396:     my ($dates,$now,$status) = @_;
                   3397:     my ($start,$end) = split(/\./,$dates);
                   3398:     if (!$start && !$end) {
                   3399:         return 'ok';
                   3400:     }
                   3401:     if (grep/^active$/,@{$status}) {
                   3402:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   3403:             return 'ok';
                   3404:         }
                   3405:     }
                   3406:     if (grep/^previous$/,@{$status}) {
                   3407:         if ($end > $now ) {
                   3408:             return 'ok';
                   3409:         }
                   3410:     }
                   3411:     if (grep/^future$/,@{$status}) {
                   3412:         if ($start > $now) {
                   3413:             return 'ok';
                   3414:         }
                   3415:     }
                   3416:     return; 
                   3417: }
                   3418: 
                   3419: sub parse_portfolio_url {
                   3420:     my ($url) = @_;
                   3421: 
                   3422:     my ($type,$udom,$unum,$group,$file_name);
                   3423:     
                   3424:     if ($url =~  m-^/*uploaded/([^/]+)/([^/]+)/portfolio(/.+)$-) {
                   3425: 	$type = 1;
                   3426:         $udom = $1;
                   3427:         $unum = $2;
                   3428:         $file_name = $3;
                   3429:     } elsif ($url =~ m-^/*uploaded/([^/]+)/([^/]+)/groups/([^/]+)/portfolio/(.+)$-) {
                   3430: 	$type = 2;
                   3431:         $udom = $1;
                   3432:         $unum = $2;
                   3433:         $group = $3;
                   3434:         $file_name = $3.'/'.$4;
                   3435:     }
                   3436:     if (wantarray) {
                   3437: 	return ($type,$udom,$unum,$file_name,$group);
                   3438:     }
                   3439:     return $type;
                   3440: }
                   3441: 
                   3442: sub is_portfolio_url {
                   3443:     my ($url) = @_;
                   3444:     return scalar(&parse_portfolio_url($url));
                   3445: }
                   3446: 
1.341     www      3447: # ---------------------------------------------- Custom access rule evaluation
                   3448: 
                   3449: sub customaccess {
                   3450:     my ($priv,$uri)=@_;
1.620     albertel 3451:     my ($urole,$urealm)=split(/\./,$env{'request.role'});
1.343     www      3452:     $urealm=~s/^\W//;
                   3453:     my ($udom,$ucrs,$usec)=split(/\//,$urealm);
1.341     www      3454:     my $access=0;
                   3455:     foreach (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.342     www      3456: 	my ($effect,$realm,$role)=split(/\:/,$_);
1.343     www      3457:         if ($role) {
                   3458: 	   if ($role ne $urole) { next; }
                   3459:         }
                   3460:         foreach (split(/\s*\,\s*/,$realm)) {
                   3461:             my ($tdom,$tcrs,$tsec)=split(/\_/,$_);
                   3462:             if ($tdom) {
                   3463: 		if ($tdom ne $udom) { next; }
                   3464:             }
                   3465:             if ($tcrs) {
                   3466: 		if ($tcrs ne $ucrs) { next; }
                   3467:             }
                   3468:             if ($tsec) {
                   3469: 		if ($tsec ne $usec) { next; }
                   3470:             }
                   3471:             $access=($effect eq 'allow');
                   3472:             last;
1.342     www      3473:         }
1.402     bowersj2 3474: 	if ($realm eq '' && $role eq '') {
                   3475:             $access=($effect eq 'allow');
                   3476: 	}
1.341     www      3477:     }
                   3478:     return $access;
                   3479: }
                   3480: 
1.103     harris41 3481: # ------------------------------------------------- Check for a user privilege
1.12      www      3482: 
                   3483: sub allowed {
1.579     albertel 3484:     my ($priv,$uri,$symb)=@_;
1.705     albertel 3485:     my $ver_orguri=$uri;
1.439     www      3486:     $uri=&deversion($uri);
1.152     www      3487:     my $orguri=$uri;
1.52      www      3488:     $uri=&declutter($uri);
1.545     banghart 3489:     
1.620     albertel 3490:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      3491: # Free bre access to adm and meta resources
1.775     albertel 3492:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 3493: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   3494: 	&& ($priv eq 'bre')) {
1.14      www      3495: 	return 'F';
1.159     www      3496:     }
                   3497: 
1.545     banghart 3498: # Free bre access to user's own portfolio contents
1.714     raeburn  3499:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  3500:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  3501: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.545     banghart 3502:         return 'F';
                   3503:     }
                   3504: 
1.762     raeburn  3505: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  3506:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   3507:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   3508:         if (exists($env{'request.course.id'})) {
                   3509:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3510:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3511:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   3512:                 my $courseprivid=$env{'request.course.id'};
                   3513:                 $courseprivid=~s/\_/\//;
                   3514:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   3515:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   3516:                     return $1; 
1.762     raeburn  3517:                 } else {
                   3518:                     if ($env{'request.course.sec'}) {
                   3519:                         $courseprivid.='/'.$env{'request.course.sec'};
                   3520:                     }
                   3521:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   3522:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   3523:                         return $2;
                   3524:                     }
1.714     raeburn  3525:                 }
                   3526:             }
                   3527:         }
                   3528:     }
                   3529: 
1.159     www      3530: # Free bre to public access
                   3531: 
                   3532:     if ($priv eq 'bre') {
1.238     www      3533:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 3534: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      3535:            return 'F'; 
                   3536:         }
1.238     www      3537:         if ($copyright eq 'priv') {
                   3538:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3539: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      3540: 		return '';
                   3541:             }
                   3542:         }
                   3543:         if ($copyright eq 'domain') {
                   3544:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3545: 	    unless (($env{'user.domain'} eq $1) ||
                   3546:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      3547: 		return '';
                   3548:             }
1.262     matthew  3549:         }
1.620     albertel 3550:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  3551:             # Library role, so allow browsing of resources in this domain.
                   3552:             return 'F';
1.238     www      3553:         }
1.341     www      3554:         if ($copyright eq 'custom') {
                   3555: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   3556:         }
1.14      www      3557:     }
1.264     matthew  3558:     # Domain coordinator is trying to create a course
1.620     albertel 3559:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  3560:         # uri is the requested domain in this case.
                   3561:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  3562:         # a role of dc for the domain in question.
1.620     albertel 3563:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  3564:     }
1.29      www      3565: 
1.52      www      3566:     my $thisallowed='';
                   3567:     my $statecond=0;
                   3568:     my $courseprivid='';
                   3569: 
                   3570: # Course
                   3571: 
1.620     albertel 3572:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3573:        $thisallowed.=$1;
                   3574:     }
1.29      www      3575: 
1.52      www      3576: # Domain
                   3577: 
1.620     albertel 3578:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 3579:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3580:        $thisallowed.=$1;
                   3581:     }
1.52      www      3582: 
                   3583: # Course: uri itself is a course
1.66      www      3584:     my $courseuri=$uri;
                   3585:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      3586:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      3587: 
1.620     albertel 3588:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 3589:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3590:        $thisallowed.=$1;
                   3591:     }
1.29      www      3592: 
1.665     albertel 3593: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 3594: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 3595:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 3596: 	$thisallowed='';
1.671     raeburn  3597:         my ($match)=&is_on_map($uri);
                   3598:         if ($match) {
                   3599:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   3600:                   =~/\Q$priv\E\&([^\:]*)/) {
                   3601:                 $thisallowed.=$1;
                   3602:             }
                   3603:         } else {
1.705     albertel 3604:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  3605:             if ($refuri) {
                   3606:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  3607:                     $thisallowed='F';
1.671     raeburn  3608:                 } else {
                   3609:                     $refuri=&declutter($refuri);
                   3610:                     my ($match) = &is_on_map($refuri);
                   3611:                     if ($match) {
                   3612:                         $thisallowed='F';
                   3613:                     }
1.669     raeburn  3614:                 }
1.671     raeburn  3615:             }
                   3616:         }
1.314     www      3617:     }
1.492     albertel 3618: 
1.766     albertel 3619:     if ($priv eq 'bre'
                   3620: 	&& $thisallowed ne 'F' 
                   3621: 	&& $thisallowed ne '2'
                   3622: 	&& &is_portfolio_url($uri)) {
                   3623: 	$thisallowed = &portfolio_access($uri);
                   3624:     }
                   3625:     
1.52      www      3626: # Full access at system, domain or course-wide level? Exit.
1.29      www      3627: 
                   3628:     if ($thisallowed=~/F/) {
                   3629: 	return 'F';
                   3630:     }
                   3631: 
1.52      www      3632: # If this is generating or modifying users, exit with special codes
1.29      www      3633: 
1.643     www      3634:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   3635: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 3636: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      3637: # no author name given, so this just checks on the general right to make a co-author in this domain
                   3638: 	    unless ($auname) { return $thisallowed; }
                   3639: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 3640: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   3641: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   3642: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   3643: 	}
1.52      www      3644: 	return $thisallowed;
                   3645:     }
                   3646: #
1.103     harris41 3647: # Gathered so far: system, domain and course wide privileges
1.52      www      3648: #
                   3649: # Course: See if uri or referer is an individual resource that is part of 
                   3650: # the course
                   3651: 
1.620     albertel 3652:     if ($env{'request.course.id'}) {
1.232     www      3653: 
1.620     albertel 3654:        $courseprivid=$env{'request.course.id'};
                   3655:        if ($env{'request.course.sec'}) {
                   3656:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      3657:        }
                   3658:        $courseprivid=~s/\_/\//;
                   3659:        my $checkreferer=1;
1.232     www      3660:        my ($match,$cond)=&is_on_map($uri);
                   3661:        if ($match) {
                   3662:            $statecond=$cond;
1.620     albertel 3663:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 3664:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3665:                $thisallowed.=$1;
                   3666:                $checkreferer=0;
                   3667:            }
1.29      www      3668:        }
1.83      www      3669:        
1.148     www      3670:        if ($checkreferer) {
1.620     albertel 3671: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      3672:             unless ($refuri) {
1.620     albertel 3673:                 foreach (keys %env) {
1.148     www      3674: 		    if ($_=~/^httpref\..*\*/) {
                   3675: 			my $pattern=$_;
1.156     www      3676:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      3677:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   3678:                         $pattern=~s/\//\\\//g;
1.152     www      3679:                         if ($orguri=~/$pattern/) {
1.620     albertel 3680: 			    $refuri=$env{$_};
1.148     www      3681:                         }
                   3682:                     }
1.191     harris41 3683:                 }
1.148     www      3684:             }
1.232     www      3685: 
1.148     www      3686:          if ($refuri) { 
1.152     www      3687: 	  $refuri=&declutter($refuri);
1.232     www      3688:           my ($match,$cond)=&is_on_map($refuri);
                   3689:             if ($match) {
                   3690:               my $refstatecond=$cond;
1.620     albertel 3691:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 3692:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3693:                   $thisallowed.=$1;
1.53      www      3694:                   $uri=$refuri;
                   3695:                   $statecond=$refstatecond;
1.52      www      3696:               }
                   3697:           }
1.148     www      3698:         }
1.29      www      3699:        }
1.52      www      3700:    }
1.29      www      3701: 
1.52      www      3702: #
1.103     harris41 3703: # Gathered now: all privileges that could apply, and condition number
1.52      www      3704: # 
                   3705: #
                   3706: # Full or no access?
                   3707: #
1.29      www      3708: 
1.52      www      3709:     if ($thisallowed=~/F/) {
                   3710: 	return 'F';
                   3711:     }
1.29      www      3712: 
1.52      www      3713:     unless ($thisallowed) {
                   3714:         return '';
                   3715:     }
1.29      www      3716: 
1.52      www      3717: # Restrictions exist, deal with them
                   3718: #
                   3719: #   C:according to course preferences
                   3720: #   R:according to resource settings
                   3721: #   L:unless locked
                   3722: #   X:according to user session state
                   3723: #
                   3724: 
                   3725: # Possibly locked functionality, check all courses
1.54      www      3726: # Locks might take effect only after 10 minutes cache expiration for other
                   3727: # courses, and 2 minutes for current course
1.52      www      3728: 
                   3729:     my $envkey;
                   3730:     if ($thisallowed=~/L/) {
1.620     albertel 3731:         foreach $envkey (keys %env) {
1.54      www      3732:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   3733:                my $courseid=$2;
                   3734:                my $roleid=$1.'.'.$2;
1.92      www      3735:                $courseid=~s/^\///;
1.54      www      3736:                my $expiretime=600;
1.620     albertel 3737:                if ($env{'request.role'} eq $roleid) {
1.54      www      3738: 		  $expiretime=120;
                   3739:                }
                   3740: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   3741:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 3742:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 3743: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      3744:                }
1.620     albertel 3745:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   3746:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   3747: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   3748:                        &log($env{'user.domain'},$env{'user.name'},
                   3749:                             $env{'user.home'},
1.57      www      3750:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      3751:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 3752:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      3753: 		       return '';
                   3754:                    }
                   3755:                }
1.620     albertel 3756:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   3757:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   3758: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   3759:                        &log($env{'user.domain'},$env{'user.name'},
                   3760:                             $env{'user.home'},
1.57      www      3761:                             'Locked by priv: '.$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:                }
                   3767: 	   }
1.29      www      3768:        }
1.52      www      3769:     }
                   3770:    
                   3771: #
                   3772: # Rest of the restrictions depend on selected course
                   3773: #
                   3774: 
1.620     albertel 3775:     unless ($env{'request.course.id'}) {
1.766     albertel 3776: 	if ($thisallowed eq 'A') {
                   3777: 	    return 'A';
                   3778: 	} else {
                   3779: 	    return '1';
                   3780: 	}
1.52      www      3781:     }
1.29      www      3782: 
1.52      www      3783: #
                   3784: # Now user is definitely in a course
                   3785: #
1.53      www      3786: 
                   3787: 
                   3788: # Course preferences
                   3789: 
                   3790:    if ($thisallowed=~/C/) {
1.620     albertel 3791:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   3792:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   3793:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 3794: 	   =~/\Q$rolecode\E/) {
1.689     albertel 3795: 	   if ($priv ne 'pch') { 
                   3796: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   3797: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   3798: 			$env{'request.course.id'});
                   3799: 	   }
1.237     www      3800:            return '';
                   3801:        }
                   3802: 
1.620     albertel 3803:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 3804: 	   =~/\Q$unamedom\E/) {
1.689     albertel 3805: 	   if ($priv ne 'pch') { 
                   3806: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   3807: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   3808: 			$env{'request.course.id'});
                   3809: 	   }
1.54      www      3810:            return '';
                   3811:        }
1.53      www      3812:    }
                   3813: 
                   3814: # Resource preferences
                   3815: 
                   3816:    if ($thisallowed=~/R/) {
1.620     albertel 3817:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 3818:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 3819: 	   if ($priv ne 'pch') { 
                   3820: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   3821: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   3822: 	   }
                   3823: 	   return '';
1.54      www      3824:        }
1.53      www      3825:    }
1.30      www      3826: 
1.246     www      3827: # Restricted by state or randomout?
1.30      www      3828: 
1.52      www      3829:    if ($thisallowed=~/X/) {
1.620     albertel 3830:       if ($env{'acc.randomout'}) {
1.579     albertel 3831: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 3832:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      3833:             return ''; 
                   3834:          }
1.247     www      3835:       }
                   3836:       if (&condval($statecond)) {
1.52      www      3837: 	 return '2';
                   3838:       } else {
                   3839:          return '';
                   3840:       }
                   3841:    }
1.30      www      3842: 
1.766     albertel 3843:     if ($thisallowed eq 'A') {
                   3844: 	return 'A';
                   3845:     }
1.52      www      3846:    return 'F';
1.232     www      3847: }
                   3848: 
1.710     albertel 3849: sub split_uri_for_cond {
                   3850:     my $uri=&deversion(&declutter(shift));
                   3851:     my @uriparts=split(/\//,$uri);
                   3852:     my $filename=pop(@uriparts);
                   3853:     my $pathname=join('/',@uriparts);
                   3854:     return ($pathname,$filename);
                   3855: }
1.232     www      3856: # --------------------------------------------------- Is a resource on the map?
                   3857: 
                   3858: sub is_on_map {
1.710     albertel 3859:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 3860:     #Trying to find the conditional for the file
1.620     albertel 3861:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 3862: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      3863:     if ($match) {
1.289     bowersj2 3864: 	return (1,$1);
                   3865:     } else {
1.434     www      3866: 	return (0,0);
1.289     bowersj2 3867:     }
1.12      www      3868: }
                   3869: 
1.427     www      3870: # --------------------------------------------------------- Get symb from alias
                   3871: 
                   3872: sub get_symb_from_alias {
                   3873:     my $symb=shift;
                   3874:     my ($map,$resid,$url)=&decode_symb($symb);
                   3875: # Already is a symb
                   3876:     if ($url) { return $symb; }
                   3877: # Must be an alias
                   3878:     my $aliassymb='';
                   3879:     my %bighash;
1.620     albertel 3880:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      3881:                             &GDBM_READER(),0640)) {
                   3882:         my $rid=$bighash{'mapalias_'.$symb};
                   3883: 	if ($rid) {
                   3884: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 3885: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   3886: 				    $resid,$bighash{'src_'.$rid});
1.427     www      3887: 	}
                   3888:         untie %bighash;
                   3889:     }
                   3890:     return $aliassymb;
                   3891: }
                   3892: 
1.12      www      3893: # ----------------------------------------------------------------- Define Role
                   3894: 
                   3895: sub definerole {
                   3896:   if (allowed('mcr','/')) {
                   3897:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.392     www      3898:     foreach (split(':',$sysrole)) {
1.21      www      3899: 	my ($crole,$cqual)=split(/\&/,$_);
1.479     albertel 3900:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   3901:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   3902: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      3903:                return "refused:s:$crole&$cqual"; 
                   3904:             }
                   3905:         }
1.191     harris41 3906:     }
1.392     www      3907:     foreach (split(':',$domrole)) {
1.21      www      3908: 	my ($crole,$cqual)=split(/\&/,$_);
1.479     albertel 3909:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   3910:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   3911: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      3912:                return "refused:d:$crole&$cqual"; 
                   3913:             }
                   3914:         }
1.191     harris41 3915:     }
1.392     www      3916:     foreach (split(':',$courole)) {
1.21      www      3917: 	my ($crole,$cqual)=split(/\&/,$_);
1.479     albertel 3918:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   3919:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   3920: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      3921:                return "refused:c:$crole&$cqual"; 
                   3922:             }
                   3923:         }
1.191     harris41 3924:     }
1.620     albertel 3925:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   3926:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      3927: 	        "rolesdef_$rolename=".
                   3928:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 3929:     return reply($command,$env{'user.home'});
1.12      www      3930:   } else {
                   3931:     return 'refused';
                   3932:   }
1.105     harris41 3933: }
                   3934: 
                   3935: # ---------------- Make a metadata query against the network of library servers
                   3936: 
                   3937: sub metadata_query {
1.244     matthew  3938:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 3939:     my %rhash;
1.244     matthew  3940:     my @server_list = (defined($server_array) ? @$server_array
                   3941:                                               : keys(%libserv) );
                   3942:     for my $server (@server_list) {
1.118     harris41 3943: 	unless ($custom or $customshow) {
                   3944: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   3945: 	    $rhash{$server}=$reply;
                   3946: 	}
                   3947: 	else {
                   3948: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   3949: 			     &escape($custom).':'.&escape($customshow),
                   3950: 			     $server);
                   3951: 	    $rhash{$server}=$reply;
                   3952: 	}
1.112     harris41 3953:     }
1.118     harris41 3954:     return \%rhash;
1.240     www      3955: }
                   3956: 
                   3957: # ----------------------------------------- Send log queries and wait for reply
                   3958: 
                   3959: sub log_query {
                   3960:     my ($uname,$udom,$query,%filters)=@_;
                   3961:     my $uhome=&homeserver($uname,$udom);
                   3962:     if ($uhome eq 'no_host') { return 'error: no_host'; }
                   3963:     my $uhost=$hostname{$uhome};
1.241     www      3964:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys %filters));
1.240     www      3965:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   3966:                        $uhome);
1.479     albertel 3967:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      3968:     return get_query_reply($queryid);
                   3969: }
                   3970: 
1.508     raeburn  3971: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  3972: 
                   3973: sub fetch_enrollment_query {
1.511     raeburn  3974:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  3975:     my $homeserver;
1.547     raeburn  3976:     my $maxtries = 1;
1.508     raeburn  3977:     if ($context eq 'automated') {
                   3978:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  3979:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  3980:     } else {
                   3981:         $homeserver = &homeserver($cnum,$dom);
                   3982:     }
1.506     raeburn  3983:     my $host=$hostname{$homeserver};
                   3984:     my $cmd = '';
                   3985:     foreach (keys %{$affiliatesref}) {
1.508     raeburn  3986:         $cmd .= $_.'='.join(",",@{$$affiliatesref{$_}}).'%%';
1.506     raeburn  3987:     }
                   3988:     $cmd =~ s/%%$//;
                   3989:     $cmd = &escape($cmd);
                   3990:     my $query = 'fetchenrollment';
1.620     albertel 3991:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  3992:     unless ($queryid=~/^\Q$host\E\_/) { 
                   3993:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   3994:         return 'error: '.$queryid;
                   3995:     }
1.506     raeburn  3996:     my $reply = &get_query_reply($queryid);
1.547     raeburn  3997:     my $tries = 1;
                   3998:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   3999:         $reply = &get_query_reply($queryid);
                   4000:         $tries ++;
                   4001:     }
1.526     raeburn  4002:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 4003:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  4004:     } else {
1.515     raeburn  4005:         my @responses = split/:/,$reply;
                   4006:         if ($homeserver eq $perlvar{'lonHostID'}) {
                   4007:             foreach (@responses) {
                   4008:                 my ($key,$value) = split/=/,$_;
                   4009:                 $$replyref{$key} = $value;
                   4010:             }
                   4011:         } else {
1.506     raeburn  4012:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
                   4013:             foreach (@responses) {
                   4014:                 my ($key,$value) = split/=/,$_;
                   4015:                 $$replyref{$key} = $value;
                   4016:                 if ($value > 0) {
                   4017:                     foreach (@{$$affiliatesref{$key}}) {
                   4018:                         my $filename = $dom.'_'.$key.'_'.$_.'_classlist.xml';
                   4019:                         my $destname = $pathname.'/'.$filename;
                   4020:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  4021:                         if ($xml_classlist =~ /^error/) {
                   4022:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   4023:                         } else {
1.506     raeburn  4024:                             if ( open(FILE,">$destname") ) {
                   4025:                                 print FILE &unescape($xml_classlist);
                   4026:                                 close(FILE);
1.526     raeburn  4027:                             } else {
                   4028:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  4029:                             }
                   4030:                         }
                   4031:                     }
                   4032:                 }
                   4033:             }
                   4034:         }
                   4035:         return 'ok';
                   4036:     }
                   4037:     return 'error';
                   4038: }
                   4039: 
1.242     www      4040: sub get_query_reply {
                   4041:     my $queryid=shift;
1.240     www      4042:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   4043:     my $reply='';
                   4044:     for (1..100) {
                   4045: 	sleep 2;
                   4046:         if (-e $replyfile.'.end') {
1.448     albertel 4047: 	    if (open(my $fh,$replyfile)) {
1.240     www      4048:                $reply.=<$fh>;
1.448     albertel 4049:                close($fh);
1.240     www      4050: 	   } else { return 'error: reply_file_error'; }
1.242     www      4051:            return &unescape($reply);
                   4052: 	}
1.240     www      4053:     }
1.242     www      4054:     return 'timeout:'.$queryid;
1.240     www      4055: }
                   4056: 
                   4057: sub courselog_query {
1.241     www      4058: #
                   4059: # possible filters:
                   4060: # url: url or symb
                   4061: # username
                   4062: # domain
                   4063: # action: view, submit, grade
                   4064: # start: timestamp
                   4065: # end: timestamp
                   4066: #
1.240     www      4067:     my (%filters)=@_;
1.620     albertel 4068:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      4069:     if ($filters{'url'}) {
                   4070: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   4071:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   4072:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   4073:     }
1.620     albertel 4074:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4075:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      4076:     return &log_query($cname,$cdom,'courselog',%filters);
                   4077: }
                   4078: 
                   4079: sub userlog_query {
                   4080:     my ($uname,$udom,%filters)=@_;
                   4081:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      4082: }
                   4083: 
1.506     raeburn  4084: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   4085: 
                   4086: sub auto_run {
1.508     raeburn  4087:     my ($cnum,$cdom) = @_;
                   4088:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4089:     my $response = &reply('autorun:'.$cdom,$homeserver);
1.506     raeburn  4090:     return $response;
                   4091: }
1.776     albertel 4092: 
1.506     raeburn  4093: sub auto_get_sections {
1.508     raeburn  4094:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   4095:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  4096:     my @secs = ();
1.511     raeburn  4097:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  4098:     unless ($response eq 'refused') {
                   4099:         @secs = split/:/,$response;
                   4100:     }
                   4101:     return @secs;
                   4102: }
1.776     albertel 4103: 
1.506     raeburn  4104: sub auto_new_course {
1.508     raeburn  4105:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   4106:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  4107:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  4108:     return $response;
                   4109: }
1.776     albertel 4110: 
1.506     raeburn  4111: sub auto_validate_courseID {
1.508     raeburn  4112:     my ($cnum,$cdom,$inst_course_id) = @_;
                   4113:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4114:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  4115:     return $response;
                   4116: }
1.776     albertel 4117: 
1.506     raeburn  4118: sub auto_create_password {
1.508     raeburn  4119:     my ($cnum,$cdom,$authparam) = @_;
                   4120:     my $homeserver = &homeserver($cnum,$cdom); 
1.506     raeburn  4121:     my $create_passwd = 0;
                   4122:     my $authchk = '';
1.511     raeburn  4123:     my $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
1.506     raeburn  4124:     if ($response eq 'refused') {
                   4125:         $authchk = 'refused';
                   4126:     } else {
                   4127:         ($authparam,$create_passwd,$authchk) = split/:/,$response;
                   4128:     }
                   4129:     return ($authparam,$create_passwd,$authchk);
                   4130: }
                   4131: 
1.706     raeburn  4132: sub auto_photo_permission {
                   4133:     my ($cnum,$cdom,$students) = @_;
                   4134:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 4135:     my ($outcome,$perm_reqd,$conditions) = 
                   4136: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 4137:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4138: 	return (undef,undef);
                   4139:     }
1.706     raeburn  4140:     return ($outcome,$perm_reqd,$conditions);
                   4141: }
                   4142: 
                   4143: sub auto_checkphotos {
                   4144:     my ($uname,$udom,$pid) = @_;
                   4145:     my $homeserver = &homeserver($uname,$udom);
                   4146:     my ($result,$resulttype);
                   4147:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 4148: 				   &escape($uname).':'.&escape($pid),
                   4149: 				   $homeserver));
1.709     albertel 4150:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4151: 	return (undef,undef);
                   4152:     }
1.706     raeburn  4153:     if ($outcome) {
                   4154:         ($result,$resulttype) = split(/:/,$outcome);
                   4155:     } 
                   4156:     return ($result,$resulttype);
                   4157: }
                   4158: 
                   4159: sub auto_photochoice {
                   4160:     my ($cnum,$cdom) = @_;
                   4161:     my $homeserver = &homeserver($cnum,$cdom);
                   4162:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 4163: 						       &escape($cdom),
                   4164: 						       $homeserver)));
1.709     albertel 4165:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4166: 	return (undef,undef);
                   4167:     }
1.706     raeburn  4168:     return ($update,$comment);
                   4169: }
                   4170: 
                   4171: sub auto_photoupdate {
                   4172:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   4173:     my $homeserver = &homeserver($cnum,$dom);
                   4174:     my $host=$hostname{$homeserver};
                   4175:     my $cmd = '';
                   4176:     my $maxtries = 1;
                   4177:     foreach (keys %{$affiliatesref}) {
                   4178:         $cmd .= $_.'='.join(",",@{$$affiliatesref{$_}}).'%%';
                   4179:     }
                   4180:     $cmd =~ s/%%$//;
                   4181:     $cmd = &escape($cmd);
                   4182:     my $query = 'institutionalphotos';
                   4183:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   4184:     unless ($queryid=~/^\Q$host\E\_/) {
                   4185:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   4186:         return 'error: '.$queryid;
                   4187:     }
                   4188:     my $reply = &get_query_reply($queryid);
                   4189:     my $tries = 1;
                   4190:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4191:         $reply = &get_query_reply($queryid);
                   4192:         $tries ++;
                   4193:     }
                   4194:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   4195:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   4196:     } else {
                   4197:         my @responses = split(/:/,$reply);
                   4198:         my $outcome = shift(@responses); 
                   4199:         foreach my $item (@responses) {
                   4200:             my ($key,$value) = split(/=/,$item);
                   4201:             $$photo{$key} = $value;
                   4202:         }
                   4203:         return $outcome;
                   4204:     }
                   4205:     return 'error';
                   4206: }
                   4207: 
1.521     raeburn  4208: sub auto_instcode_format {
1.793     albertel 4209:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   4210: 	$cat_order) = @_;
1.521     raeburn  4211:     my $courses = '';
1.772     raeburn  4212:     my @homeservers;
1.521     raeburn  4213:     if ($caller eq 'global') {
1.793     albertel 4214:         foreach my $tryserver (keys(%libserv)) {
1.584     raeburn  4215:             if ($hostdom{$tryserver} eq $codedom) {
1.793     albertel 4216:                 if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
1.772     raeburn  4217:                     push(@homeservers,$tryserver);
                   4218:                 }
1.584     raeburn  4219:             }
                   4220:         }
1.521     raeburn  4221:     } else {
1.772     raeburn  4222:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  4223:     }
1.793     albertel 4224:     foreach my $code (keys(%{$instcodes})) {
                   4225:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  4226:     }
                   4227:     chop($courses);
1.772     raeburn  4228:     my $ok_response = 0;
                   4229:     my $response;
                   4230:     while (@homeservers > 0 && $ok_response == 0) {
                   4231:         my $server = shift(@homeservers); 
                   4232:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   4233:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   4234:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.793     albertel 4235: 		split/:/,$response;
1.772     raeburn  4236:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   4237:             push(@{$codetitles},&str2array($codetitles_str));
                   4238:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   4239:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   4240:             $ok_response = 1;
                   4241:         }
                   4242:     }
                   4243:     if ($ok_response) {
1.521     raeburn  4244:         return 'ok';
1.772     raeburn  4245:     } else {
                   4246:         return $response;
1.521     raeburn  4247:     }
                   4248: }
                   4249: 
1.792     raeburn  4250: sub auto_instcode_defaults {
                   4251:     my ($domain,$returnhash,$code_order) = @_;
                   4252:     my @homeservers;
1.793     albertel 4253:     foreach my $tryserver (keys(%libserv)) {
1.792     raeburn  4254:         if ($hostdom{$tryserver} eq $domain) {
1.793     albertel 4255:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
1.792     raeburn  4256:                 push(@homeservers,$tryserver);
                   4257:             }
                   4258:         }
                   4259:     }
                   4260:     my $ok_response = 0;
                   4261:     my $response;
                   4262:     while (@homeservers > 0 && $ok_response == 0) {
                   4263:         my $server = shift(@homeservers);
                   4264:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
                   4265:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
1.793     albertel 4266:             foreach my $pair (split(/\&/,$response)) {
                   4267:                 my ($name,$value)=split(/\=/,$pair);
1.792     raeburn  4268:                 if ($name eq 'code_order') {
1.796     raeburn  4269:                     @{$code_order} = split(/\&/,&unescape($value));
1.792     raeburn  4270:                 } else {
1.796     raeburn  4271:                     $returnhash->{&unescape($name)}=&unescape($value);
1.792     raeburn  4272:                 }
                   4273:             }
                   4274:         }
                   4275:         $ok_response = 1;
                   4276:     }
                   4277:     if ($ok_response) {
                   4278:         return 'ok';
                   4279:     } else {
                   4280:         return $response;
                   4281:     }
                   4282: } 
                   4283: 
1.777     albertel 4284: sub auto_validate_class_sec {
1.773     raeburn  4285:     my ($cdom,$cnum,$owner,$inst_class) = @_;
                   4286:     my $homeserver = &homeserver($cnum,$cdom);
                   4287:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.774     banghart 4288:                         &escape($owner).':'.$cdom,$homeserver);
1.773     raeburn  4289:     return $response;
                   4290: }
                   4291: 
1.679     raeburn  4292: # ------------------------------------------------------- Course Group routines
                   4293: 
                   4294: sub get_coursegroups {
1.683     raeburn  4295:     my ($cdom,$cnum,$group) = @_;
                   4296:     return(&dump('coursegroups',$cdom,$cnum,$group));
1.679     raeburn  4297: }
                   4298: 
                   4299: sub modify_coursegroup {
                   4300:     my ($cdom,$cnum,$groupsettings) = @_;
                   4301:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   4302: }
                   4303: 
                   4304: sub modify_group_roles {
                   4305:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
                   4306:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   4307:     my $role = 'gr/'.&escape($userprivs);
                   4308:     my ($uname,$udom) = split(/:/,$user);
                   4309:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
1.684     raeburn  4310:     if ($result eq 'ok') {
                   4311:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   4312:     }
1.679     raeburn  4313:     return $result;
                   4314: }
                   4315: 
                   4316: sub modify_coursegroup_membership {
                   4317:     my ($cdom,$cnum,$membership) = @_;
                   4318:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   4319:     return $result;
                   4320: }
                   4321: 
1.682     raeburn  4322: sub get_active_groups {
                   4323:     my ($udom,$uname,$cdom,$cnum) = @_;
                   4324:     my $now = time;
                   4325:     my %groups = ();
                   4326:     foreach my $key (keys(%env)) {
                   4327:         if ($key =~ m-user\.role\.gr\./([^/]+)/([^/]+)/(\w+)$-) {
                   4328:             my ($start,$end) = split(/\./,$env{$key});
                   4329:             if (($end!=0) && ($end<$now)) { next; }
                   4330:             if (($start!=0) && ($start>$now)) { next; }
                   4331:             if ($1 eq $cdom && $2 eq $cnum) {
                   4332:                 $groups{$3} = $env{$key} ;
                   4333:             }
                   4334:         }
                   4335:     }
                   4336:     return %groups;
                   4337: }
                   4338: 
1.683     raeburn  4339: sub get_group_membership {
                   4340:     my ($cdom,$cnum,$group) = @_;
                   4341:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   4342: }
                   4343: 
                   4344: sub get_users_groups {
                   4345:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  4346:     my @usersgroups;
1.683     raeburn  4347:     my $cachetime=1800;
                   4348:     $courseid=~s/\_/\//g;
                   4349:     $courseid=~s/^(\w)/\/$1/;
                   4350: 
                   4351:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  4352:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   4353:     if (defined($cached)) {
1.734     albertel 4354:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  4355:     } else {  
                   4356:         $grouplist = '';
                   4357:         my %roleshash = &dump('roles',$udom,$uname,$courseid);
                   4358:         my ($tmp) = keys(%roleshash);
                   4359:         if ($tmp=~/^error:/) {
                   4360:             &logthis('Error retrieving roles: '.$tmp.' for '.$uname.':'.$udom);
                   4361:         } else {
                   4362:             my $access_end = $env{'course.'.$courseid.
                   4363:                                   '.default_enrollment_end_date'};
                   4364:             my $now = time;
1.734     albertel 4365:             foreach my $key (keys(%roleshash)) {
1.733     raeburn  4366:                 if ($key =~ /^\Q$courseid\E\/(\w+)\_gr$/) {
                   4367:                     my $group = $1;
                   4368:                     if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   4369:                         my $start = $2;
                   4370:                         my $end = $1;
                   4371:                         if ($start == -1) { next; } # deleted from group
                   4372:                         if (($start!=0) && ($start>$now)) { next; }
                   4373:                         if (($end!=0) && ($end<$now)) {
                   4374:                             if ($access_end && $access_end < $now) {
                   4375:                                 if ($access_end - $end < 86400) {
                   4376:                                     push(@usersgroups,$group);
                   4377:                                 }
                   4378:                             }
                   4379:                             next;
                   4380:                         }
                   4381:                         push(@usersgroups,$group);
                   4382:                     }
1.683     raeburn  4383:                 }
                   4384:             }
1.733     raeburn  4385:             @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   4386:             $grouplist = join(':',@usersgroups);
                   4387:             &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  4388:         }
                   4389:     }
1.733     raeburn  4390:     return @usersgroups;
1.683     raeburn  4391: }
                   4392: 
                   4393: sub devalidate_getgroups_cache {
                   4394:     my ($udom,$uname,$cdom,$cnum)=@_;
                   4395:     my $courseid = $cdom.'_'.$cnum;
                   4396:     $courseid=~s/\_/\//g;
                   4397:     $courseid=~s/^(\w)/\/$1/;
                   4398:     my $hashid="$udom:$uname:$courseid";
                   4399:     &devalidate_cache_new('getgroups',$hashid);
                   4400: }
                   4401: 
1.12      www      4402: # ------------------------------------------------------------------ Plain Text
                   4403: 
                   4404: sub plaintext {
1.742     raeburn  4405:     my ($short,$type,$cid) = @_;
1.758     albertel 4406:     if ($short =~ /^cr/) {
                   4407: 	return (split('/',$short))[-1];
                   4408:     }
1.742     raeburn  4409:     if (!defined($cid)) {
                   4410:         $cid = $env{'request.course.id'};
                   4411:     }
                   4412:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
                   4413:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
                   4414:                                           '.plaintext'});
                   4415:     }
                   4416:     my %rolenames = (
                   4417:                       Course => 'std',
                   4418:                       Group => 'alt1',
                   4419:                     );
                   4420:     if (defined($type) && 
                   4421:          defined($rolenames{$type}) && 
                   4422:          defined($prp{$short}{$rolenames{$type}})) {
                   4423:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   4424:     } else {
                   4425:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   4426:     }
1.12      www      4427: }
                   4428: 
                   4429: # ----------------------------------------------------------------- Assign Role
                   4430: 
                   4431: sub assignrole {
1.357     www      4432:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
1.21      www      4433:     my $mrole;
                   4434:     if ($role =~ /^cr\//) {
1.393     www      4435:         my $cwosec=$url;
                   4436:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
                   4437: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      4438:            &logthis('Refused custom assignrole: '.
                   4439:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4440: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4441:            return 'refused'; 
                   4442:         }
1.21      www      4443:         $mrole='cr';
1.678     raeburn  4444:     } elsif ($role =~ /^gr\//) {
                   4445:         my $cwogrp=$url;
                   4446:         $cwogrp=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
                   4447:         unless (&allowed('mdg',$cwogrp)) {
                   4448:             &logthis('Refused group assignrole: '.
                   4449:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   4450:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   4451:             return 'refused';
                   4452:         }
                   4453:         $mrole='gr';
1.21      www      4454:     } else {
1.82      www      4455:         my $cwosec=$url;
1.83      www      4456:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
1.373     www      4457:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
1.104     www      4458:            &logthis('Refused assignrole: '.
                   4459:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4460: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4461:            return 'refused'; 
                   4462:         }
1.21      www      4463:         $mrole=$role;
                   4464:     }
1.620     albertel 4465:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4466:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      4467:     if ($end) { $command.='_'.$end; }
1.21      www      4468:     if ($start) {
                   4469: 	if ($end) { 
1.81      www      4470:            $command.='_'.$start; 
1.21      www      4471:         } else {
1.81      www      4472:            $command.='_0_'.$start;
1.21      www      4473:         }
                   4474:     }
1.739     raeburn  4475:     my $origstart = $start;
                   4476:     my $origend = $end;
1.357     www      4477: # actually delete
                   4478:     if ($deleteflag) {
1.373     www      4479: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      4480: # modify command to delete the role
1.620     albertel 4481:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      4482:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 4483: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      4484: # set start and finish to negative values for userrolelog
                   4485:            $start=-1;
                   4486:            $end=-1;
                   4487:         }
                   4488:     }
                   4489: # send command
1.349     www      4490:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      4491: # log new user role if status is ok
1.349     www      4492:     if ($answer eq 'ok') {
1.663     raeburn  4493: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  4494: # for course roles, perform group memberships changes triggered by role change.
                   4495:         unless ($role =~ /^gr/) {
                   4496:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   4497:                                              $origstart);
                   4498:         }
1.349     www      4499:     }
                   4500:     return $answer;
1.169     harris41 4501: }
                   4502: 
                   4503: # -------------------------------------------------- Modify user authentication
1.197     www      4504: # Overrides without validation
                   4505: 
1.169     harris41 4506: sub modifyuserauth {
                   4507:     my ($udom,$uname,$umode,$upass)=@_;
                   4508:     my $uhome=&homeserver($uname,$udom);
1.197     www      4509:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   4510:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 4511:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4512:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 4513:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   4514: 		     &escape($upass),$uhome);
1.620     albertel 4515:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      4516:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   4517:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   4518:     &log($udom,,$uname,$uhome,
1.620     albertel 4519:         'Authentication changed by '.$env{'user.domain'}.', '.
                   4520:                                      $env{'user.name'}.', '.$umode.
1.197     www      4521:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 4522:     unless ($reply eq 'ok') {
1.197     www      4523:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 4524: 	return 'error: '.$reply;
                   4525:     }   
1.170     harris41 4526:     return 'ok';
1.80      www      4527: }
                   4528: 
1.81      www      4529: # --------------------------------------------------------------- Modify a user
1.80      www      4530: 
1.81      www      4531: sub modifyuser {
1.206     matthew  4532:     my ($udom,    $uname, $uid,
                   4533:         $umode,   $upass, $first,
                   4534:         $middle,  $last,  $gene,
1.387     www      4535:         $forceid, $desiredhome, $email)=@_;
1.198     www      4536:     $udom=~s/\W//g;
                   4537:     $uname=~s/\W//g;
1.81      www      4538:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4539:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  4540: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   4541:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   4542:                                      ' desiredhome not specified'). 
1.620     albertel 4543:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4544:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 4545:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      4546: # ----------------------------------------------------------------- Create User
1.406     albertel 4547:     if (($uhome eq 'no_host') && 
                   4548: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      4549:         my $unhome='';
1.209     matthew  4550:         if (defined($desiredhome) && $hostdom{$desiredhome} eq $udom) { 
                   4551:             $unhome = $desiredhome;
1.620     albertel 4552: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   4553: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  4554:         } else { # load balancing routine for determining $unhome
1.80      www      4555:             my $tryserver;
1.81      www      4556:             my $loadm=10000000;
1.80      www      4557:             foreach $tryserver (keys %libserv) {
                   4558: 	       if ($hostdom{$tryserver} eq $udom) {
                   4559:                   my $answer=reply('load',$tryserver);
                   4560:                   if (($answer=~/\d+/) && ($answer<$loadm)) {
                   4561: 		      $loadm=$answer;
                   4562:                       $unhome=$tryserver;
                   4563:                   }
                   4564: 	       }
                   4565: 	    }
                   4566:         }
                   4567:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  4568: 	    return 'error: unable to find a home server for '.$uname.
                   4569:                    ' in domain '.$udom;
1.80      www      4570:         }
                   4571:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   4572:                          &escape($upass),$unhome);
                   4573: 	unless ($reply eq 'ok') {
                   4574:             return 'error: '.$reply;
                   4575:         }   
1.230     stredwic 4576:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      4577:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  4578: 	    return 'error: unable verify users home machine.';
1.80      www      4579:         }
1.209     matthew  4580:     }   # End of creation of new user
1.80      www      4581: # ---------------------------------------------------------------------- Add ID
                   4582:     if ($uid) {
                   4583:        $uid=~tr/A-Z/a-z/;
                   4584:        my %uidhash=&idrget($udom,$uname);
1.196     www      4585:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   4586:          && (!$forceid)) {
1.80      www      4587: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  4588: 	      return 'error: user id "'.$uid.'" does not match '.
                   4589:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      4590:           }
                   4591:        } else {
                   4592: 	  &idput($udom,($uname => $uid));
                   4593:        }
                   4594:     }
                   4595: # -------------------------------------------------------------- Add names, etc
1.313     matthew  4596:     my @tmp=&get('environment',
1.134     albertel 4597: 		   ['firstname','middlename','lastname','generation'],
                   4598: 		   $udom,$uname);
1.313     matthew  4599:     my %names;
                   4600:     if ($tmp[0] =~ m/^error:.*/) { 
                   4601:         %names=(); 
                   4602:     } else {
                   4603:         %names = @tmp;
                   4604:     }
1.388     www      4605: #
                   4606: # Make sure to not trash student environment if instructor does not bother
                   4607: # to supply name and email information
                   4608: #
                   4609:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  4610:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      4611:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  4612:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      4613:     if ($email) {
                   4614:        $email=~s/[^\w\@\.\-\,]//gs;
                   4615:        if ($email=~/\@/) { $names{'notification'} = $email;
                   4616: 			   $names{'critnotification'} = $email;
                   4617: 			   $names{'permanentemail'} = $email; }
                   4618:     }
1.134     albertel 4619:     my $reply = &put('environment', \%names, $udom,$uname);
                   4620:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.680     www      4621:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.81      www      4622:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4623:              $umode.', '.$first.', '.$middle.', '.
                   4624: 	     $last.', '.$gene.' by '.
1.620     albertel 4625:              $env{'user.name'}.' at '.$env{'user.domain'});
1.134     albertel 4626:     return 'ok';
1.80      www      4627: }
                   4628: 
1.81      www      4629: # -------------------------------------------------------------- Modify student
1.80      www      4630: 
1.81      www      4631: sub modifystudent {
                   4632:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.515     raeburn  4633:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
1.455     albertel 4634:     if (!$cid) {
1.620     albertel 4635: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 4636: 	    return 'not_in_class';
                   4637: 	}
1.80      www      4638:     }
                   4639: # --------------------------------------------------------------- Make the user
1.81      www      4640:     my $reply=&modifyuser
1.209     matthew  4641: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      4642:          $desiredhome,$email);
1.80      www      4643:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  4644:     # This will cause &modify_student_enrollment to get the uid from the
                   4645:     # students environment
                   4646:     $uid = undef if (!$forceid);
1.455     albertel 4647:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.515     raeburn  4648: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
1.297     matthew  4649:     return $reply;
                   4650: }
                   4651: 
                   4652: sub modify_student_enrollment {
1.515     raeburn  4653:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
1.455     albertel 4654:     my ($cdom,$cnum,$chome);
                   4655:     if (!$cid) {
1.620     albertel 4656: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 4657: 	    return 'not_in_class';
                   4658: 	}
1.620     albertel 4659: 	$cdom=$env{'course.'.$cid.'.domain'};
                   4660: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 4661:     } else {
                   4662: 	($cdom,$cnum)=split(/_/,$cid);
                   4663:     }
1.620     albertel 4664:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 4665:     if (!$chome) {
1.457     raeburn  4666: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  4667:     }
1.455     albertel 4668:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  4669:     # Make sure the user exists
1.81      www      4670:     my $uhome=&homeserver($uname,$udom);
                   4671:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   4672: 	return 'error: no such user';
                   4673:     }
1.297     matthew  4674:     # Get student data if we were not given enough information
                   4675:     if (!defined($first)  || $first  eq '' || 
                   4676:         !defined($last)   || $last   eq '' || 
                   4677:         !defined($uid)    || $uid    eq '' || 
                   4678:         !defined($middle) || $middle eq '' || 
                   4679:         !defined($gene)   || $gene   eq '') {
1.294     matthew  4680:         # They did not supply us with enough data to enroll the student, so
                   4681:         # we need to pick up more information.
1.297     matthew  4682:         my %tmp = &get('environment',
1.294     matthew  4683:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  4684:                        ,$udom,$uname);
                   4685: 
1.455     albertel 4686:         #foreach (keys(%tmp)) {
                   4687:         #    &logthis("key $_ = ".$tmp{$_});
                   4688:         #}
1.294     matthew  4689:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   4690:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   4691:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  4692:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  4693:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   4694:     }
1.556     albertel 4695:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 4696:     my $reply=cput('classlist',
                   4697: 		   {"$uname:$udom" => 
1.515     raeburn  4698: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 4699: 		   $cdom,$cnum);
1.81      www      4700:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   4701: 	return 'error: '.$reply;
1.652     albertel 4702:     } else {
                   4703: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      4704:     }
1.297     matthew  4705:     # Add student role to user
1.83      www      4706:     my $uurl='/'.$cid;
1.81      www      4707:     $uurl=~s/\_/\//g;
                   4708:     if ($usec) {
                   4709: 	$uurl.='/'.$usec;
                   4710:     }
                   4711:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21      www      4712: }
                   4713: 
1.556     albertel 4714: sub format_name {
                   4715:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   4716:     my $name;
                   4717:     if ($first ne 'lastname') {
                   4718: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   4719:     } else {
                   4720: 	if ($lastname=~/\S/) {
                   4721: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   4722: 	    $name=~s/\s+,/,/;
                   4723: 	} else {
                   4724: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   4725: 	}
                   4726:     }
                   4727:     $name=~s/^\s+//;
                   4728:     $name=~s/\s+$//;
                   4729:     $name=~s/\s+/ /g;
                   4730:     return $name;
                   4731: }
                   4732: 
1.84      www      4733: # ------------------------------------------------- Write to course preferences
                   4734: 
                   4735: sub writecoursepref {
                   4736:     my ($courseid,%prefs)=@_;
                   4737:     $courseid=~s/^\///;
                   4738:     $courseid=~s/\_/\//g;
                   4739:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   4740:     my $chome=homeserver($cnum,$cdomain);
                   4741:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   4742: 	return 'error: no such course';
                   4743:     }
                   4744:     my $cstring='';
1.191     harris41 4745:     foreach (keys %prefs) {
1.84      www      4746: 	$cstring.=escape($_).'='.escape($prefs{$_}).'&';
1.191     harris41 4747:     }
1.84      www      4748:     $cstring=~s/\&$//;
                   4749:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   4750: }
                   4751: 
                   4752: # ---------------------------------------------------------- Make/modify course
                   4753: 
                   4754: sub createcourse {
1.741     raeburn  4755:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
                   4756:         $course_owner,$crstype)=@_;
1.84      www      4757:     $url=&declutter($url);
                   4758:     my $cid='';
1.264     matthew  4759:     unless (&allowed('ccc',$udom)) {
1.84      www      4760:         return 'refused';
                   4761:     }
                   4762: # ------------------------------------------------------------------- Create ID
1.674     www      4763:    my $uname=int(1+rand(9)).
                   4764:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   4765:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      4766:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   4767: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 4768:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      4769:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   4770:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   4771:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 4772:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      4773:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   4774:            return 'error: unable to generate unique course-ID';
                   4775:        } 
                   4776:    }
1.264     matthew  4777: # ------------------------------------------------ Check supplied server name
1.620     albertel 4778:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.264     matthew  4779:     if (! exists($libserv{$course_server})) {
                   4780:         return 'error:bad server name '.$course_server;
                   4781:     }
1.84      www      4782: # ------------------------------------------------------------- Make the course
                   4783:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  4784:                       $course_server);
1.84      www      4785:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 4786:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      4787:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   4788: 	return 'error: no such course';
                   4789:     }
1.271     www      4790: # ----------------------------------------------------------------- Course made
1.516     raeburn  4791: # log existence
                   4792:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
1.741     raeburn  4793:                  ':'.&escape($inst_code).':'.&escape($course_owner).':'.
                   4794:                   &escape($crstype),$uhome);
1.358     www      4795:     &flushcourselogs();
                   4796: # set toplevel url
1.271     www      4797:     my $topurl=$url;
                   4798:     unless ($nonstandard) {
                   4799: # ------------------------------------------ For standard courses, make top url
                   4800:         my $mapurl=&clutter($url);
1.278     www      4801:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 4802:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      4803: <map>
                   4804: <resource id="1" type="start"></resource>
                   4805: <resource id="2" src="$mapurl"></resource>
                   4806: <resource id="3" type="finish"></resource>
                   4807: <link index="1" from="1" to="2"></link>
                   4808: <link index="2" from="2" to="3"></link>
                   4809: </map>
                   4810: ENDINITMAP
                   4811:         $topurl=&declutter(
1.638     albertel 4812:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      4813:                           );
                   4814:     }
                   4815: # ----------------------------------------------------------- Write preferences
1.84      www      4816:     &writecoursepref($udom.'_'.$uname,
                   4817:                      ('description' => $description,
1.271     www      4818:                       'url'         => $topurl));
1.84      www      4819:     return '/'.$udom.'/'.$uname;
                   4820: }
                   4821: 
1.21      www      4822: # ---------------------------------------------------------- Assign Custom Role
                   4823: 
                   4824: sub assigncustomrole {
1.357     www      4825:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21      www      4826:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357     www      4827:                        $end,$start,$deleteflag);
1.21      www      4828: }
                   4829: 
                   4830: # ----------------------------------------------------------------- Revoke Role
                   4831: 
                   4832: sub revokerole {
1.357     www      4833:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21      www      4834:     my $now=time;
1.357     www      4835:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21      www      4836: }
                   4837: 
                   4838: # ---------------------------------------------------------- Revoke Custom Role
                   4839: 
                   4840: sub revokecustomrole {
1.357     www      4841:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21      www      4842:     my $now=time;
1.357     www      4843:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
                   4844:            $deleteflag);
1.17      www      4845: }
                   4846: 
1.533     banghart 4847: # ------------------------------------------------------------ Disk usage
1.535     albertel 4848: sub diskusage {
1.533     banghart 4849:     my ($udom,$uname,$directoryRoot)=@_;
                   4850:     $directoryRoot =~ s/\/$//;
1.535     albertel 4851:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
1.514     albertel 4852:     return $listing;
1.512     banghart 4853: }
                   4854: 
1.566     banghart 4855: sub is_locked {
                   4856:     my ($file_name, $domain, $user) = @_;
                   4857:     my @check;
                   4858:     my $is_locked;
                   4859:     push @check, $file_name;
1.613     albertel 4860:     my %locked = &get('file_permissions',\@check,
1.620     albertel 4861: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 4862:     my ($tmp)=keys(%locked);
                   4863:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  4864:     
1.566     banghart 4865:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  4866:         $is_locked = 'false';
                   4867:         foreach my $entry (@{$locked{$file_name}}) {
                   4868:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  4869:                $is_locked = 'true';
                   4870:                last;
1.745     raeburn  4871:            }
                   4872:        }
1.566     banghart 4873:     } else {
                   4874:         $is_locked = 'false';
                   4875:     }
                   4876: }
                   4877: 
1.759     albertel 4878: sub declutter_portfile {
                   4879:     my ($file) = @_;
                   4880:     &logthis("got $file");
                   4881:     $file =~ s-^(/portfolio/|portfolio/)-/-;
                   4882:     &logthis("ret $file");
                   4883:     return $file;
                   4884: }
                   4885: 
1.559     banghart 4886: # ------------------------------------------------------------- Mark as Read Only
                   4887: 
                   4888: sub mark_as_readonly {
                   4889:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 4890:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 4891:     my ($tmp)=keys(%current_permissions);
                   4892:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 4893:     foreach my $file (@{$files}) {
1.759     albertel 4894: 	$file = &declutter_portfile($file);
1.561     banghart 4895:         push(@{$current_permissions{$file}},$what);
1.559     banghart 4896:     }
1.613     albertel 4897:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 4898:     return;
                   4899: }
                   4900: 
1.572     banghart 4901: # ------------------------------------------------------------Save Selected Files
                   4902: 
                   4903: sub save_selected_files {
                   4904:     my ($user, $path, @files) = @_;
                   4905:     my $filename = $user."savedfiles";
1.573     banghart 4906:     my @other_files = &files_not_in_path($user, $path);
1.574     banghart 4907:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 4908:     foreach my $file (@files) {
1.620     albertel 4909:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 4910:     }
                   4911:     foreach my $file (@other_files) {
1.574     banghart 4912:         print (OUT $file."\n");
1.572     banghart 4913:     }
1.574     banghart 4914:     close (OUT);
1.572     banghart 4915:     return 'ok';
                   4916: }
                   4917: 
1.574     banghart 4918: sub clear_selected_files {
                   4919:     my ($user) = @_;
                   4920:     my $filename = $user."savedfiles";
                   4921:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   4922:     print (OUT undef);
                   4923:     close (OUT);
                   4924:     return ("ok");    
                   4925: }
                   4926: 
1.572     banghart 4927: sub files_in_path {
                   4928:     my ($user, $path) = @_;
                   4929:     my $filename = $user."savedfiles";
                   4930:     my %return_files;
1.574     banghart 4931:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 4932:     while (my $line_in = <IN>) {
1.574     banghart 4933:         chomp ($line_in);
                   4934:         my @paths_and_file = split (m!/!, $line_in);
                   4935:         my $file_part = pop (@paths_and_file);
                   4936:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 4937:         $path_part.='/';
                   4938:         my $path_and_file = $path_part.$file_part;
                   4939:         if ($path_part eq $path) {
                   4940:             $return_files{$file_part}= 'selected';
                   4941:         }
                   4942:     }
1.574     banghart 4943:     close (IN);
                   4944:     return (\%return_files);
1.572     banghart 4945: }
                   4946: 
                   4947: # called in portfolio select mode, to show files selected NOT in current directory
                   4948: sub files_not_in_path {
                   4949:     my ($user, $path) = @_;
                   4950:     my $filename = $user."savedfiles";
                   4951:     my @return_files;
                   4952:     my $path_part;
1.574     banghart 4953:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.572     banghart 4954:     while (<IN>) {
                   4955:         #ok, I know it's clunky, but I want it to work
                   4956:         my @paths_and_file = split m!/!, $_;
1.574     banghart 4957:         my $file_part = pop (@paths_and_file);
                   4958:         chomp ($file_part);
                   4959:         my $path_part = join ('/', @paths_and_file);
1.572     banghart 4960:         $path_part .= '/';
                   4961:         my $path_and_file = $path_part.$file_part;
                   4962:         if ($path_part ne $path) {
1.574     banghart 4963:             push (@return_files, ($path_and_file));
1.572     banghart 4964:         }
                   4965:     }
1.574     banghart 4966:     close (OUT);
                   4967:     return (@return_files);
1.572     banghart 4968: }
                   4969: 
1.745     raeburn  4970: #----------------------------------------------Get portfolio file permissions
1.629     banghart 4971: 
1.745     raeburn  4972: sub get_portfile_permissions {
                   4973:     my ($domain,$user) = @_;
1.613     albertel 4974:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 4975:     my ($tmp)=keys(%current_permissions);
                   4976:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  4977:     return \%current_permissions;
                   4978: }
                   4979: 
                   4980: #---------------------------------------------Get portfolio file access controls
                   4981: 
1.749     raeburn  4982: sub get_access_controls {
1.745     raeburn  4983:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 4984:     my %access;
                   4985:     my $real_file = $file;
                   4986:     $file =~ s/\.meta$//;
1.745     raeburn  4987:     if (defined($file)) {
1.749     raeburn  4988:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   4989:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 4990:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  4991:             }
                   4992:         }
1.745     raeburn  4993:     } else {
1.749     raeburn  4994:         foreach my $key (keys(%{$current_permissions})) {
                   4995:             if ($key =~ /\0accesscontrol$/) {
                   4996:                 if (defined($group)) {
                   4997:                     if ($key !~ m-^\Q$group\E/-) {
                   4998:                         next;
                   4999:                     }
                   5000:                 }
                   5001:                 my ($fullpath) = split(/\0/,$key);
                   5002:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   5003:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   5004:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   5005:                     }
                   5006:                 }
                   5007:             }
                   5008:         }
                   5009:     }
                   5010:     return %access;
                   5011: }
                   5012: 
                   5013: sub modify_access_controls {
                   5014:     my ($file_name,$changes,$domain,$user)=@_;
                   5015:     my ($outcome,$deloutcome);
                   5016:     my %store_permissions;
                   5017:     my %new_values;
                   5018:     my %new_control;
                   5019:     my %translation;
                   5020:     my @deletions = ();
                   5021:     my $now = time;
                   5022:     if (exists($$changes{'activate'})) {
                   5023:         if (ref($$changes{'activate'}) eq 'HASH') {
                   5024:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   5025:             my $numnew = scalar(@newitems);
                   5026:             for (my $i=0; $i<$numnew; $i++) {
                   5027:                 my $newkey = $newitems[$i];
                   5028:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797   ! raeburn  5029:                 if ($newkey =~ /^\d+:/) { 
        !          5030:                     $newkey =~ s/^(\d+)/$newid/;
        !          5031:                     $translation{$1} = $newid;
        !          5032:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
        !          5033:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
        !          5034:                     $translation{$1} = $newid;
        !          5035:                 }
1.749     raeburn  5036:                 $new_values{$file_name."\0".$newkey} = 
                   5037:                                           $$changes{'activate'}{$newitems[$i]};
                   5038:                 $new_control{$newkey} = $now;
                   5039:             }
                   5040:         }
                   5041:     }
                   5042:     my %todelete;
                   5043:     my %changed_items;
                   5044:     foreach my $action ('delete','update') {
                   5045:         if (exists($$changes{$action})) {
                   5046:             if (ref($$changes{$action}) eq 'HASH') {
                   5047:                 foreach my $key (keys(%{$$changes{$action}})) {
                   5048:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   5049:                     if ($action eq 'delete') { 
                   5050:                         $todelete{$itemnum} = 1;
                   5051:                     } else {
                   5052:                         $changed_items{$itemnum} = $key;
                   5053:                     }
                   5054:                 }
1.745     raeburn  5055:             }
                   5056:         }
1.749     raeburn  5057:     }
                   5058:     # get lock on access controls for file.
                   5059:     my $lockhash = {
                   5060:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   5061:                                                        ':'.$env{'user.domain'},
                   5062:                    }; 
                   5063:     my $tries = 0;
                   5064:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5065:    
                   5066:     while (($gotlock ne 'ok') && $tries <3) {
                   5067:         $tries ++;
                   5068:         sleep 1;
                   5069:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5070:     }
                   5071:     if ($gotlock eq 'ok') {
                   5072:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   5073:         my ($tmp)=keys(%curr_permissions);
                   5074:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   5075:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   5076:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   5077:             if (ref($curr_controls) eq 'HASH') {
                   5078:                 foreach my $control_item (keys(%{$curr_controls})) {
                   5079:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   5080:                     if (defined($todelete{$itemnum})) {
                   5081:                         push(@deletions,$file_name."\0".$control_item);
                   5082:                     } else {
                   5083:                         if (defined($changed_items{$itemnum})) {
                   5084:                             $new_control{$changed_items{$itemnum}} = $now;
                   5085:                             push(@deletions,$file_name."\0".$control_item);
                   5086:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   5087:                         } else {
                   5088:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   5089:                         }
                   5090:                     }
1.745     raeburn  5091:                 }
                   5092:             }
                   5093:         }
1.749     raeburn  5094:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   5095:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   5096:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   5097:         #  remove lock
                   5098:         my @del_lock = ($file_name."\0".'locked_access_records');
                   5099:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
                   5100:     } else {
                   5101:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  5102:     }
1.749     raeburn  5103:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  5104: }
                   5105: 
                   5106: #------------------------------------------------------Get Marked as Read Only
                   5107: 
                   5108: sub get_marked_as_readonly {
                   5109:     my ($domain,$user,$what,$group) = @_;
                   5110:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 5111:     my @readonly_files;
1.629     banghart 5112:     my $cmp1=$what;
                   5113:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  5114:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5115:         if (defined($group)) {
                   5116:             if ($file_name !~ m-^\Q$group\E/-) {
                   5117:                 next;
                   5118:             }
                   5119:         }
1.561     banghart 5120:         if (ref($value) eq "ARRAY"){
                   5121:             foreach my $stored_what (@{$value}) {
1.629     banghart 5122:                 my $cmp2=$stored_what;
1.759     albertel 5123:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  5124:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  5125:                 }
1.629     banghart 5126:                 if ($cmp1 eq $cmp2) {
1.561     banghart 5127:                     push(@readonly_files, $file_name);
1.745     raeburn  5128:                     last;
1.563     banghart 5129:                 } elsif (!defined($what)) {
                   5130:                     push(@readonly_files, $file_name);
1.745     raeburn  5131:                     last;
1.561     banghart 5132:                 }
                   5133:             }
1.745     raeburn  5134:         }
1.561     banghart 5135:     }
                   5136:     return @readonly_files;
                   5137: }
1.577     banghart 5138: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 5139: 
1.577     banghart 5140: sub get_marked_as_readonly_hash {
1.745     raeburn  5141:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 5142:     my %readonly_files;
1.745     raeburn  5143:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5144:         if (defined($group)) {
                   5145:             if ($file_name !~ m-^\Q$group\E/-) {
                   5146:                 next;
                   5147:             }
                   5148:         }
1.577     banghart 5149:         if (ref($value) eq "ARRAY"){
                   5150:             foreach my $stored_what (@{$value}) {
1.745     raeburn  5151:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 5152:                     foreach my $lock_descriptor(@{$stored_what}) {
                   5153:                         if ($lock_descriptor eq 'graded') {
                   5154:                             $readonly_files{$file_name} = 'graded';
                   5155:                         } elsif ($lock_descriptor eq 'handback') {
                   5156:                             $readonly_files{$file_name} = 'handback';
                   5157:                         } else {
                   5158:                             if (!exists($readonly_files{$file_name})) {
                   5159:                                 $readonly_files{$file_name} = 'locked';
                   5160:                             }
                   5161:                         }
1.745     raeburn  5162:                     }
1.750     banghart 5163:                 } 
1.577     banghart 5164:             }
                   5165:         } 
                   5166:     }
                   5167:     return %readonly_files;
                   5168: }
1.559     banghart 5169: # ------------------------------------------------------------ Unmark as Read Only
                   5170: 
                   5171: sub unmark_as_readonly {
1.629     banghart 5172:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   5173:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  5174:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 5175:     $file_name = &declutter_portfile($file_name);
1.634     albertel 5176:     my $symb_crs = $what;
                   5177:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  5178:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 5179:     my ($tmp)=keys(%current_permissions);
                   5180:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5181:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 5182:     foreach my $file (@readonly_files) {
1.759     albertel 5183: 	my $clean_file = &declutter_portfile($file);
                   5184: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 5185: 	my $current_locks = $current_permissions{$file};
1.563     banghart 5186:         my @new_locks;
                   5187:         my @del_keys;
                   5188:         if (ref($current_locks) eq "ARRAY"){
                   5189:             foreach my $locker (@{$current_locks}) {
1.632     albertel 5190:                 my $compare=$locker;
1.749     raeburn  5191:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  5192:                     $compare=join('',@{$locker});
1.746     raeburn  5193:                     if ($compare ne $symb_crs) {
                   5194:                         push(@new_locks, $locker);
                   5195:                     }
1.563     banghart 5196:                 }
                   5197:             }
1.650     albertel 5198:             if (scalar(@new_locks) > 0) {
1.563     banghart 5199:                 $current_permissions{$file} = \@new_locks;
                   5200:             } else {
                   5201:                 push(@del_keys, $file);
1.613     albertel 5202:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 5203:                 delete($current_permissions{$file});
1.563     banghart 5204:             }
                   5205:         }
1.561     banghart 5206:     }
1.613     albertel 5207:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5208:     return;
                   5209: }
1.512     banghart 5210: 
1.17      www      5211: # ------------------------------------------------------------ Directory lister
                   5212: 
                   5213: sub dirlist {
1.253     stredwic 5214:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
                   5215: 
1.18      www      5216:     $uri=~s/^\///;
                   5217:     $uri=~s/\/$//;
1.253     stredwic 5218:     my ($udom, $uname);
                   5219:     (undef,$udom,$uname)=split(/\//,$uri);
                   5220:     if(defined($userdomain)) {
                   5221:         $udom = $userdomain;
                   5222:     }
                   5223:     if(defined($username)) {
                   5224:         $uname = $username;
                   5225:     }
                   5226: 
                   5227:     my $dirRoot = $perlvar{'lonDocRoot'};
                   5228:     if(defined($alternateDirectoryRoot)) {
                   5229:         $dirRoot = $alternateDirectoryRoot;
                   5230:         $dirRoot =~ s/\/$//;
1.751     banghart 5231:     }
1.253     stredwic 5232: 
                   5233:     if($udom) {
                   5234:         if($uname) {
1.605     matthew  5235:             my $listing=reply('ls2:'.$dirRoot.'/'.$uri,
1.253     stredwic 5236:                               homeserver($uname,$udom));
1.605     matthew  5237:             my @listing_results;
                   5238:             if ($listing eq 'unknown_cmd') {
                   5239:                 $listing=reply('ls:'.$dirRoot.'/'.$uri,
                   5240:                                homeserver($uname,$udom));
                   5241:                 @listing_results = split(/:/,$listing);
                   5242:             } else {
                   5243:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   5244:             }
                   5245:             return @listing_results;
1.253     stredwic 5246:         } elsif(!defined($alternateDirectoryRoot)) {
                   5247:             my $tryserver;
                   5248:             my %allusers=();
                   5249:             foreach $tryserver (keys %libserv) {
                   5250:                 if($hostdom{$tryserver} eq $udom) {
1.605     matthew  5251:                     my $listing=reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
1.253     stredwic 5252:                                       $udom, $tryserver);
1.605     matthew  5253:                     my @listing_results;
                   5254:                     if ($listing eq 'unknown_cmd') {
                   5255:                         $listing=reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   5256:                                        $udom, $tryserver);
                   5257:                         @listing_results = split(/:/,$listing);
                   5258:                     } else {
                   5259:                         @listing_results =
                   5260:                             map { &unescape($_); } split(/:/,$listing);
                   5261:                     }
                   5262:                     if ($listing_results[0] ne 'no_such_dir' && 
                   5263:                         $listing_results[0] ne 'empty'       &&
                   5264:                         $listing_results[0] ne 'con_lost') {
                   5265:                         foreach (@listing_results) {
1.253     stredwic 5266:                             my ($entry,@stat)=split(/&/,$_);
                   5267:                             $allusers{$entry}=1;
                   5268:                         }
                   5269:                     }
1.191     harris41 5270:                 }
1.253     stredwic 5271:             }
                   5272:             my $alluserstr='';
                   5273:             foreach (sort keys %allusers) {
                   5274:                 $alluserstr.=$_.'&user:';
                   5275:             }
                   5276:             $alluserstr=~s/:$//;
                   5277:             return split(/:/,$alluserstr);
                   5278:         } else {
                   5279:             my @emptyResults = ();
                   5280:             push(@emptyResults, 'missing user name');
                   5281:             return split(':',@emptyResults);
                   5282:         }
                   5283:     } elsif(!defined($alternateDirectoryRoot)) {
                   5284:         my $tryserver;
                   5285:         my %alldom=();
                   5286:         foreach $tryserver (keys %libserv) {
                   5287:             $alldom{$hostdom{$tryserver}}=1;
                   5288:         }
                   5289:         my $alldomstr='';
                   5290:         foreach (sort keys %alldom) {
1.397     albertel 5291:             $alldomstr.=$perlvar{'lonDocRoot'}.'/res/'.$_.'/&domain:';
1.253     stredwic 5292:         }
                   5293:         $alldomstr=~s/:$//;
                   5294:         return split(/:/,$alldomstr);       
                   5295:     } else {
                   5296:         my @emptyResults = ();
                   5297:         push(@emptyResults, 'missing domain');
                   5298:         return split(':',@emptyResults);
1.275     stredwic 5299:     }
                   5300: }
                   5301: 
                   5302: # --------------------------------------------- GetFileTimestamp
                   5303: # This function utilizes dirlist and returns the date stamp for
                   5304: # when it was last modified.  It will also return an error of -1
                   5305: # if an error occurs
                   5306: 
1.410     matthew  5307: ##
                   5308: ## FIXME: This subroutine assumes its caller knows something about the
                   5309: ## directory structure of the home server for the student ($root).
                   5310: ## Not a good assumption to make.  Since this is for looking up files
                   5311: ## in user directories, the full path should be constructed by lond, not
                   5312: ## whatever machine we request data from.
                   5313: ##
1.275     stredwic 5314: sub GetFileTimestamp {
                   5315:     my ($studentDomain,$studentName,$filename,$root)=@_;
                   5316:     $studentDomain=~s/\W//g;
                   5317:     $studentName=~s/\W//g;
                   5318:     my $subdir=$studentName.'__';
                   5319:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   5320:     my $proname="$studentDomain/$subdir/$studentName";
                   5321:     $proname .= '/'.$filename;
1.375     matthew  5322:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
                   5323:                                               $studentName, $root);
1.275     stredwic 5324:     my @stats = split('&', $fileStat);
                   5325:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  5326:         # @stats contains first the filename, then the stat output
                   5327:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 5328:     } else {
                   5329:         return -1;
1.253     stredwic 5330:     }
1.26      www      5331: }
                   5332: 
1.712     albertel 5333: sub stat_file {
                   5334:     my ($uri) = @_;
1.787     albertel 5335:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 5336: 
1.712     albertel 5337:     my ($udom,$uname,$file,$dir);
                   5338:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   5339: 	($udom,$uname,$file) =
                   5340: 	    ($uri =~ m-/(?:uploaded|editupload)/?([^/]*)/?([^/]*)/?(.*)-);
                   5341: 	$file = 'userfiles/'.$file;
1.740     www      5342: 	$dir = &propath($udom,$uname);
1.712     albertel 5343:     }
                   5344:     if ($uri =~ m-^/res/-) {
                   5345: 	($udom,$uname) = 
                   5346: 	    ($uri =~ m-/(?:res)/?([^/]*)/?([^/]*)/-);
                   5347: 	$file = $uri;
                   5348:     }
                   5349: 
                   5350:     if (!$udom || !$uname || !$file) {
                   5351: 	# unable to handle the uri
                   5352: 	return ();
                   5353:     }
                   5354: 
                   5355:     my ($result) = &dirlist($file,$udom,$uname,$dir);
                   5356:     my @stats = split('&', $result);
1.721     banghart 5357:     
1.712     albertel 5358:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   5359: 	shift(@stats); #filename is first
                   5360: 	return @stats;
                   5361:     }
                   5362:     return ();
                   5363: }
                   5364: 
1.26      www      5365: # -------------------------------------------------------- Value of a Condition
                   5366: 
1.713     albertel 5367: # gets the value of a specific preevaluated condition
                   5368: #    stored in the string  $env{user.state.<cid>}
                   5369: # or looks up a condition reference in the bighash and if if hasn't
                   5370: # already been evaluated recurses into docondval to get the value of
                   5371: # the condition, then memoizing it to 
                   5372: #   $env{user.state.<cid>.<condition>}
1.40      www      5373: sub directcondval {
                   5374:     my $number=shift;
1.620     albertel 5375:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 5376: 	&Apache::lonuserstate::evalstate();
                   5377:     }
1.713     albertel 5378:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   5379: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   5380:     } elsif ($number =~ /^_/) {
                   5381: 	my $sub_condition;
                   5382: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   5383: 		&GDBM_READER(),0640)) {
                   5384: 	    $sub_condition=$bighash{'conditions'.$number};
                   5385: 	    untie(%bighash);
                   5386: 	}
                   5387: 	my $value = &docondval($sub_condition);
                   5388: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
                   5389: 	return $value;
                   5390:     }
1.620     albertel 5391:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   5392:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      5393:     } else {
                   5394:        return 2;
                   5395:     }
                   5396: }
                   5397: 
1.713     albertel 5398: # get the collection of conditions for this resource
1.26      www      5399: sub condval {
                   5400:     my $condidx=shift;
1.54      www      5401:     my $allpathcond='';
1.713     albertel 5402:     foreach my $cond (split(/\|/,$condidx)) {
                   5403: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   5404: 	    $allpathcond.=
                   5405: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   5406: 	}
1.191     harris41 5407:     }
1.54      www      5408:     $allpathcond=~s/\|$//;
1.713     albertel 5409:     return &docondval($allpathcond);
                   5410: }
                   5411: 
                   5412: #evaluates an expression of conditions
                   5413: sub docondval {
                   5414:     my ($allpathcond) = @_;
                   5415:     my $result=0;
                   5416:     if ($env{'request.course.id'}
                   5417: 	&& defined($allpathcond)) {
                   5418: 	my $operand='|';
                   5419: 	my @stack;
                   5420: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   5421: 	    if ($chunk eq '(') {
                   5422: 		push @stack,($operand,$result);
                   5423: 	    } elsif ($chunk eq ')') {
                   5424: 		my $before=pop @stack;
                   5425: 		if (pop @stack eq '&') {
                   5426: 		    $result=$result>$before?$before:$result;
                   5427: 		} else {
                   5428: 		    $result=$result>$before?$result:$before;
                   5429: 		}
                   5430: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   5431: 		$operand=$chunk;
                   5432: 	    } else {
                   5433: 		my $new=directcondval($chunk);
                   5434: 		if ($operand eq '&') {
                   5435: 		    $result=$result>$new?$new:$result;
                   5436: 		} else {
                   5437: 		    $result=$result>$new?$result:$new;
                   5438: 		}
                   5439: 	    }
                   5440: 	}
1.26      www      5441:     }
                   5442:     return $result;
1.421     albertel 5443: }
                   5444: 
                   5445: # ---------------------------------------------------- Devalidate courseresdata
                   5446: 
                   5447: sub devalidatecourseresdata {
                   5448:     my ($coursenum,$coursedomain)=@_;
                   5449:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 5450:     &devalidate_cache_new('courseres',$hashid);
1.28      www      5451: }
                   5452: 
1.763     www      5453: 
1.200     www      5454: # --------------------------------------------------- Course Resourcedata Query
                   5455: 
1.624     albertel 5456: sub get_courseresdata {
                   5457:     my ($coursenum,$coursedomain)=@_;
1.200     www      5458:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   5459:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 5460:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 5461:     my %dumpreply;
1.417     albertel 5462:     unless (defined($cached)) {
1.624     albertel 5463: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 5464: 	$result=\%dumpreply;
1.251     albertel 5465: 	my ($tmp) = keys(%dumpreply);
                   5466: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 5467: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 5468: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   5469: 	    return $tmp;
1.416     albertel 5470: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 5471: 	    $result=undef;
1.599     albertel 5472: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 5473: 	}
                   5474:     }
1.624     albertel 5475:     return $result;
                   5476: }
                   5477: 
1.633     albertel 5478: sub devalidateuserresdata {
                   5479:     my ($uname,$udom)=@_;
                   5480:     my $hashid="$udom:$uname";
                   5481:     &devalidate_cache_new('userres',$hashid);
                   5482: }
                   5483: 
1.624     albertel 5484: sub get_userresdata {
                   5485:     my ($uname,$udom)=@_;
                   5486:     #most student don\'t have any data set, check if there is some data
                   5487:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   5488: 
                   5489:     my $hashid="$udom:$uname";
                   5490:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   5491:     if (!defined($cached)) {
                   5492: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   5493: 	$result=\%resourcedata;
                   5494: 	&do_cache_new('userres',$hashid,$result,600);
                   5495:     }
                   5496:     my ($tmp)=keys(%$result);
                   5497:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   5498: 	return $result;
                   5499:     }
                   5500:     #error 2 occurs when the .db doesn't exist
                   5501:     if ($tmp!~/error: 2 /) {
1.672     albertel 5502: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 5503: 		 " Trying to get resource data for ".
                   5504: 		 $uname." at ".$udom.": ".
                   5505: 		 $tmp."</font>");
                   5506:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 5507: 	#&EXT_cache_set($udom,$uname);
                   5508: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 5509: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 5510:     }
                   5511:     return $tmp;
                   5512: }
                   5513: 
                   5514: sub resdata {
                   5515:     my ($name,$domain,$type,@which)=@_;
                   5516:     my $result;
                   5517:     if ($type eq 'course') {
                   5518: 	$result=&get_courseresdata($name,$domain);
                   5519:     } elsif ($type eq 'user') {
                   5520: 	$result=&get_userresdata($name,$domain);
                   5521:     }
                   5522:     if (!ref($result)) { return $result; }    
1.251     albertel 5523:     foreach my $item (@which) {
1.417     albertel 5524: 	if (defined($result->{$item})) {
                   5525: 	    return $result->{$item};
1.251     albertel 5526: 	}
1.250     albertel 5527:     }
1.291     albertel 5528:     return undef;
1.200     www      5529: }
                   5530: 
1.379     matthew  5531: #
                   5532: # EXT resource caching routines
                   5533: #
                   5534: 
                   5535: sub clear_EXT_cache_status {
1.383     albertel 5536:     &delenv('cache.EXT.');
1.379     matthew  5537: }
                   5538: 
                   5539: sub EXT_cache_status {
                   5540:     my ($target_domain,$target_user) = @_;
1.383     albertel 5541:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 5542:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  5543:         # We know already the user has no data
                   5544:         return 1;
                   5545:     } else {
                   5546:         return 0;
                   5547:     }
                   5548: }
                   5549: 
                   5550: sub EXT_cache_set {
                   5551:     my ($target_domain,$target_user) = @_;
1.383     albertel 5552:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.633     albertel 5553:     #&appenv($cachename => time);
1.379     matthew  5554: }
                   5555: 
1.28      www      5556: # --------------------------------------------------------- Value of a Variable
1.58      www      5557: sub EXT {
1.715     albertel 5558: 
1.395     albertel 5559:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      5560:     unless ($varname) { return ''; }
1.218     albertel 5561:     #get real user name/domain, courseid and symb
                   5562:     my $courseid;
1.359     albertel 5563:     my $publicuser;
1.427     www      5564:     if ($symbparm) {
                   5565: 	$symbparm=&get_symb_from_alias($symbparm);
                   5566:     }
1.218     albertel 5567:     if (!($uname && $udom)) {
1.790     albertel 5568:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 5569:       if (!$symbparm) {	$symbparm=$cursymb; }
                   5570:     } else {
1.620     albertel 5571: 	$courseid=$env{'request.course.id'};
1.218     albertel 5572:     }
1.48      www      5573:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   5574:     my $rest;
1.320     albertel 5575:     if (defined($therest[0])) {
1.48      www      5576:        $rest=join('.',@therest);
                   5577:     } else {
                   5578:        $rest='';
                   5579:     }
1.320     albertel 5580: 
1.57      www      5581:     my $qualifierrest=$qualifier;
                   5582:     if ($rest) { $qualifierrest.='.'.$rest; }
                   5583:     my $spacequalifierrest=$space;
                   5584:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      5585:     if ($realm eq 'user') {
1.48      www      5586: # --------------------------------------------------------------- user.resource
                   5587: 	if ($space eq 'resource') {
1.651     albertel 5588: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   5589: 		  || defined($Apache::lonhomework::parsing_a_task))
                   5590: 		 &&
1.744     albertel 5591: 		 ($symbparm eq &symbread()) ) {	
                   5592: 		# if we are in the middle of processing the resource the
                   5593: 		# get the value we are planning on committing
                   5594:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   5595:                     return $Apache::lonhomework::results{$qualifierrest};
                   5596:                 } else {
                   5597:                     return $Apache::lonhomework::history{$qualifierrest};
                   5598:                 }
1.335     albertel 5599: 	    } else {
1.359     albertel 5600: 		my %restored;
1.620     albertel 5601: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 5602: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   5603: 		} else {
                   5604: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   5605: 		}
1.335     albertel 5606: 		return $restored{$qualifierrest};
                   5607: 	    }
1.48      www      5608: # ----------------------------------------------------------------- user.access
                   5609:         } elsif ($space eq 'access') {
1.218     albertel 5610: 	    # FIXME - not supporting calls for a specific user
1.48      www      5611:             return &allowed($qualifier,$rest);
                   5612: # ------------------------------------------ user.preferences, user.environment
                   5613:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 5614: 	    if (($uname eq $env{'user.name'}) &&
                   5615: 		($udom eq $env{'user.domain'})) {
                   5616: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 5617: 	    } else {
1.359     albertel 5618: 		my %returnhash;
                   5619: 		if (!$publicuser) {
                   5620: 		    %returnhash=&userenvironment($udom,$uname,
                   5621: 						 $qualifierrest);
                   5622: 		}
1.218     albertel 5623: 		return $returnhash{$qualifierrest};
                   5624: 	    }
1.48      www      5625: # ----------------------------------------------------------------- user.course
                   5626:         } elsif ($space eq 'course') {
1.218     albertel 5627: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 5628:             return $env{join('.',('request.course',$qualifier))};
1.48      www      5629: # ------------------------------------------------------------------- user.role
                   5630:         } elsif ($space eq 'role') {
1.218     albertel 5631: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 5632:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      5633:             if ($qualifier eq 'value') {
                   5634: 		return $role;
                   5635:             } elsif ($qualifier eq 'extent') {
                   5636:                 return $where;
                   5637:             }
                   5638: # ----------------------------------------------------------------- user.domain
                   5639:         } elsif ($space eq 'domain') {
1.218     albertel 5640:             return $udom;
1.48      www      5641: # ------------------------------------------------------------------- user.name
                   5642:         } elsif ($space eq 'name') {
1.218     albertel 5643:             return $uname;
1.48      www      5644: # ---------------------------------------------------- Any other user namespace
1.29      www      5645:         } else {
1.359     albertel 5646: 	    my %reply;
                   5647: 	    if (!$publicuser) {
                   5648: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   5649: 	    }
                   5650: 	    return $reply{$qualifierrest};
1.48      www      5651:         }
1.236     www      5652:     } elsif ($realm eq 'query') {
                   5653: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 5654:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   5655: 						[$spacequalifierrest]);
1.620     albertel 5656: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      5657:    } elsif ($realm eq 'request') {
1.48      www      5658: # ------------------------------------------------------------- request.browser
                   5659:         if ($space eq 'browser') {
1.430     www      5660: 	    if ($qualifier eq 'textremote') {
1.676     albertel 5661: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      5662: 		    return 1;
                   5663: 		} else {
                   5664: 		    return 0;
                   5665: 		}
                   5666: 	    } else {
1.620     albertel 5667: 		return $env{'browser.'.$qualifier};
1.430     www      5668: 	    }
1.57      www      5669: # ------------------------------------------------------------ request.filename
                   5670:         } else {
1.620     albertel 5671:             return $env{'request.'.$spacequalifierrest};
1.29      www      5672:         }
1.28      www      5673:     } elsif ($realm eq 'course') {
1.48      www      5674: # ---------------------------------------------------------- course.description
1.620     albertel 5675:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      5676:     } elsif ($realm eq 'resource') {
1.165     www      5677: 
1.620     albertel 5678: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 5679: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   5680: 	}
1.693     albertel 5681: 
                   5682: 	if ($space eq 'title') {
                   5683: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   5684: 	    return &gettitle($symbparm);
                   5685: 	}
                   5686: 	
                   5687: 	if ($space eq 'map') {
                   5688: 	    my ($map) = &decode_symb($symbparm);
                   5689: 	    return &symbread($map);
                   5690: 	}
                   5691: 
                   5692: 	my ($section, $group, @groups);
1.593     albertel 5693: 	my ($courselevelm,$courselevel);
1.539     albertel 5694: 	if ($symbparm && defined($courseid) && 
1.620     albertel 5695: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      5696: 
1.218     albertel 5697: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      5698: 
1.60      www      5699: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 5700: 	    my $symbp=$symbparm;
1.735     albertel 5701: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 5702: 
                   5703: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   5704: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   5705: 
1.620     albertel 5706: 	    if (($env{'user.name'} eq $uname) &&
                   5707: 		($env{'user.domain'} eq $udom)) {
                   5708: 		$section=$env{'request.course.sec'};
1.733     raeburn  5709:                 @groups = split(/:/,$env{'request.course.groups'});  
                   5710:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 5711: 	    } else {
1.539     albertel 5712: 		if (! defined($usection)) {
1.551     albertel 5713: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 5714: 		} else {
                   5715: 		    $section = $usection;
                   5716: 		}
1.733     raeburn  5717:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 5718: 	    }
                   5719: 
                   5720: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   5721: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   5722: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   5723: 
1.593     albertel 5724: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 5725: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 5726: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      5727: 
1.60      www      5728: # ----------------------------------------------------------- first, check user
1.624     albertel 5729: 
                   5730: 	    my $userreply=&resdata($uname,$udom,'user',
                   5731: 				       ($courselevelr,$courselevelm,
                   5732: 					$courselevel));
                   5733: 	    if (defined($userreply)) { return $userreply; }
1.95      www      5734: 
1.594     albertel 5735: # ------------------------------------------------ second, check some of course
1.684     raeburn  5736:             my $coursereply;
1.691     raeburn  5737:             if (@groups > 0) {
                   5738:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   5739:                                        $mapparm,$spacequalifierrest);
1.684     raeburn  5740:                 if (defined($coursereply)) { return $coursereply; }
                   5741:             }
1.96      www      5742: 
1.684     raeburn  5743: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.624     albertel 5744: 				     $env{'course.'.$courseid.'.domain'},
                   5745: 				     'course',
                   5746: 				     ($seclevelr,$seclevelm,$seclevel,
                   5747: 				      $courselevelr));
1.287     albertel 5748: 	    if (defined($coursereply)) { return $coursereply; }
1.200     www      5749: 
1.60      www      5750: # ------------------------------------------------------ third, check map parms
1.218     albertel 5751: 	    my %parmhash=();
                   5752: 	    my $thisparm='';
                   5753: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 5754: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 5755: 		    &GDBM_READER(),0640)) {
1.218     albertel 5756: 		$thisparm=$parmhash{$symbparm};
                   5757: 		untie(%parmhash);
                   5758: 	    }
                   5759: 	    if ($thisparm) { return $thisparm; }
                   5760: 	}
1.594     albertel 5761: # ------------------------------------------ fourth, look in resource metadata
1.71      www      5762: 
1.218     albertel 5763: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 5764: 	my $filename;
                   5765: 	if (!$symbparm) { $symbparm=&symbread(); }
                   5766: 	if ($symbparm) {
1.409     www      5767: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 5768: 	} else {
1.620     albertel 5769: 	    $filename=$env{'request.filename'};
1.282     albertel 5770: 	}
                   5771: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.288     albertel 5772: 	if (defined($metadata)) { return $metadata; }
1.282     albertel 5773: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.288     albertel 5774: 	if (defined($metadata)) { return $metadata; }
1.142     www      5775: 
1.594     albertel 5776: # ---------------------------------------------- fourth, look in rest pf course
1.593     albertel 5777: 	if ($symbparm && defined($courseid) && 
1.620     albertel 5778: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 5779: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   5780: 				     $env{'course.'.$courseid.'.domain'},
                   5781: 				     'course',
                   5782: 				     ($courselevelm,$courselevel));
1.593     albertel 5783: 	    if (defined($coursereply)) { return $coursereply; }
                   5784: 	}
1.145     www      5785: # ------------------------------------------------------------------ Cascade up
1.218     albertel 5786: 	unless ($space eq '0') {
1.336     albertel 5787: 	    my @parts=split(/_/,$space);
                   5788: 	    my $id=pop(@parts);
                   5789: 	    my $part=join('_',@parts);
                   5790: 	    if ($part eq '') { $part='0'; }
                   5791: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 5792: 				 $symbparm,$udom,$uname,$section,1);
1.337     albertel 5793: 	    if (defined($partgeneral)) { return $partgeneral; }
1.218     albertel 5794: 	}
1.395     albertel 5795: 	if ($recurse) { return undef; }
                   5796: 	my $pack_def=&packages_tab_default($filename,$varname);
                   5797: 	if (defined($pack_def)) { return $pack_def; }
1.71      www      5798: 
1.48      www      5799: # ---------------------------------------------------- Any other user namespace
                   5800:     } elsif ($realm eq 'environment') {
                   5801: # ----------------------------------------------------------------- environment
1.620     albertel 5802: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   5803: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 5804: 	} else {
1.770     albertel 5805: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   5806: 		return '';
                   5807: 	    }
1.219     albertel 5808: 	    my %returnhash=&userenvironment($udom,$uname,
                   5809: 					    $spacequalifierrest);
                   5810: 	    return $returnhash{$spacequalifierrest};
                   5811: 	}
1.28      www      5812:     } elsif ($realm eq 'system') {
1.48      www      5813: # ----------------------------------------------------------------- system.time
                   5814: 	if ($space eq 'time') {
                   5815: 	    return time;
                   5816:         }
1.696     albertel 5817:     } elsif ($realm eq 'server') {
                   5818: # ----------------------------------------------------------------- system.time
                   5819: 	if ($space eq 'name') {
                   5820: 	    return $ENV{'SERVER_NAME'};
                   5821:         }
1.28      www      5822:     }
1.48      www      5823:     return '';
1.61      www      5824: }
                   5825: 
1.691     raeburn  5826: sub check_group_parms {
                   5827:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   5828:     my @groupitems = ();
                   5829:     my $resultitem;
                   5830:     my @levels = ($symbparm,$mapparm,$what);
                   5831:     foreach my $group (@{$groups}) {
                   5832:         foreach my $level (@levels) {
                   5833:              my $item = $courseid.'.['.$group.'].'.$level;
                   5834:              push(@groupitems,$item);
                   5835:         }
                   5836:     }
                   5837:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   5838:                             $env{'course.'.$courseid.'.domain'},
                   5839:                                      'course',@groupitems);
                   5840:     return $coursereply;
                   5841: }
                   5842: 
                   5843: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  5844:     my ($courseid,@groups) = @_;
                   5845:     @groups = sort(@groups);
1.691     raeburn  5846:     return @groups;
                   5847: }
                   5848: 
1.395     albertel 5849: sub packages_tab_default {
                   5850:     my ($uri,$varname)=@_;
                   5851:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 5852: 
                   5853:     my (@extension,@specifics,$do_default);
                   5854:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 5855: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 5856: 	if ($pack_type eq 'default') {
                   5857: 	    $do_default=1;
                   5858: 	} elsif ($pack_type eq 'extension') {
                   5859: 	    push(@extension,[$package,$pack_type,$pack_part]);
                   5860: 	} else {
                   5861: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   5862: 	}
                   5863:     }
                   5864:     # first look for a package that matches the requested part id
                   5865:     foreach my $package (@specifics) {
                   5866: 	my (undef,$pack_type,$pack_part)=@{$package};
                   5867: 	next if ($pack_part ne $part);
                   5868: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   5869: 	    return $packagetab{"$pack_type&$name&default"};
                   5870: 	}
                   5871:     }
                   5872:     # look for any possible matching non extension_ package
                   5873:     foreach my $package (@specifics) {
                   5874: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 5875: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   5876: 	    return $packagetab{"$pack_type&$name&default"};
                   5877: 	}
1.585     albertel 5878: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 5879: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   5880: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 5881: 	}
                   5882:     }
1.738     albertel 5883:     # look for any posible extension_ match
                   5884:     foreach my $package (@extension) {
                   5885: 	my ($package,$pack_type)=@{$package};
                   5886: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   5887: 	    return $packagetab{"$pack_type&$name&default"};
                   5888: 	}
                   5889: 	if (defined($packagetab{$package."&$name&default"})) {
                   5890: 	    return $packagetab{$package."&$name&default"};
                   5891: 	}
                   5892:     }
                   5893:     # look for a global default setting
                   5894:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   5895: 	return $packagetab{"default&$name&default"};
                   5896:     }
1.395     albertel 5897:     return undef;
                   5898: }
                   5899: 
1.334     albertel 5900: sub add_prefix_and_part {
                   5901:     my ($prefix,$part)=@_;
                   5902:     my $keyroot;
                   5903:     if (defined($prefix) && $prefix !~ /^__/) {
                   5904: 	# prefix that has a part already
                   5905: 	$keyroot=$prefix;
                   5906:     } elsif (defined($prefix)) {
                   5907: 	# prefix that is missing a part
                   5908: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   5909:     } else {
                   5910: 	# no prefix at all
                   5911: 	if (defined($part)) { $keyroot='_'.$part; }
                   5912:     }
                   5913:     return $keyroot;
                   5914: }
                   5915: 
1.71      www      5916: # ---------------------------------------------------------------- Get metadata
                   5917: 
1.599     albertel 5918: my %metaentry;
1.71      www      5919: sub metadata {
1.176     www      5920:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      5921:     $uri=&declutter($uri);
1.288     albertel 5922:     # if it is a non metadata possible uri return quickly
1.529     albertel 5923:     if (($uri eq '') || 
                   5924: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 5925: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.423     albertel 5926:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
1.489     albertel 5927: 	($uri =~ m|home/[^/]+/public_html/|)) {
1.468     albertel 5928: 	return undef;
1.288     albertel 5929:     }
1.73      www      5930:     my $filename=$uri;
                   5931:     $uri=~s/\.meta$//;
1.172     www      5932: #
                   5933: # Is the metadata already cached?
1.177     www      5934: # Look at timestamp of caching
1.172     www      5935: # Everything is cached by the main uri, libraries are never directly cached
                   5936: #
1.428     albertel 5937:     if (!defined($liburi)) {
1.599     albertel 5938: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 5939: 	if (defined($cached)) { return $result->{':'.$what}; }
                   5940:     }
                   5941:     {
1.172     www      5942: #
                   5943: # Is this a recursive call for a library?
                   5944: #
1.599     albertel 5945: #	if (! exists($metacache{$uri})) {
                   5946: #	    $metacache{$uri}={};
                   5947: #	}
1.171     www      5948:         if ($liburi) {
                   5949: 	    $liburi=&declutter($liburi);
                   5950:             $filename=$liburi;
1.401     bowersj2 5951:         } else {
1.599     albertel 5952: 	    &devalidate_cache_new('meta',$uri);
                   5953: 	    undef(%metaentry);
1.401     bowersj2 5954: 	}
1.140     www      5955:         my %metathesekeys=();
1.73      www      5956:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 5957: 	my $metastring;
1.768     albertel 5958: 	if ($uri !~ m -^(editupload)/-) {
1.543     albertel 5959: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 5960: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 5961: 	    $metastring=&getfile($file);
1.489     albertel 5962: 	}
1.208     albertel 5963:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      5964:         my $token;
1.140     www      5965:         undef %metathesekeys;
1.71      www      5966:         while ($token=$parser->get_token) {
1.339     albertel 5967: 	    if ($token->[0] eq 'S') {
                   5968: 		if (defined($token->[2]->{'package'})) {
1.172     www      5969: #
                   5970: # This is a package - get package info
                   5971: #
1.339     albertel 5972: 		    my $package=$token->[2]->{'package'};
                   5973: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   5974: 		    if (defined($token->[2]->{'id'})) { 
                   5975: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   5976: 		    }
1.599     albertel 5977: 		    if ($metaentry{':packages'}) {
                   5978: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 5979: 		    } else {
1.599     albertel 5980: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 5981: 		    }
1.736     albertel 5982: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 5983: 			my $part=$keyroot;
                   5984: 			$part=~s/^\_//;
1.736     albertel 5985: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   5986: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   5987: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 5988: 			    # ignore package.tab specified default values
                   5989:                             # here &package_tab_default() will fetch those
                   5990: 			    if ($subp eq 'default') { next; }
1.736     albertel 5991: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 5992: 			    my $unikey;
                   5993: 			    if ($pack =~ /_0$/) {
                   5994: 				$unikey='parameter_0_'.$name;
                   5995: 				$part=0;
                   5996: 			    } else {
                   5997: 				$unikey='parameter'.$keyroot.'_'.$name;
                   5998: 			    }
1.339     albertel 5999: 			    if ($subp eq 'display') {
                   6000: 				$value.=' [Part: '.$part.']';
                   6001: 			    }
1.599     albertel 6002: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 6003: 			    $metathesekeys{$unikey}=1;
1.599     albertel 6004: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6005: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 6006: 			    }
1.599     albertel 6007: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   6008: 				$metaentry{':'.$unikey}=
                   6009: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 6010: 			    }
1.339     albertel 6011: 			}
                   6012: 		    }
                   6013: 		} else {
1.172     www      6014: #
                   6015: # This is not a package - some other kind of start tag
1.339     albertel 6016: #
                   6017: 		    my $entry=$token->[1];
                   6018: 		    my $unikey;
                   6019: 		    if ($entry eq 'import') {
                   6020: 			$unikey='';
                   6021: 		    } else {
                   6022: 			$unikey=$entry;
                   6023: 		    }
                   6024: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6025: 
                   6026: 		    if (defined($token->[2]->{'id'})) { 
                   6027: 			$unikey.='_'.$token->[2]->{'id'}; 
                   6028: 		    }
1.175     www      6029: 
1.339     albertel 6030: 		    if ($entry eq 'import') {
1.175     www      6031: #
                   6032: # Importing a library here
1.339     albertel 6033: #
                   6034: 			if ($depthcount<20) {
                   6035: 			    my $location=$parser->get_text('/import');
                   6036: 			    my $dir=$filename;
                   6037: 			    $dir=~s|[^/]*$||;
                   6038: 			    $location=&filelocation($dir,$location);
1.736     albertel 6039: 			    my $metadata = 
                   6040: 				&metadata($uri,'keys', $location,$unikey,
                   6041: 					  $depthcount+1);
                   6042: 			    foreach my $meta (split(',',$metadata)) {
                   6043: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   6044: 				$metathesekeys{$meta}=1;
1.339     albertel 6045: 			    }
                   6046: 			}
                   6047: 		    } else { 
                   6048: 			
                   6049: 			if (defined($token->[2]->{'name'})) { 
                   6050: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   6051: 			}
                   6052: 			$metathesekeys{$unikey}=1;
1.736     albertel 6053: 			foreach my $param (@{$token->[3]}) {
                   6054: 			    $metaentry{':'.$unikey.'.'.$param} =
                   6055: 				$token->[2]->{$param};
1.339     albertel 6056: 			}
                   6057: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 6058: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 6059: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   6060: 		 # only ws inside the tag, and not in default, so use default
                   6061: 		 # as value
1.599     albertel 6062: 			    $metaentry{':'.$unikey}=$default;
1.339     albertel 6063: 			} else {
1.321     albertel 6064: 		  # either something interesting inside the tag or default
                   6065:                   # uninteresting
1.599     albertel 6066: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 6067: 			}
1.172     www      6068: # end of not-a-package not-a-library import
1.339     albertel 6069: 		    }
1.172     www      6070: # end of not-a-package start tag
1.339     albertel 6071: 		}
1.172     www      6072: # the next is the end of "start tag"
1.339     albertel 6073: 	    }
                   6074: 	}
1.483     albertel 6075: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.737     albertel 6076: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 6077: 	    #no specific packages #how's our extension
                   6078: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 6079: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 6080: 					 \%metathesekeys);
                   6081: 	}
1.599     albertel 6082: 	if (!exists($metaentry{':packages'})) {
1.737     albertel 6083: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 6084: 		#no specific packages well let's get default then
                   6085: 		if ($key!~/^default&/) { next; }
1.488     albertel 6086: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 6087: 					     \%metathesekeys);
                   6088: 	    }
                   6089: 	}
1.338     www      6090: # are there custom rights to evaluate
1.599     albertel 6091: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 6092: 
1.338     www      6093:     #
                   6094:     # Importing a rights file here
1.339     albertel 6095:     #
                   6096: 	    unless ($depthcount) {
1.599     albertel 6097: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 6098: 		my $dir=$filename;
                   6099: 		$dir=~s|[^/]*$||;
                   6100: 		$location=&filelocation($dir,$location);
1.736     albertel 6101: 		my $rights_metadata =
                   6102: 		    &metadata($uri,'keys',$location,'_rights',
                   6103: 			      $depthcount+1);
                   6104: 		foreach my $rights (split(',',$rights_metadata)) {
                   6105: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   6106: 		    $metathesekeys{$rights}=1;
1.339     albertel 6107: 		}
                   6108: 	    }
                   6109: 	}
1.737     albertel 6110: 	# uniqifiy package listing
                   6111: 	my %seen;
                   6112: 	my @uniq_packages =
                   6113: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   6114: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   6115: 
                   6116: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 6117: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   6118: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.699     albertel 6119: 	&do_cache_new('meta',$uri,\%metaentry,60*60);
1.177     www      6120: # this is the end of "was not already recently cached
1.71      www      6121:     }
1.599     albertel 6122:     return $metaentry{':'.$what};
1.261     albertel 6123: }
                   6124: 
1.488     albertel 6125: sub metadata_create_package_def {
1.483     albertel 6126:     my ($uri,$key,$package,$metathesekeys)=@_;
                   6127:     my ($pack,$name,$subp)=split(/\&/,$key);
                   6128:     if ($subp eq 'default') { next; }
                   6129:     
1.599     albertel 6130:     if (defined($metaentry{':packages'})) {
                   6131: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 6132:     } else {
1.599     albertel 6133: 	$metaentry{':packages'}=$package;
1.483     albertel 6134:     }
                   6135:     my $value=$packagetab{$key};
                   6136:     my $unikey;
                   6137:     $unikey='parameter_0_'.$name;
1.599     albertel 6138:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 6139:     $$metathesekeys{$unikey}=1;
1.599     albertel 6140:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6141: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 6142:     }
1.599     albertel 6143:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   6144: 	$metaentry{':'.$unikey}=
                   6145: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 6146:     }
                   6147: }
                   6148: 
1.261     albertel 6149: sub metadata_generate_part0 {
                   6150:     my ($metadata,$metacache,$uri) = @_;
                   6151:     my %allnames;
1.737     albertel 6152:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 6153: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 6154: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   6155: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 6156: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 6157: 	    $allnames{$name}=$part;
                   6158: 	  }
                   6159: 	}
                   6160:     }
                   6161:     foreach my $name (keys(%allnames)) {
                   6162:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 6163:       my $key=":parameter_0_$name";
1.261     albertel 6164:       $$metacache{"$key.part"}='0';
                   6165:       $$metacache{"$key.name"}=$name;
1.428     albertel 6166:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 6167: 					   $allnames{$name}.'_'.$name.
                   6168: 					   '.type'};
1.428     albertel 6169:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 6170: 			     '.display'};
1.644     www      6171:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 6172:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 6173:       $$metacache{"$key.display"}=$olddis;
                   6174:     }
1.71      www      6175: }
                   6176: 
1.764     albertel 6177: # ------------------------------------------------------ Devalidate title cache
                   6178: 
                   6179: sub devalidate_title_cache {
                   6180:     my ($url)=@_;
                   6181:     if (!$env{'request.course.id'}) { return; }
                   6182:     my $symb=&symbread($url);
                   6183:     if (!$symb) { return; }
                   6184:     my $key=$env{'request.course.id'}."\0".$symb;
                   6185:     &devalidate_cache_new('title',$key);
                   6186: }
                   6187: 
1.301     www      6188: # ------------------------------------------------- Get the title of a resource
                   6189: 
                   6190: sub gettitle {
                   6191:     my $urlsymb=shift;
                   6192:     my $symb=&symbread($urlsymb);
1.534     albertel 6193:     if ($symb) {
1.620     albertel 6194: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 6195: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 6196: 	if (defined($cached)) { 
                   6197: 	    return $result;
                   6198: 	}
1.534     albertel 6199: 	my ($map,$resid,$url)=&decode_symb($symb);
                   6200: 	my $title='';
                   6201: 	my %bighash;
1.620     albertel 6202: 	if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.534     albertel 6203: 		&GDBM_READER(),0640)) {
                   6204: 	    my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   6205: 	    $title=$bighash{'title_'.$mapid.'.'.$resid};
                   6206: 	    untie %bighash;
                   6207: 	}
                   6208: 	$title=~s/\&colon\;/\:/gs;
                   6209: 	if ($title) {
1.599     albertel 6210: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 6211: 	}
                   6212: 	$urlsymb=$url;
                   6213:     }
                   6214:     my $title=&metadata($urlsymb,'title');
                   6215:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   6216:     return $title;
1.301     www      6217: }
1.613     albertel 6218: 
1.614     albertel 6219: sub get_slot {
                   6220:     my ($which,$cnum,$cdom)=@_;
                   6221:     if (!$cnum || !$cdom) {
1.790     albertel 6222: 	(undef,my $courseid)=&whichuser();
1.620     albertel 6223: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   6224: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 6225:     }
1.703     albertel 6226:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   6227:     my %slotinfo;
                   6228:     if (exists($remembered{$key})) {
                   6229: 	$slotinfo{$which} = $remembered{$key};
                   6230:     } else {
                   6231: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   6232: 	&Apache::lonhomework::showhash(%slotinfo);
                   6233: 	my ($tmp)=keys(%slotinfo);
                   6234: 	if ($tmp=~/^error:/) { return (); }
                   6235: 	$remembered{$key} = $slotinfo{$which};
                   6236:     }
1.616     albertel 6237:     if (ref($slotinfo{$which}) eq 'HASH') {
                   6238: 	return %{$slotinfo{$which}};
                   6239:     }
                   6240:     return $slotinfo{$which};
1.614     albertel 6241: }
1.31      www      6242: # ------------------------------------------------- Update symbolic store links
                   6243: 
                   6244: sub symblist {
                   6245:     my ($mapname,%newhash)=@_;
1.438     www      6246:     $mapname=&deversion(&declutter($mapname));
1.31      www      6247:     my %hash;
1.620     albertel 6248:     if (($env{'request.course.fn'}) && (%newhash)) {
                   6249:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6250:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 6251: 	    foreach my $url (keys %newhash) {
                   6252: 		next if ($url eq 'last_known'
                   6253: 			 && $env{'form.no_update_last_known'});
                   6254: 		$hash{declutter($url)}=&encode_symb($mapname,
                   6255: 						    $newhash{$url}->[1],
                   6256: 						    $newhash{$url}->[0]);
1.191     harris41 6257:             }
1.31      www      6258:             if (untie(%hash)) {
                   6259: 		return 'ok';
                   6260:             }
                   6261:         }
                   6262:     }
                   6263:     return 'error';
1.212     www      6264: }
                   6265: 
                   6266: # --------------------------------------------------------------- Verify a symb
                   6267: 
                   6268: sub symbverify {
1.510     www      6269:     my ($symb,$thisurl)=@_;
                   6270:     my $thisfn=$thisurl;
1.439     www      6271:     $thisfn=&declutter($thisfn);
1.215     www      6272: # direct jump to resource in page or to a sequence - will construct own symbs
                   6273:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   6274: # check URL part
1.409     www      6275:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      6276: 
1.431     www      6277:     unless ($url eq $thisfn) { return 0; }
1.213     www      6278: 
1.216     www      6279:     $symb=&symbclean($symb);
1.510     www      6280:     $thisurl=&deversion($thisurl);
1.439     www      6281:     $thisfn=&deversion($thisfn);
1.213     www      6282: 
                   6283:     my %bighash;
                   6284:     my $okay=0;
1.431     www      6285: 
1.620     albertel 6286:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6287:                             &GDBM_READER(),0640)) {
1.510     www      6288:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      6289:         unless ($ids) { 
1.510     www      6290:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      6291:         }
                   6292:         if ($ids) {
                   6293: # ------------------------------------------------------------------- Has ID(s)
                   6294: 	    foreach (split(/\,/,$ids)) {
1.644     www      6295: 	       my ($mapid,$resid)=split(/\./,$_);
1.216     www      6296:                if (
                   6297:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   6298:    eq $symb) { 
1.620     albertel 6299: 		   if (($env{'request.role.adv'}) ||
                   6300: 		       $bighash{'encrypted_'.$_} eq $env{'request.enc'}) {
1.582     albertel 6301: 		       $okay=1; 
                   6302: 		   }
                   6303: 	       }
1.216     www      6304: 	   }
                   6305:         }
1.213     www      6306: 	untie(%bighash);
                   6307:     }
                   6308:     return $okay;
1.31      www      6309: }
                   6310: 
1.210     www      6311: # --------------------------------------------------------------- Clean-up symb
                   6312: 
                   6313: sub symbclean {
                   6314:     my $symb=shift;
1.568     albertel 6315:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      6316: # remove version from map
                   6317:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      6318: 
1.210     www      6319: # remove version from URL
                   6320:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      6321: 
1.507     www      6322: # remove wrapper
                   6323: 
1.510     www      6324:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 6325:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      6326:     return $symb;
1.409     www      6327: }
                   6328: 
                   6329: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 6330: 
                   6331: sub encode_symb {
                   6332:     my ($map,$resid,$url)=@_;
                   6333:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   6334: }
1.409     www      6335: 
                   6336: sub decode_symb {
1.568     albertel 6337:     my $symb=shift;
                   6338:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   6339:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      6340:     return (&fixversion($map),$resid,&fixversion($url));
                   6341: }
                   6342: 
                   6343: sub fixversion {
                   6344:     my $fn=shift;
1.609     banghart 6345:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      6346:     my %bighash;
                   6347:     my $uri=&clutter($fn);
1.620     albertel 6348:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      6349: # is this cached?
1.599     albertel 6350:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      6351:     if (defined($cached)) { return $result; }
                   6352: # unfortunately not cached, or expired
1.620     albertel 6353:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      6354: 	    &GDBM_READER(),0640)) {
                   6355:  	if ($bighash{'version_'.$uri}) {
                   6356:  	    my $version=$bighash{'version_'.$uri};
1.444     www      6357:  	    unless (($version eq 'mostrecent') || 
                   6358: 		    ($version==&getversion($uri))) {
1.440     www      6359:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   6360:  	    }
                   6361:  	}
                   6362:  	untie %bighash;
1.413     www      6363:     }
1.599     albertel 6364:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      6365: }
                   6366: 
                   6367: sub deversion {
                   6368:     my $url=shift;
                   6369:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   6370:     return $url;
1.210     www      6371: }
                   6372: 
1.31      www      6373: # ------------------------------------------------------ Return symb list entry
                   6374: 
                   6375: sub symbread {
1.249     www      6376:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 6377:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 6378:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      6379: # no filename provided? try from environment
1.44      www      6380:     unless ($thisfn) {
1.620     albertel 6381:         if ($env{'request.symb'}) {
                   6382: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 6383: 	}
1.620     albertel 6384: 	$thisfn=$env{'request.filename'};
1.44      www      6385:     }
1.569     albertel 6386:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      6387: # is that filename actually a symb? Verify, clean, and return
                   6388:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 6389: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 6390: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 6391: 	}
1.242     www      6392:     }
1.44      www      6393:     $thisfn=declutter($thisfn);
1.31      www      6394:     my %hash;
1.37      www      6395:     my %bighash;
                   6396:     my $syval='';
1.620     albertel 6397:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  6398:         my $targetfn = $thisfn;
1.609     banghart 6399:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  6400:             $targetfn = 'adm/wrapper/'.$thisfn;
                   6401:         }
1.687     albertel 6402: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   6403: 	    $targetfn=$1;
                   6404: 	}
1.620     albertel 6405:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6406:                       &GDBM_READER(),0640)) {
1.481     raeburn  6407: 	    $syval=$hash{$targetfn};
1.37      www      6408:             untie(%hash);
                   6409:         }
                   6410: # ---------------------------------------------------------- There was an entry
                   6411:         if ($syval) {
1.601     albertel 6412: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 6413: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.601     albertel 6414: 		    #&appenv('request.ambiguous' => $thisfn);
1.620     albertel 6415: 		    #return $env{$cache_str}='';
1.601     albertel 6416: 		#}    
                   6417: 		#$syval.=$1;
                   6418: 	    #}
1.37      www      6419:         } else {
                   6420: # ------------------------------------------------------- Was not in symb table
1.620     albertel 6421:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6422:                             &GDBM_READER(),0640)) {
1.37      www      6423: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      6424:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      6425:               unless ($ids) { 
                   6426:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      6427:               }
                   6428:               unless ($ids) {
                   6429: # alias?
                   6430: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      6431:               }
1.37      www      6432:               if ($ids) {
                   6433: # ------------------------------------------------------------------- Has ID(s)
                   6434:                  my @possibilities=split(/\,/,$ids);
1.39      www      6435:                  if ($#possibilities==0) {
                   6436: # ----------------------------------------------- There is only one possibility
1.37      www      6437: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 6438: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6439: 						    $resid,$thisfn);
1.249     www      6440:                  } elsif (!$donotrecurse) {
1.39      www      6441: # ------------------------------------------ There is more than one possibility
                   6442:                      my $realpossible=0;
1.191     harris41 6443:                      foreach (@possibilities) {
1.39      www      6444: 			 my $file=$bighash{'src_'.$_};
                   6445:                          if (&allowed('bre',$file)) {
                   6446:          		    my ($mapid,$resid)=split(/\./,$_);
                   6447:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   6448: 				$realpossible++;
1.626     albertel 6449:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6450: 						    $resid,$thisfn);
1.39      www      6451:                             }
                   6452: 			 }
1.191     harris41 6453:                      }
1.39      www      6454: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      6455:                  } else {
                   6456:                      $syval='';
1.37      www      6457:                  }
                   6458: 	      }
                   6459:               untie(%bighash)
1.481     raeburn  6460:            }
1.31      www      6461:         }
1.62      www      6462:         if ($syval) {
1.620     albertel 6463: 	    return $env{$cache_str}=$syval;
1.62      www      6464:         }
1.31      www      6465:     }
1.44      www      6466:     &appenv('request.ambiguous' => $thisfn);
1.620     albertel 6467:     return $env{$cache_str}='';
1.31      www      6468: }
                   6469: 
                   6470: # ---------------------------------------------------------- Return random seed
                   6471: 
1.32      www      6472: sub numval {
                   6473:     my $txt=shift;
                   6474:     $txt=~tr/A-J/0-9/;
                   6475:     $txt=~tr/a-j/0-9/;
                   6476:     $txt=~tr/K-T/0-9/;
                   6477:     $txt=~tr/k-t/0-9/;
                   6478:     $txt=~tr/U-Z/0-5/;
                   6479:     $txt=~tr/u-z/0-5/;
                   6480:     $txt=~s/\D//g;
1.564     albertel 6481:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      6482:     return int($txt);
1.368     albertel 6483: }
                   6484: 
1.484     albertel 6485: sub numval2 {
                   6486:     my $txt=shift;
                   6487:     $txt=~tr/A-J/0-9/;
                   6488:     $txt=~tr/a-j/0-9/;
                   6489:     $txt=~tr/K-T/0-9/;
                   6490:     $txt=~tr/k-t/0-9/;
                   6491:     $txt=~tr/U-Z/0-5/;
                   6492:     $txt=~tr/u-z/0-5/;
                   6493:     $txt=~s/\D//g;
                   6494:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   6495:     my $total;
                   6496:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 6497:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 6498:     return int($total);
                   6499: }
                   6500: 
1.575     albertel 6501: sub numval3 {
                   6502:     use integer;
                   6503:     my $txt=shift;
                   6504:     $txt=~tr/A-J/0-9/;
                   6505:     $txt=~tr/a-j/0-9/;
                   6506:     $txt=~tr/K-T/0-9/;
                   6507:     $txt=~tr/k-t/0-9/;
                   6508:     $txt=~tr/U-Z/0-5/;
                   6509:     $txt=~tr/u-z/0-5/;
                   6510:     $txt=~s/\D//g;
                   6511:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   6512:     my $total;
                   6513:     foreach my $val (@txts) { $total+=$val; }
                   6514:     if ($_64bit) { $total=(($total<<32)>>32); }
                   6515:     return $total;
                   6516: }
                   6517: 
1.675     albertel 6518: sub digest {
                   6519:     my ($data)=@_;
                   6520:     my $digest=&Digest::MD5::md5($data);
                   6521:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   6522:     my ($e,$f);
                   6523:     {
                   6524:         use integer;
                   6525:         $e=($a+$b);
                   6526:         $f=($c+$d);
                   6527:         if ($_64bit) {
                   6528:             $e=(($e<<32)>>32);
                   6529:             $f=(($f<<32)>>32);
                   6530:         }
                   6531:     }
                   6532:     if (wantarray) {
                   6533: 	return ($e,$f);
                   6534:     } else {
                   6535: 	my $g;
                   6536: 	{
                   6537: 	    use integer;
                   6538: 	    $g=($e+$f);
                   6539: 	    if ($_64bit) {
                   6540: 		$g=(($g<<32)>>32);
                   6541: 	    }
                   6542: 	}
                   6543: 	return $g;
                   6544:     }
                   6545: }
                   6546: 
1.368     albertel 6547: sub latest_rnd_algorithm_id {
1.675     albertel 6548:     return '64bit5';
1.366     albertel 6549: }
1.32      www      6550: 
1.503     albertel 6551: sub get_rand_alg {
                   6552:     my ($courseid)=@_;
1.790     albertel 6553:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 6554:     if ($courseid) {
1.620     albertel 6555: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 6556:     }
                   6557:     return &latest_rnd_algorithm_id();
                   6558: }
                   6559: 
1.562     albertel 6560: sub validCODE {
                   6561:     my ($CODE)=@_;
                   6562:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   6563:     return 0;
                   6564: }
                   6565: 
1.491     albertel 6566: sub getCODE {
1.620     albertel 6567:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 6568:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   6569: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   6570: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 6571: 	return $Apache::lonhomework::history{'resource.CODE'};
                   6572:     }
                   6573:     return undef;
                   6574: }
                   6575: 
1.31      www      6576: sub rndseed {
1.155     albertel 6577:     my ($symb,$courseid,$domain,$username)=@_;
1.366     albertel 6578: 
1.790     albertel 6579:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.155     albertel 6580:     if (!$symb) {
1.366     albertel 6581: 	unless ($symb=$wsymb) { return time; }
                   6582:     }
                   6583:     if (!$courseid) { $courseid=$wcourseid; }
                   6584:     if (!$domain) { $domain=$wdomain; }
                   6585:     if (!$username) { $username=$wusername }
1.503     albertel 6586:     my $which=&get_rand_alg();
1.491     albertel 6587:     if (defined(&getCODE())) {
1.675     albertel 6588: 	if ($which eq '64bit5') {
                   6589: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   6590: 	} elsif ($which eq '64bit4') {
1.575     albertel 6591: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   6592: 	} else {
                   6593: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   6594: 	}
1.675     albertel 6595:     } elsif ($which eq '64bit5') {
                   6596: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 6597:     } elsif ($which eq '64bit4') {
                   6598: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 6599:     } elsif ($which eq '64bit3') {
                   6600: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 6601:     } elsif ($which eq '64bit2') {
                   6602: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 6603:     } elsif ($which eq '64bit') {
                   6604: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   6605:     }
                   6606:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   6607: }
                   6608: 
                   6609: sub rndseed_32bit {
                   6610:     my ($symb,$courseid,$domain,$username)=@_;
                   6611:     {
                   6612: 	use integer;
                   6613: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   6614: 	my $symbseed=numval($symb) << 22;
                   6615: 	my $namechck=unpack("%32C*",$username) << 17;
                   6616: 	my $nameseed=numval($username) << 12;
                   6617: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   6618: 	my $courseseed=unpack("%32C*",$courseid);
                   6619: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 6620: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6621: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 6622: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 6623: 	return $num;
                   6624:     }
                   6625: }
                   6626: 
                   6627: sub rndseed_64bit {
                   6628:     my ($symb,$courseid,$domain,$username)=@_;
                   6629:     {
                   6630: 	use integer;
                   6631: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   6632: 	my $symbseed=numval($symb) << 10;
                   6633: 	my $namechck=unpack("%32S*",$username);
                   6634: 	
                   6635: 	my $nameseed=numval($username) << 21;
                   6636: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   6637: 	my $courseseed=unpack("%32S*",$courseid);
                   6638: 	
                   6639: 	my $num1=$symbchck+$symbseed+$namechck;
                   6640: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6641: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6642: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 6643: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6644: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 6645: 	return "$num1,$num2";
1.155     albertel 6646:     }
1.366     albertel 6647: }
                   6648: 
1.443     albertel 6649: sub rndseed_64bit2 {
                   6650:     my ($symb,$courseid,$domain,$username)=@_;
                   6651:     {
                   6652: 	use integer;
                   6653: 	# strings need to be an even # of cahracters long, it it is odd the
                   6654:         # last characters gets thrown away
                   6655: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6656: 	my $symbseed=numval($symb) << 10;
                   6657: 	my $namechck=unpack("%32S*",$username.' ');
                   6658: 	
                   6659: 	my $nameseed=numval($username) << 21;
1.501     albertel 6660: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6661: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6662: 	
                   6663: 	my $num1=$symbchck+$symbseed+$namechck;
                   6664: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6665: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6666: 	#&logthis("rndseed :$num:$symb");
1.501     albertel 6667: 	return "$num1,$num2";
                   6668:     }
                   6669: }
                   6670: 
                   6671: sub rndseed_64bit3 {
                   6672:     my ($symb,$courseid,$domain,$username)=@_;
                   6673:     {
                   6674: 	use integer;
                   6675: 	# strings need to be an even # of cahracters long, it it is odd the
                   6676:         # last characters gets thrown away
                   6677: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6678: 	my $symbseed=numval2($symb) << 10;
                   6679: 	my $namechck=unpack("%32S*",$username.' ');
                   6680: 	
                   6681: 	my $nameseed=numval2($username) << 21;
1.443     albertel 6682: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6683: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6684: 	
                   6685: 	my $num1=$symbchck+$symbseed+$namechck;
                   6686: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6687: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6688: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 6689: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6690: 	
1.503     albertel 6691: 	return "$num1:$num2";
1.443     albertel 6692:     }
                   6693: }
                   6694: 
1.575     albertel 6695: sub rndseed_64bit4 {
                   6696:     my ($symb,$courseid,$domain,$username)=@_;
                   6697:     {
                   6698: 	use integer;
                   6699: 	# strings need to be an even # of cahracters long, it it is odd the
                   6700:         # last characters gets thrown away
                   6701: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6702: 	my $symbseed=numval3($symb) << 10;
                   6703: 	my $namechck=unpack("%32S*",$username.' ');
                   6704: 	
                   6705: 	my $nameseed=numval3($username) << 21;
                   6706: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6707: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6708: 	
                   6709: 	my $num1=$symbchck+$symbseed+$namechck;
                   6710: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6711: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6712: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 6713: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6714: 	
                   6715: 	return "$num1:$num2";
                   6716:     }
                   6717: }
                   6718: 
1.675     albertel 6719: sub rndseed_64bit5 {
                   6720:     my ($symb,$courseid,$domain,$username)=@_;
                   6721:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   6722:     return "$num1:$num2";
                   6723: }
                   6724: 
1.366     albertel 6725: sub rndseed_CODE_64bit {
                   6726:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 6727:     {
1.366     albertel 6728: 	use integer;
1.443     albertel 6729: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 6730: 	my $symbseed=numval2($symb);
1.491     albertel 6731: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   6732: 	my $CODEseed=numval(&getCODE());
1.443     albertel 6733: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 6734: 	my $num1=$symbseed+$CODEchck;
                   6735: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 6736: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   6737: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 6738: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   6739: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 6740: 	return "$num1:$num2";
1.366     albertel 6741:     }
                   6742: }
                   6743: 
1.575     albertel 6744: sub rndseed_CODE_64bit4 {
                   6745:     my ($symb,$courseid,$domain,$username)=@_;
                   6746:     {
                   6747: 	use integer;
                   6748: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   6749: 	my $symbseed=numval3($symb);
                   6750: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   6751: 	my $CODEseed=numval3(&getCODE());
                   6752: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6753: 	my $num1=$symbseed+$CODEchck;
                   6754: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 6755: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   6756: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 6757: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   6758: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   6759: 	return "$num1:$num2";
                   6760:     }
                   6761: }
                   6762: 
1.675     albertel 6763: sub rndseed_CODE_64bit5 {
                   6764:     my ($symb,$courseid,$domain,$username)=@_;
                   6765:     my $code = &getCODE();
                   6766:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   6767:     return "$num1:$num2";
                   6768: }
                   6769: 
1.366     albertel 6770: sub setup_random_from_rndseed {
                   6771:     my ($rndseed)=@_;
1.503     albertel 6772:     if ($rndseed =~/([,:])/) {
                   6773: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 6774: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   6775:     } else {
                   6776: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 6777:     }
1.36      albertel 6778: }
                   6779: 
1.474     albertel 6780: sub latest_receipt_algorithm_id {
                   6781:     return 'receipt2';
                   6782: }
                   6783: 
1.480     www      6784: sub recunique {
                   6785:     my $fucourseid=shift;
                   6786:     my $unique;
1.620     albertel 6787:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   6788: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      6789:     } else {
                   6790: 	$unique=$perlvar{'lonReceipt'};
                   6791:     }
                   6792:     return unpack("%32C*",$unique);
                   6793: }
                   6794: 
                   6795: sub recprefix {
                   6796:     my $fucourseid=shift;
                   6797:     my $prefix;
1.620     albertel 6798:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   6799: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      6800:     } else {
                   6801: 	$prefix=$perlvar{'lonHostID'};
                   6802:     }
                   6803:     return unpack("%32C*",$prefix);
                   6804: }
                   6805: 
1.76      www      6806: sub ireceipt {
1.474     albertel 6807:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.76      www      6808:     my $cuname=unpack("%32C*",$funame);
                   6809:     my $cudom=unpack("%32C*",$fudom);
                   6810:     my $cucourseid=unpack("%32C*",$fucourseid);
                   6811:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      6812:     my $cunique=&recunique($fucourseid);
1.474     albertel 6813:     my $cpart=unpack("%32S*",$part);
1.480     www      6814:     my $return =&recprefix($fucourseid).'-';
1.620     albertel 6815:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   6816: 	$env{'request.state'} eq 'construct') {
1.790     albertel 6817: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 6818: 			       
                   6819: 	$return.= ($cunique%$cuname+
                   6820: 		   $cunique%$cudom+
                   6821: 		   $cusymb%$cuname+
                   6822: 		   $cusymb%$cudom+
                   6823: 		   $cucourseid%$cuname+
                   6824: 		   $cucourseid%$cudom+
                   6825: 		   $cpart%$cuname+
                   6826: 		   $cpart%$cudom);
                   6827:     } else {
                   6828: 	$return.= ($cunique%$cuname+
                   6829: 		   $cunique%$cudom+
                   6830: 		   $cusymb%$cuname+
                   6831: 		   $cusymb%$cudom+
                   6832: 		   $cucourseid%$cuname+
                   6833: 		   $cucourseid%$cudom);
                   6834:     }
                   6835:     return $return;
1.76      www      6836: }
                   6837: 
                   6838: sub receipt {
1.474     albertel 6839:     my ($part)=@_;
1.790     albertel 6840:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 6841:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      6842: }
1.260     ng       6843: 
1.790     albertel 6844: sub whichuser {
                   6845:     my ($passedsymb)=@_;
                   6846:     my ($symb,$courseid,$domain,$name,$publicuser);
                   6847:     if (defined($env{'form.grade_symb'})) {
                   6848: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   6849: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   6850: 	if (!$allowed &&
                   6851: 	    exists($env{'request.course.sec'}) &&
                   6852: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   6853: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   6854: 			      '/'.$env{'request.course.sec'});
                   6855: 	}
                   6856: 	if ($allowed) {
                   6857: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   6858: 	    $courseid=$tmp_courseid;
                   6859: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   6860: 	    ($name)=&get_env_multiple('form.grade_username');
                   6861: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   6862: 	}
                   6863:     }
                   6864:     if (!$passedsymb) {
                   6865: 	$symb=&symbread();
                   6866:     } else {
                   6867: 	$symb=$passedsymb;
                   6868:     }
                   6869:     $courseid=$env{'request.course.id'};
                   6870:     $domain=$env{'user.domain'};
                   6871:     $name=$env{'user.name'};
                   6872:     if ($name eq 'public' && $domain eq 'public') {
                   6873: 	if (!defined($env{'form.username'})) {
                   6874: 	    $env{'form.username'}.=time.rand(10000000);
                   6875: 	}
                   6876: 	$name.=$env{'form.username'};
                   6877:     }
                   6878:     return ($symb,$courseid,$domain,$name,$publicuser);
                   6879: 
                   6880: }
                   6881: 
1.36      albertel 6882: # ------------------------------------------------------------ Serves up a file
1.472     albertel 6883: # returns either the contents of the file or 
                   6884: # -1 if the file doesn't exist
1.481     raeburn  6885: #
                   6886: # if the target is a file that was uploaded via DOCS, 
                   6887: # a check will be made to see if a current copy exists on the local server,
                   6888: # if it does this will be served, otherwise a copy will be retrieved from
                   6889: # the home server for the course and stored in /home/httpd/html/userfiles on
                   6890: # the local server.   
1.472     albertel 6891: 
1.36      albertel 6892: sub getfile {
1.538     albertel 6893:     my ($file) = @_;
1.609     banghart 6894:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 6895:     &repcopy($file);
                   6896:     return &readfile($file);
                   6897: }
                   6898: 
                   6899: sub repcopy_userfile {
                   6900:     my ($file)=@_;
1.609     banghart 6901:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 6902:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 6903:     my ($cdom,$cnum,$filename) = 
                   6904: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+([^/]+)/+([^/]+)/+(.*)|);
                   6905:     my ($info,$rtncode);
                   6906:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   6907:     if (-e "$file") {
                   6908: 	my @fileinfo = stat($file);
                   6909: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 6910: 	if ($lwpresp ne 'ok') {
                   6911: 	    if ($rtncode eq '404') {
1.538     albertel 6912: 		unlink($file);
1.482     albertel 6913: 	    }
1.517     albertel 6914: 	    #my $ua=new LWP::UserAgent;
1.538     albertel 6915: 	    #my $request=new HTTP::Request('GET',&tokenwrapper($uri));
1.517     albertel 6916: 	    #my $response=$ua->request($request);
                   6917: 	    #if ($response->is_success()) {
                   6918: 	#	return $response->content;
                   6919: 	#    } else {
                   6920: 	#	return -1;
                   6921: 	#    }
1.482     albertel 6922: 	    return -1;
                   6923: 	}
                   6924: 	if ($info < $fileinfo[9]) {
1.607     raeburn  6925: 	    return 'ok';
1.482     albertel 6926: 	}
                   6927: 	$info = '';
1.538     albertel 6928: 	$lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 6929: 	if ($lwpresp ne 'ok') {
                   6930: 	    return -1;
                   6931: 	}
                   6932:     } else {
1.538     albertel 6933: 	my $lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 6934: 	if ($lwpresp ne 'ok') {
1.517     albertel 6935: 	    my $ua=new LWP::UserAgent;
1.538     albertel 6936: 	    my $request=new HTTP::Request('GET',&tokenwrapper($uri));
1.517     albertel 6937: 	    my $response=$ua->request($request);
                   6938: 	    if ($response->is_success()) {
1.538     albertel 6939: 		$info=$response->content;
1.517     albertel 6940: 	    } else {
                   6941: 		return -1;
                   6942: 	    }
1.482     albertel 6943: 	}
                   6944: 	my @parts = ($cdom,$cnum); 
                   6945: 	if ($filename =~ m|^(.+)/[^/]+$|) {
                   6946: 	    push @parts, split(/\//,$1);
1.518     albertel 6947: 	}
1.538     albertel 6948: 	my $path = $perlvar{'lonDocRoot'}.'/userfiles';
1.482     albertel 6949: 	foreach my $part (@parts) {
                   6950: 	    $path .= '/'.$part;
                   6951: 	    if (!-e $path) {
                   6952: 		mkdir($path,0770);
                   6953: 	    }
                   6954: 	}
                   6955:     }
1.538     albertel 6956:     open(FILE,">$file");
1.482     albertel 6957:     print FILE $info;
                   6958:     close(FILE);
1.607     raeburn  6959:     return 'ok';
1.481     raeburn  6960: }
                   6961: 
1.517     albertel 6962: sub tokenwrapper {
                   6963:     my $uri=shift;
1.552     albertel 6964:     $uri=~s|^http\://([^/]+)||;
                   6965:     $uri=~s|^/||;
1.620     albertel 6966:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 6967:     my $token=$1;
1.552     albertel 6968:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   6969:     if ($udom && $uname && $file) {
                   6970: 	$file=~s|(\?\.*)*$||;
1.620     albertel 6971:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
1.552     albertel 6972:         return 'http://'.$hostname{ &homeserver($uname,$udom)}.'/'.$uri.
1.517     albertel 6973:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   6974:                                '&tokenissued='.$perlvar{'lonHostID'};
                   6975:     } else {
                   6976:         return '/adm/notfound.html';
                   6977:     }
                   6978: }
                   6979: 
1.481     raeburn  6980: sub getuploaded {
                   6981:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   6982:     $uri=~s/^\///;
                   6983:     $uri = 'http://'.$hostname{ &homeserver($cnum,$cdom)}.'/raw/'.$uri;
                   6984:     my $ua=new LWP::UserAgent;
                   6985:     my $request=new HTTP::Request($reqtype,$uri);
                   6986:     my $response=$ua->request($request);
                   6987:     $$rtncode = $response->code;
1.482     albertel 6988:     if (! $response->is_success()) {
                   6989: 	return 'failed';
                   6990:     }      
                   6991:     if ($reqtype eq 'HEAD') {
1.486     www      6992: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 6993:     } elsif ($reqtype eq 'GET') {
                   6994: 	$$info = $response->content;
1.472     albertel 6995:     }
1.482     albertel 6996:     return 'ok';
1.36      albertel 6997: }
                   6998: 
1.481     raeburn  6999: sub readfile {
                   7000:     my $file = shift;
                   7001:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   7002:     my $fh;
                   7003:     open($fh,"<$file");
                   7004:     my $a='';
                   7005:     while (<$fh>) { $a .=$_; }
                   7006:     return $a;
                   7007: }
                   7008: 
1.36      albertel 7009: sub filelocation {
1.590     banghart 7010:     my ($dir,$file) = @_;
                   7011:     my $location;
                   7012:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 7013: 
                   7014:     if ($file =~ m-^/adm/-) {
                   7015: 	$file=~s-^/adm/wrapper/-/-;
                   7016: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   7017:     }
1.590     banghart 7018:     if ($file=~m:^/~:) { # is a contruction space reference
                   7019:         $location = $file;
                   7020:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.649     albertel 7021:     } elsif ($file=~m:^/home/[^/]*/public_html/:) {
                   7022: 	# is a correct contruction space reference
                   7023:         $location = $file;
1.609     banghart 7024:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 7025:         my ($udom,$uname,$filename)=
1.609     banghart 7026:   	    ($file=~m -^/+(?:uploaded|editupload)/+([^/]+)/+([^/]+)/+(.*)$-);
1.590     banghart 7027:         my $home=&homeserver($uname,$udom);
                   7028:         my $is_me=0;
                   7029:         my @ids=&current_machine_ids();
                   7030:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   7031:         if ($is_me) {
1.740     www      7032:   	    $location=&propath($udom,$uname).
1.590     banghart 7033:   	      '/userfiles/'.$filename;
                   7034:         } else {
                   7035:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   7036:   	      $udom.'/'.$uname.'/'.$filename;
                   7037:         }
                   7038:     } else {
                   7039:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   7040:         $file=~s:^/res/:/:;
                   7041:         if ( !( $file =~ m:^/:) ) {
                   7042:             $location = $dir. '/'.$file;
                   7043:         } else {
                   7044:             $location = '/home/httpd/html/res'.$file;
                   7045:         }
1.59      albertel 7046:     }
1.590     banghart 7047:     $location=~s://+:/:g; # remove duplicate /
                   7048:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
                   7049:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   7050:     return $location;
1.46      www      7051: }
1.36      albertel 7052: 
1.46      www      7053: sub hreflocation {
                   7054:     my ($dir,$file)=@_;
1.460     albertel 7055:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666     albertel 7056: 	$file=filelocation($dir,$file);
1.700     albertel 7057:     } elsif ($file=~m-^/adm/-) {
                   7058: 	$file=~s-^/adm/wrapper/-/-;
                   7059: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 7060:     }
                   7061:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   7062: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   7063:     } elsif ($file=~m-/home/(\w+)/public_html/-) {
1.462     albertel 7064: 	$file=~s-^/home/(\w+)/public_html/-/~$1/-;
1.666     albertel 7065:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
                   7066: 	$file=~s-^/home/httpd/lonUsers/([^/]*)/./././([^/]*)/userfiles/
                   7067: 	    -/uploaded/$1/$2/-x;
1.46      www      7068:     }
1.462     albertel 7069:     return $file;
1.465     albertel 7070: }
                   7071: 
                   7072: sub current_machine_domains {
                   7073:     my $hostname=$hostname{$perlvar{'lonHostID'}};
                   7074:     my @domains;
                   7075:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  7076: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 7077: 	if ($hostname eq $name) {
                   7078: 	    push(@domains,$hostdom{$id});
                   7079: 	}
                   7080:     }
                   7081:     return @domains;
                   7082: }
                   7083: 
                   7084: sub current_machine_ids {
                   7085:     my $hostname=$hostname{$perlvar{'lonHostID'}};
                   7086:     my @ids;
                   7087:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  7088: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 7089: 	if ($hostname eq $name) {
                   7090: 	    push(@ids,$id);
                   7091: 	}
                   7092:     }
                   7093:     return @ids;
1.31      www      7094: }
                   7095: 
                   7096: # ------------------------------------------------------------- Declutters URLs
                   7097: 
                   7098: sub declutter {
                   7099:     my $thisfn=shift;
1.569     albertel 7100:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 7101:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      7102:     $thisfn=~s/^\///;
1.697     albertel 7103:     $thisfn=~s|^adm/wrapper/||;
                   7104:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      7105:     $thisfn=~s/^res\///;
1.235     www      7106:     $thisfn=~s/\?.+$//;
1.268     www      7107:     return $thisfn;
                   7108: }
                   7109: 
                   7110: # ------------------------------------------------------------- Clutter up URLs
                   7111: 
                   7112: sub clutter {
                   7113:     my $thisfn='/'.&declutter(shift);
1.609     banghart 7114:     unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) { 
1.270     www      7115:        $thisfn='/res'.$thisfn; 
                   7116:     }
1.694     albertel 7117:     if ($thisfn !~m|/adm|) {
1.695     albertel 7118: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 7119: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 7120: 	} else {
                   7121: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   7122: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 7123: 	    if ($embstyle eq 'ssi'
                   7124: 		|| ($embstyle eq 'hdn')
                   7125: 		|| ($embstyle eq 'rat')
                   7126: 		|| ($embstyle eq 'prv')
                   7127: 		|| ($embstyle eq 'ign')) {
                   7128: 		#do nothing with these
                   7129: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 7130: 		|| ($embstyle eq 'emb')
                   7131: 		|| ($embstyle eq 'wrp')) {
                   7132: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 7133: 	    } elsif ($embstyle eq 'unk'
                   7134: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 7135: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 7136: 	    } else {
1.718     www      7137: #		&logthis("Got a blank emb style");
1.695     albertel 7138: 	    }
1.694     albertel 7139: 	}
                   7140:     }
1.31      www      7141:     return $thisfn;
1.12      www      7142: }
                   7143: 
1.787     albertel 7144: sub clutter_with_no_wrapper {
                   7145:     my $uri = &clutter(shift);
                   7146:     if ($uri =~ m-^/adm/-) {
                   7147: 	$uri =~ s-^/adm/wrapper/-/-;
                   7148: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   7149:     }
                   7150:     return $uri;
                   7151: }
                   7152: 
1.557     albertel 7153: sub freeze_escape {
                   7154:     my ($value)=@_;
                   7155:     if (ref($value)) {
                   7156: 	$value=&nfreeze($value);
                   7157: 	return '__FROZEN__'.&escape($value);
                   7158:     }
                   7159:     return &escape($value);
                   7160: }
                   7161: 
1.11      www      7162: 
1.557     albertel 7163: sub thaw_unescape {
                   7164:     my ($value)=@_;
                   7165:     if ($value =~ /^__FROZEN__/) {
                   7166: 	substr($value,0,10,undef);
                   7167: 	$value=&unescape($value);
                   7168: 	return &thaw($value);
                   7169:     }
                   7170:     return &unescape($value);
                   7171: }
                   7172: 
1.436     albertel 7173: sub correct_line_ends {
                   7174:     my ($result)=@_;
                   7175:     $$result =~s/\r\n/\n/mg;
                   7176:     $$result =~s/\r/\n/mg;
1.415     albertel 7177: }
1.1       albertel 7178: # ================================================================ Main Program
                   7179: 
1.184     www      7180: sub goodbye {
1.204     albertel 7181:    &logthis("Starting Shut down");
1.443     albertel 7182: #not converted to using infrastruture and probably shouldn't be
1.599     albertel 7183:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&freeze(\%badServerCache))));
1.443     albertel 7184: #converted
1.599     albertel 7185: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
                   7186:    &logthis(sprintf("%-20s is %s",'%homecache',length(&freeze(\%homecache))));
                   7187: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&freeze(\%titlecache))));
                   7188: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&freeze(\%courseresdatacache))));
1.425     albertel 7189: #1.1 only
1.599     albertel 7190: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&freeze(\%userresdatacache))));
                   7191: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&freeze(\%getsectioncache))));
                   7192: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&freeze(\%courseresversioncache))));
                   7193: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&freeze(\%resversioncache))));
                   7194:    &logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
                   7195:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   7196:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      7197:    &flushcourselogs();
                   7198:    &logthis("Shutting down");
                   7199: }
                   7200: 
1.179     www      7201: BEGIN {
1.228     harris41 7202: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
1.195     www      7203:     unless ($readit) {
1.217     harris41 7204: {
1.781     raeburn  7205:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   7206:     %perlvar = (%perlvar,%{$configvars});
1.227     harris41 7207: }
1.1       albertel 7208: 
1.327     albertel 7209: # ------------------------------------------------------------ Read domain file
                   7210: {
                   7211:     %domaindescription = ();
                   7212:     %domain_auth_def = ();
                   7213:     %domain_auth_arg_def = ();
1.448     albertel 7214:     my $fh;
                   7215:     if (open($fh,"<".$Apache::lonnet::perlvar{'lonTabDir'}.'/domain.tab')) {
1.327     albertel 7216:        while (<$fh>) {
1.390     matthew  7217:            next if (/^(\#|\s*$)/);
                   7218: #           next if /^\#/;
1.327     albertel 7219:            chomp;
1.403     www      7220:            my ($domain, $domain_description, $def_auth, $def_auth_arg,
1.685     raeburn  7221: 	       $def_lang, $city, $longi, $lati, $primary) = split(/:/,$_);
1.403     www      7222: 	   $domain_auth_def{$domain}=$def_auth;
1.327     albertel 7223:            $domain_auth_arg_def{$domain}=$def_auth_arg;
1.403     www      7224: 	   $domaindescription{$domain}=$domain_description;
                   7225: 	   $domain_lang_def{$domain}=$def_lang;
                   7226: 	   $domain_city{$domain}=$city;
                   7227: 	   $domain_longi{$domain}=$longi;
                   7228: 	   $domain_lati{$domain}=$lati;
1.685     raeburn  7229:            $domain_primary{$domain}=$primary;
1.403     www      7230: 
1.448     albertel 7231:  #         &logthis("Domain.tab: $domain, $domain_auth_def{$domain}, $domain_auth_arg_def{$domain},$domaindescription{$domain}");
1.327     albertel 7232: #          &logthis("Domain.tab: $domain ".$domaindescription{$domain} );
1.448     albertel 7233: 	}
1.327     albertel 7234:     }
1.448     albertel 7235:     close ($fh);
1.327     albertel 7236: }
                   7237: 
                   7238: 
1.1       albertel 7239: # ------------------------------------------------------------- Read hosts file
                   7240: {
1.448     albertel 7241:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
1.1       albertel 7242: 
                   7243:     while (my $configline=<$config>) {
1.303     matthew  7244:        next if ($configline =~ /^(\#|\s*$)/);
1.154     www      7245:        chomp($configline);
1.595     albertel 7246:        my ($id,$domain,$role,$name)=split(/:/,$configline);
1.597     albertel 7247:        $name=~s/\s//g;
1.595     albertel 7248:        if ($id && $domain && $role && $name) {
1.252     albertel 7249: 	 $hostname{$id}=$name;
                   7250: 	 $hostdom{$id}=$domain;
                   7251: 	 if ($role eq 'library') { $libserv{$id}=$name; }
1.245     www      7252:        }
1.1       albertel 7253:     }
1.448     albertel 7254:     close($config);
1.619     albertel 7255:     # FIXME: dev server don't want this, production servers _do_ want this
1.654     albertel 7256:     #&get_iphost();
1.1       albertel 7257: }
                   7258: 
1.598     albertel 7259: sub get_iphost {
                   7260:     if (%iphost) { return %iphost; }
1.653     albertel 7261:     my %name_to_ip;
1.598     albertel 7262:     foreach my $id (keys(%hostname)) {
                   7263: 	my $name=$hostname{$id};
1.653     albertel 7264: 	my $ip;
                   7265: 	if (!exists($name_to_ip{$name})) {
                   7266: 	    $ip = gethostbyname($name);
                   7267: 	    if (!$ip || length($ip) ne 4) {
                   7268: 		&logthis("Skipping host $id name $name no IP found\n");
                   7269: 		next;
                   7270: 	    }
                   7271: 	    $ip=inet_ntoa($ip);
                   7272: 	    $name_to_ip{$name} = $ip;
                   7273: 	} else {
                   7274: 	    $ip = $name_to_ip{$name};
1.598     albertel 7275: 	}
                   7276: 	push(@{$iphost{$ip}},$id);
                   7277:     }
                   7278:     return %iphost;
                   7279: }
                   7280: 
1.1       albertel 7281: # ------------------------------------------------------ Read spare server file
                   7282: {
1.448     albertel 7283:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 7284: 
                   7285:     while (my $configline=<$config>) {
                   7286:        chomp($configline);
1.284     matthew  7287:        if ($configline) {
1.784     albertel 7288: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 7289: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 7290: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 7291:        }
                   7292:     }
1.448     albertel 7293:     close($config);
1.1       albertel 7294: }
1.11      www      7295: # ------------------------------------------------------------ Read permissions
                   7296: {
1.448     albertel 7297:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      7298: 
                   7299:     while (my $configline=<$config>) {
1.448     albertel 7300: 	chomp($configline);
                   7301: 	if ($configline) {
                   7302: 	    my ($role,$perm)=split(/ /,$configline);
                   7303: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   7304: 	}
1.11      www      7305:     }
1.448     albertel 7306:     close($config);
1.11      www      7307: }
                   7308: 
                   7309: # -------------------------------------------- Read plain texts for permissions
                   7310: {
1.448     albertel 7311:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      7312: 
                   7313:     while (my $configline=<$config>) {
1.448     albertel 7314: 	chomp($configline);
                   7315: 	if ($configline) {
1.742     raeburn  7316: 	    my ($short,@plain)=split(/:/,$configline);
                   7317:             %{$prp{$short}} = ();
                   7318: 	    if (@plain > 0) {
                   7319:                 $prp{$short}{'std'} = $plain[0];
                   7320:                 for (my $i=1; $i<@plain; $i++) {
                   7321:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   7322:                 }
                   7323:             }
1.448     albertel 7324: 	}
1.135     www      7325:     }
1.448     albertel 7326:     close($config);
1.135     www      7327: }
                   7328: 
                   7329: # ---------------------------------------------------------- Read package table
                   7330: {
1.448     albertel 7331:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      7332: 
                   7333:     while (my $configline=<$config>) {
1.483     albertel 7334: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 7335: 	chomp($configline);
                   7336: 	my ($short,$plain)=split(/:/,$configline);
                   7337: 	my ($pack,$name)=split(/\&/,$short);
                   7338: 	if ($plain ne '') {
                   7339: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   7340: 	    $packagetab{$short}=$plain; 
                   7341: 	}
1.11      www      7342:     }
1.448     albertel 7343:     close($config);
1.329     matthew  7344: }
                   7345: 
                   7346: # ------------- set up temporary directory
                   7347: {
                   7348:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   7349: 
1.11      www      7350: }
                   7351: 
1.794     albertel 7352: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   7353: 				'compress_threshold'=> 20_000,
                   7354:  			        });
1.185     www      7355: 
1.281     www      7356: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      7357: $dumpcount=0;
1.22      www      7358: 
1.163     harris41 7359: &logtouch();
1.672     albertel 7360: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      7361: $readit=1;
1.564     albertel 7362:     {
                   7363: 	use integer;
                   7364: 	my $test=(2**32)+1;
1.568     albertel 7365: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 7366: 	&logthis(" Detected 64bit platform ($_64bit)");
                   7367:     }
1.195     www      7368: }
1.1       albertel 7369: }
1.179     www      7370: 
1.1       albertel 7371: 1;
1.191     harris41 7372: __END__
                   7373: 
1.243     albertel 7374: =pod
                   7375: 
1.191     harris41 7376: =head1 NAME
                   7377: 
1.243     albertel 7378: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 7379: 
                   7380: =head1 SYNOPSIS
                   7381: 
1.243     albertel 7382: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 7383: 
                   7384:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   7385: 
1.243     albertel 7386: Common parameters:
                   7387: 
                   7388: =over 4
                   7389: 
                   7390: =item *
                   7391: 
                   7392: $uname : an internal username (if $cname expecting a course Id specifically)
                   7393: 
                   7394: =item *
                   7395: 
                   7396: $udom : a domain (if $cdom expecting a course's domain specifically)
                   7397: 
                   7398: =item *
                   7399: 
                   7400: $symb : a resource instance identifier
                   7401: 
                   7402: =item *
                   7403: 
                   7404: $namespace : the name of a .db file that contains the data needed or
                   7405: being set.
                   7406: 
                   7407: =back
                   7408: 
1.394     bowersj2 7409: =head1 OVERVIEW
1.191     harris41 7410: 
1.394     bowersj2 7411: lonnet provides subroutines which interact with the
                   7412: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   7413: about classes, users, and resources.
1.243     albertel 7414: 
                   7415: For many of these objects you can also use this to store data about
                   7416: them or modify them in various ways.
1.191     harris41 7417: 
1.394     bowersj2 7418: =head2 Symbs
1.191     harris41 7419: 
1.394     bowersj2 7420: To identify a specific instance of a resource, LON-CAPA uses symbols
                   7421: or "symbs"X<symb>. These identifiers are built from the URL of the
                   7422: map, the resource number of the resource in the map, and the URL of
                   7423: the resource itself. The latter is somewhat redundant, but might help
                   7424: if maps change.
                   7425: 
                   7426: An example is
                   7427: 
                   7428:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   7429: 
                   7430: The respective map entry is
                   7431: 
                   7432:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   7433:   title="Problem 2">
                   7434:  </resource>
                   7435: 
                   7436: Symbs are used by the random number generator, as well as to store and
                   7437: restore data specific to a certain instance of for example a problem.
                   7438: 
                   7439: =head2 Storing And Retrieving Data
                   7440: 
                   7441: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   7442: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   7443: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   7444: is is the non-critical message twin of cstore. These functions are for
                   7445: handlers to store a perl hash to a user's permanent data space in an
                   7446: easy manner, and to retrieve it again on another call. It is expected
                   7447: that a handler would use this once at the beginning to retrieve data,
                   7448: and then again once at the end to send only the new data back.
                   7449: 
                   7450: The data is stored in the user's data directory on the user's
                   7451: homeserver under the ID of the course.
                   7452: 
                   7453: The hash that is returned by restore will have all of the previous
                   7454: value for all of the elements of the hash.
                   7455: 
                   7456: Example:
                   7457: 
                   7458:  #creating a hash
                   7459:  my %hash;
                   7460:  $hash{'foo'}='bar';
                   7461: 
                   7462:  #storing it
                   7463:  &Apache::lonnet::cstore(\%hash);
                   7464: 
                   7465:  #changing a value
                   7466:  $hash{'foo'}='notbar';
                   7467: 
                   7468:  #adding a new value
                   7469:  $hash{'bar'}='foo';
                   7470:  &Apache::lonnet::cstore(\%hash);
                   7471: 
                   7472:  #retrieving the hash
                   7473:  my %history=&Apache::lonnet::restore();
                   7474: 
                   7475:  #print the hash
                   7476:  foreach my $key (sort(keys(%history))) {
                   7477:    print("\%history{$key} = $history{$key}");
                   7478:  }
                   7479: 
                   7480: Will print out:
1.191     harris41 7481: 
1.394     bowersj2 7482:  %history{1:foo} = bar
                   7483:  %history{1:keys} = foo:timestamp
                   7484:  %history{1:timestamp} = 990455579
                   7485:  %history{2:bar} = foo
                   7486:  %history{2:foo} = notbar
                   7487:  %history{2:keys} = foo:bar:timestamp
                   7488:  %history{2:timestamp} = 990455580
                   7489:  %history{bar} = foo
                   7490:  %history{foo} = notbar
                   7491:  %history{timestamp} = 990455580
                   7492:  %history{version} = 2
                   7493: 
                   7494: Note that the special hash entries C<keys>, C<version> and
                   7495: C<timestamp> were added to the hash. C<version> will be equal to the
                   7496: total number of versions of the data that have been stored. The
                   7497: C<timestamp> attribute will be the UNIX time the hash was
                   7498: stored. C<keys> is available in every historical section to list which
                   7499: keys were added or changed at a specific historical revision of a
                   7500: hash.
                   7501: 
                   7502: B<Warning>: do not store the hash that restore returns directly. This
                   7503: will cause a mess since it will restore the historical keys as if the
                   7504: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 7505: 
1.394     bowersj2 7506: Calling convention:
1.191     harris41 7507: 
1.394     bowersj2 7508:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   7509:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 7510: 
1.394     bowersj2 7511: For more detailed information, see lonnet specific documentation.
1.191     harris41 7512: 
1.394     bowersj2 7513: =head1 RETURN MESSAGES
1.191     harris41 7514: 
1.394     bowersj2 7515: =over 4
1.191     harris41 7516: 
1.394     bowersj2 7517: =item * B<con_lost>: unable to contact remote host
1.191     harris41 7518: 
1.394     bowersj2 7519: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   7520: when the connection is brought back up
1.191     harris41 7521: 
1.394     bowersj2 7522: =item * B<con_failed>: unable to contact remote host and unable to save message
                   7523: for later delivery
1.191     harris41 7524: 
1.394     bowersj2 7525: =item * B<error:>: an error a occured, a description of the error follows the :
1.191     harris41 7526: 
1.394     bowersj2 7527: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 7528: that was requested
1.191     harris41 7529: 
1.243     albertel 7530: =back
1.191     harris41 7531: 
1.243     albertel 7532: =head1 PUBLIC SUBROUTINES
1.191     harris41 7533: 
1.243     albertel 7534: =head2 Session Environment Functions
1.191     harris41 7535: 
1.243     albertel 7536: =over 4
1.191     harris41 7537: 
1.394     bowersj2 7538: =item * 
                   7539: X<appenv()>
                   7540: B<appenv(%hash)>: the value of %hash is written to
                   7541: the user envirnoment file, and will be restored for each access this
1.620     albertel 7542: user makes during this session, also modifies the %env for the current
1.394     bowersj2 7543: process
1.191     harris41 7544: 
                   7545: =item *
1.394     bowersj2 7546: X<delenv()>
                   7547: B<delenv($regexp)>: removes all items from the session
                   7548: environment file that matches the regular expression in $regexp. The
1.620     albertel 7549: values are also delted from the current processes %env.
1.191     harris41 7550: 
1.795     albertel 7551: =item * get_env_multiple($name) 
                   7552: 
                   7553: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   7554: values may be defined and end up as an array ref.
                   7555: 
                   7556: returns an array of values
                   7557: 
1.243     albertel 7558: =back
                   7559: 
                   7560: =head2 User Information
1.191     harris41 7561: 
1.243     albertel 7562: =over 4
1.191     harris41 7563: 
                   7564: =item *
1.394     bowersj2 7565: X<queryauthenticate()>
                   7566: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 7567: authentication scheme
                   7568: 
                   7569: =item *
1.394     bowersj2 7570: X<authenticate()>
                   7571: B<authenticate($uname,$upass,$udom)>: try to
                   7572: authenticate user from domain's lib servers (first use the current
                   7573: one). C<$upass> should be the users password.
1.191     harris41 7574: 
                   7575: =item *
1.394     bowersj2 7576: X<homeserver()>
                   7577: B<homeserver($uname,$udom)>: find the server which has
                   7578: the user's directory and files (there must be only one), this caches
                   7579: the answer, and also caches if there is a borken connection.
1.191     harris41 7580: 
                   7581: =item *
1.394     bowersj2 7582: X<idget()>
                   7583: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   7584: (IDs are a unique resource in a domain, there must be only 1 ID per
                   7585: username, and only 1 username per ID in a specific domain) (returns
                   7586: hash: id=>name,id=>name)
1.191     harris41 7587: 
                   7588: =item *
1.394     bowersj2 7589: X<idrget()>
                   7590: B<idrget($udom,@unames)>: find the IDs behind a list of
                   7591: usernames (returns hash: name=>id,name=>id)
1.191     harris41 7592: 
                   7593: =item *
1.394     bowersj2 7594: X<idput()>
                   7595: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 7596: 
                   7597: =item *
1.394     bowersj2 7598: X<rolesinit()>
                   7599: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 7600: 
                   7601: =item *
1.551     albertel 7602: X<getsection()>
                   7603: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 7604: course $cname, return section name/number or '' for "not in course"
                   7605: and '-1' for "no section"
                   7606: 
                   7607: =item *
1.394     bowersj2 7608: X<userenvironment()>
                   7609: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 7610: passed in @what from the requested user's environment, returns a hash
                   7611: 
                   7612: =back
                   7613: 
                   7614: =head2 User Roles
                   7615: 
                   7616: =over 4
                   7617: 
                   7618: =item *
                   7619: 
                   7620: allowed($priv,$uri) : check for a user privilege; returns codes for allowed
                   7621: actions
                   7622:  F: full access
                   7623:  U,I,K: authentication modes (cxx only)
                   7624:  '': forbidden
                   7625:  1: user needs to choose course
                   7626:  2: browse allowed
1.766     albertel 7627:  A: passphrase authentication needed
1.243     albertel 7628: 
                   7629: =item *
                   7630: 
                   7631: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   7632: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   7633: and course level
                   7634: 
                   7635: =item *
                   7636: 
                   7637: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   7638: explanation of a user role term
                   7639: 
                   7640: =back
                   7641: 
                   7642: =head2 User Modification
                   7643: 
                   7644: =over 4
                   7645: 
                   7646: =item *
                   7647: 
                   7648: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
                   7649: user for the level given by URL.  Optional start and end dates (leave empty
                   7650: string or zero for "no date")
1.191     harris41 7651: 
                   7652: =item *
                   7653: 
1.243     albertel 7654: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   7655: change a users, password, possible return values are: ok,
                   7656: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   7657: refused
1.191     harris41 7658: 
                   7659: =item *
                   7660: 
1.243     albertel 7661: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 7662: 
                   7663: =item *
                   7664: 
1.243     albertel 7665: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
                   7666: modify user
1.191     harris41 7667: 
                   7668: =item *
                   7669: 
1.286     matthew  7670: modifystudent
                   7671: 
                   7672: modify a students enrollment and identification information.
                   7673: The course id is resolved based on the current users environment.  
                   7674: This means the envoking user must be a course coordinator or otherwise
                   7675: associated with a course.
                   7676: 
1.297     matthew  7677: This call is essentially a wrapper for lonnet::modifyuser and
                   7678: lonnet::modify_student_enrollment
1.286     matthew  7679: 
                   7680: Inputs: 
                   7681: 
                   7682: =over 4
                   7683: 
                   7684: =item B<$udom> Students loncapa domain
                   7685: 
                   7686: =item B<$uname> Students loncapa login name
                   7687: 
                   7688: =item B<$uid> Students id/student number
                   7689: 
                   7690: =item B<$umode> Students authentication mode
                   7691: 
                   7692: =item B<$upass> Students password
                   7693: 
                   7694: =item B<$first> Students first name
                   7695: 
                   7696: =item B<$middle> Students middle name
                   7697: 
                   7698: =item B<$last> Students last name
                   7699: 
                   7700: =item B<$gene> Students generation
                   7701: 
                   7702: =item B<$usec> Students section in course
                   7703: 
                   7704: =item B<$end> Unix time of the roles expiration
                   7705: 
                   7706: =item B<$start> Unix time of the roles start date
                   7707: 
                   7708: =item B<$forceid> If defined, allow $uid to be changed
                   7709: 
                   7710: =item B<$desiredhome> server to use as home server for student
                   7711: 
                   7712: =back
1.297     matthew  7713: 
                   7714: =item *
                   7715: 
                   7716: modify_student_enrollment
                   7717: 
                   7718: Change a students enrollment status in a class.  The environment variable
                   7719: 'role.request.course' must be defined for this function to proceed.
                   7720: 
                   7721: Inputs:
                   7722: 
                   7723: =over 4
                   7724: 
                   7725: =item $udom, students domain
                   7726: 
                   7727: =item $uname, students name
                   7728: 
                   7729: =item $uid, students user id
                   7730: 
                   7731: =item $first, students first name
                   7732: 
                   7733: =item $middle
                   7734: 
                   7735: =item $last
                   7736: 
                   7737: =item $gene
                   7738: 
                   7739: =item $usec
                   7740: 
                   7741: =item $end
                   7742: 
                   7743: =item $start
                   7744: 
                   7745: =back
                   7746: 
1.191     harris41 7747: 
                   7748: =item *
                   7749: 
1.243     albertel 7750: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   7751: custom role; give a custom role to a user for the level given by URL.  Specify
                   7752: name and domain of role author, and role name
1.191     harris41 7753: 
                   7754: =item *
                   7755: 
1.243     albertel 7756: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 7757: 
                   7758: =item *
                   7759: 
1.243     albertel 7760: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   7761: 
                   7762: =back
                   7763: 
                   7764: =head2 Course Infomation
                   7765: 
                   7766: =over 4
1.191     harris41 7767: 
                   7768: =item *
                   7769: 
1.631     albertel 7770: coursedescription($courseid) : returns a hash of information about the
                   7771: specified course id, including all environment settings for the
                   7772: course, the description of the course will be in the hash under the
                   7773: key 'description'
1.191     harris41 7774: 
                   7775: =item *
                   7776: 
1.624     albertel 7777: resdata($name,$domain,$type,@which) : request for current parameter
                   7778: setting for a specific $type, where $type is either 'course' or 'user',
                   7779: @what should be a list of parameters to ask about. This routine caches
                   7780: answers for 5 minutes.
1.243     albertel 7781: 
                   7782: =back
                   7783: 
                   7784: =head2 Course Modification
                   7785: 
                   7786: =over 4
1.191     harris41 7787: 
                   7788: =item *
                   7789: 
1.243     albertel 7790: writecoursepref($courseid,%prefs) : write preferences (environment
                   7791: database) for a course
1.191     harris41 7792: 
                   7793: =item *
                   7794: 
1.243     albertel 7795: createcourse($udom,$description,$url) : make/modify course
                   7796: 
                   7797: =back
                   7798: 
                   7799: =head2 Resource Subroutines
                   7800: 
                   7801: =over 4
1.191     harris41 7802: 
                   7803: =item *
                   7804: 
1.243     albertel 7805: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 7806: 
                   7807: =item *
                   7808: 
1.243     albertel 7809: repcopy($filename) : subscribes to the requested file, and attempts to
                   7810: replicate from the owning library server, Might return
1.607     raeburn  7811: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   7812: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 7813: resource. Expects the local filesystem pathname
                   7814: (/home/httpd/html/res/....)
                   7815: 
                   7816: =back
                   7817: 
                   7818: =head2 Resource Information
                   7819: 
                   7820: =over 4
1.191     harris41 7821: 
                   7822: =item *
                   7823: 
1.243     albertel 7824: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   7825: a vairety of different possible values, $varname should be a request
                   7826: string, and the other parameters can be used to specify who and what
                   7827: one is asking about.
                   7828: 
                   7829: Possible values for $varname are environment.lastname (or other item
                   7830: from the envirnment hash), user.name (or someother aspect about the
                   7831: user), resource.0.maxtries (or some other part and parameter of a
                   7832: resource)
1.204     albertel 7833: 
                   7834: =item *
                   7835: 
1.243     albertel 7836: directcondval($number) : get current value of a condition; reads from a state
                   7837: string
1.204     albertel 7838: 
                   7839: =item *
                   7840: 
1.243     albertel 7841: condval($condidx) : value of condition index based on state
1.204     albertel 7842: 
                   7843: =item *
                   7844: 
1.243     albertel 7845: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   7846: resource's metadata, $what should be either a specific key, or either
                   7847: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   7848: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   7849: 
                   7850: this function automatically caches all requests
1.191     harris41 7851: 
                   7852: =item *
                   7853: 
1.243     albertel 7854: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   7855: network of library servers; returns file handle of where SQL and regex results
                   7856: will be stored for query
1.191     harris41 7857: 
                   7858: =item *
                   7859: 
1.243     albertel 7860: symbread($filename) : return symbolic list entry (filename argument optional);
                   7861: returns the data handle
1.191     harris41 7862: 
                   7863: =item *
                   7864: 
1.243     albertel 7865: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 7866: a possible symb for the URL in $thisfn, and if is an encryypted
                   7867: resource that the user accessed using /enc/ returns a 1 on success, 0
                   7868: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 7869: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 7870: 
1.191     harris41 7871: 
                   7872: =item *
                   7873: 
1.243     albertel 7874: symbclean($symb) : removes versions numbers from a symb, returns the
                   7875: cleaned symb
1.191     harris41 7876: 
                   7877: =item *
                   7878: 
1.243     albertel 7879: is_on_map($uri) : checks if the $uri is somewhere on the current
                   7880: course map, user must be in a course for it to work.
1.191     harris41 7881: 
                   7882: =item *
                   7883: 
1.243     albertel 7884: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 7885: 
                   7886: =item *
                   7887: 
1.243     albertel 7888: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   7889: a random seed, all arguments are optional, if they aren't sent it uses the
                   7890: environment to derive them. Note: if symb isn't sent and it can't get one
                   7891: from &symbread it will use the current time as its return value
1.191     harris41 7892: 
                   7893: =item *
                   7894: 
1.243     albertel 7895: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   7896: unfakeable, receipt
1.191     harris41 7897: 
                   7898: =item *
                   7899: 
1.620     albertel 7900: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 7901: 
                   7902: =item *
                   7903: 
1.243     albertel 7904: countacc($url) : count the number of accesses to a given URL
1.191     harris41 7905: 
                   7906: =item *
                   7907: 
1.243     albertel 7908: 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 7909: 
                   7910: =item *
                   7911: 
1.243     albertel 7912: 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 7913: 
                   7914: =item *
                   7915: 
1.243     albertel 7916: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 7917: 
                   7918: =item *
                   7919: 
1.243     albertel 7920: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   7921: forcing spreadsheet to reevaluate the resource scores next time.
                   7922: 
                   7923: =back
                   7924: 
                   7925: =head2 Storing/Retreiving Data
                   7926: 
                   7927: =over 4
1.191     harris41 7928: 
                   7929: =item *
                   7930: 
1.243     albertel 7931: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   7932: for this url; hashref needs to be given and should be a \%hashname; the
                   7933: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 7934: be derived from the env
1.191     harris41 7935: 
                   7936: =item *
                   7937: 
1.243     albertel 7938: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   7939: uses critical subroutine
1.191     harris41 7940: 
                   7941: =item *
                   7942: 
1.243     albertel 7943: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   7944: all args are optional
1.191     harris41 7945: 
                   7946: =item *
                   7947: 
1.717     albertel 7948: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   7949: dumps the complete (or key matching regexp) namespace into a hash
                   7950: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   7951: normally &store()ed into
                   7952: 
                   7953: $range should be either an integer '100' (give me the first 100
                   7954:                                            matching records)
                   7955:               or be  two integers sperated by a - with no spaces
                   7956:                  '30-50' (give me the 30th through the 50th matching
                   7957:                           records)
                   7958: 
                   7959: 
                   7960: =item *
                   7961: 
                   7962: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   7963: replaces a &store() version of data with a replacement set of data
                   7964: for a particular resource in a namespace passed in the $storehash hash 
                   7965: reference
                   7966: 
                   7967: =item *
                   7968: 
1.243     albertel 7969: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   7970: works very similar to store/cstore, but all data is stored in a
                   7971: temporary location and can be reset using tmpreset, $storehash should
                   7972: be a hash reference, returns nothing on success
1.191     harris41 7973: 
                   7974: =item *
                   7975: 
1.243     albertel 7976: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   7977: similar to restore, but all data is stored in a temporary location and
                   7978: can be reset using tmpreset. Returns a hash of values on success,
                   7979: error string otherwise.
1.191     harris41 7980: 
                   7981: =item *
                   7982: 
1.243     albertel 7983: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   7984: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 7985: 
                   7986: =item *
                   7987: 
1.243     albertel 7988: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   7989: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 7990: 
                   7991: =item *
                   7992: 
1.243     albertel 7993: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   7994: namesp ($udom and $uname are optional)
1.191     harris41 7995: 
                   7996: =item *
                   7997: 
1.702     albertel 7998: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 7999: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 8000: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  8001: 
1.702     albertel 8002: $range should be either an integer '100' (give me the first 100
                   8003:                                            matching records)
                   8004:               or be  two integers sperated by a - with no spaces
                   8005:                  '30-50' (give me the 30th through the 50th matching
                   8006:                           records)
1.449     matthew  8007: =item *
                   8008: 
                   8009: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   8010: $store can be a scalar, an array reference, or if the amount to be 
                   8011: incremented is > 1, a hash reference.
                   8012: 
                   8013: ($udom and $uname are optional)
1.191     harris41 8014: 
                   8015: =item *
                   8016: 
1.243     albertel 8017: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   8018: ($udom and $uname are optional)
1.191     harris41 8019: 
                   8020: =item *
                   8021: 
1.243     albertel 8022: cput($namespace,$storehash,$udom,$uname) : critical put
                   8023: ($udom and $uname are optional)
1.191     harris41 8024: 
                   8025: =item *
                   8026: 
1.748     albertel 8027: newput($namespace,$storehash,$udom,$uname) :
                   8028: 
                   8029: Attempts to store the items in the $storehash, but only if they don't
                   8030: currently exist, if this succeeds you can be certain that you have 
                   8031: successfully created a new key value pair in the $namespace db.
                   8032: 
                   8033: 
                   8034: Args:
                   8035:  $namespace: name of database to store values to
                   8036:  $storehash: hashref to store to the db
                   8037:  $udom: (optional) domain of user containing the db
                   8038:  $uname: (optional) name of user caontaining the db
                   8039: 
                   8040: Returns:
                   8041:  'ok' -> succeeded in storing all keys of $storehash
                   8042:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   8043:                         least <key> already existed in the db (other
                   8044:                         requested keys may also already exist)
                   8045:  'error: <msg>' -> unable to tie the DB or other erorr occured
                   8046:  'con_lost' -> unable to contact request server
                   8047:  'refused' -> action was not allowed by remote machine
                   8048: 
                   8049: 
                   8050: =item *
                   8051: 
1.243     albertel 8052: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   8053: reference filled in from namesp (encrypts the return communication)
                   8054: ($udom and $uname are optional)
1.191     harris41 8055: 
                   8056: =item *
                   8057: 
1.243     albertel 8058: log($udom,$name,$home,$message) : write to permanent log for user; use
                   8059: critical subroutine
                   8060: 
                   8061: =back
                   8062: 
                   8063: =head2 Network Status Functions
                   8064: 
                   8065: =over 4
1.191     harris41 8066: 
                   8067: =item *
                   8068: 
                   8069: dirlist($uri) : return directory list based on URI
                   8070: 
                   8071: =item *
                   8072: 
1.243     albertel 8073: spareserver() : find server with least workload from spare.tab
                   8074: 
                   8075: =back
                   8076: 
                   8077: =head2 Apache Request
                   8078: 
                   8079: =over 4
1.191     harris41 8080: 
                   8081: =item *
                   8082: 
1.243     albertel 8083: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   8084: localhost, posts hash
                   8085: 
                   8086: =back
                   8087: 
                   8088: =head2 Data to String to Data
                   8089: 
                   8090: =over 4
1.191     harris41 8091: 
                   8092: =item *
                   8093: 
1.243     albertel 8094: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   8095: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 8096: 
                   8097: =item *
                   8098: 
1.243     albertel 8099: hashref2str($hashref) : convert a hashref into a string complete with
                   8100: escaping and '=' and '&' separators, supports elements that are
                   8101: arrayrefs and hashrefs
1.191     harris41 8102: 
                   8103: =item *
                   8104: 
1.243     albertel 8105: arrayref2str($arrayref) : convert an arrayref into a string complete
                   8106: with escaping and '&' separators, supports elements that are arrayrefs
                   8107: and hashrefs
1.191     harris41 8108: 
                   8109: =item *
                   8110: 
1.243     albertel 8111: str2hash($string) : convert string to hash using unescaping and
                   8112: splitting on '=' and '&', supports elements that are arrayrefs and
                   8113: hashrefs
1.191     harris41 8114: 
                   8115: =item *
                   8116: 
1.243     albertel 8117: str2array($string) : convert string to hash using unescaping and
                   8118: splitting on '&', supports elements that are arrayrefs and hashrefs
                   8119: 
                   8120: =back
                   8121: 
                   8122: =head2 Logging Routines
                   8123: 
                   8124: =over 4
                   8125: 
                   8126: These routines allow one to make log messages in the lonnet.log and
                   8127: lonnet.perm logfiles.
1.191     harris41 8128: 
                   8129: =item *
                   8130: 
1.243     albertel 8131: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 8132: 
                   8133: =item *
                   8134: 
1.243     albertel 8135: logthis() : append message to the normal lonnet.log file, it gets
                   8136: preiodically rolled over and deleted.
1.191     harris41 8137: 
                   8138: =item *
                   8139: 
1.243     albertel 8140: logperm() : append a permanent message to lonnet.perm.log, this log
                   8141: file never gets deleted by any automated portion of the system, only
                   8142: messages of critical importance should go in here.
                   8143: 
                   8144: =back
                   8145: 
                   8146: =head2 General File Helper Routines
                   8147: 
                   8148: =over 4
1.191     harris41 8149: 
                   8150: =item *
                   8151: 
1.481     raeburn  8152: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   8153: (a) files in /uploaded
                   8154:   (i) If a local copy of the file exists - 
                   8155:       compares modification date of local copy with last-modified date for 
                   8156:       definitive version stored on home server for course. If local copy is 
                   8157:       stale, requests a new version from the home server and stores it. 
                   8158:       If the original has been removed from the home server, then local copy 
                   8159:       is unlinked.
                   8160:   (ii) If local copy does not exist -
                   8161:       requests the file from the home server and stores it. 
                   8162:   
                   8163:   If $caller is 'uploadrep':  
                   8164:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   8165:     for request for files originally uploaded via DOCS. 
                   8166:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   8167:   
                   8168:   Otherwise:
                   8169:      This indicates a call from the content generation phase of the request.
                   8170:      -  returns the entire contents of the file or -1.
                   8171:      
                   8172: (b) files in /res
                   8173:    - returns the entire contents of a file or -1; 
                   8174:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 8175: 
1.712     albertel 8176: 
                   8177: =item *
                   8178: 
                   8179: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   8180:                   reference
                   8181: 
                   8182: returns either a stat() list of data about the file or an empty list
                   8183: if the file doesn't exist or couldn't find out about it (connection
                   8184: problems or user unknown)
                   8185: 
1.191     harris41 8186: =item *
                   8187: 
1.243     albertel 8188: filelocation($dir,$file) : returns file system location of a file
                   8189: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   8190: directory that relative $file lookups are to looked in ($dir of /a/dir
                   8191: and a file of ../bob will become /a/bob)
1.191     harris41 8192: 
                   8193: =item *
                   8194: 
                   8195: hreflocation($dir,$file) : returns file system location or a URL; same as
                   8196: filelocation except for hrefs
                   8197: 
                   8198: =item *
                   8199: 
                   8200: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   8201: 
1.243     albertel 8202: =back
                   8203: 
1.608     albertel 8204: =head2 Usererfile file routines (/uploaded*)
                   8205: 
                   8206: =over 4
                   8207: 
                   8208: =item *
                   8209: 
                   8210: userfileupload(): main rotine for putting a file in a user or course's
                   8211:                   filespace, arguments are,
                   8212: 
1.620     albertel 8213:  formname - required - this is the name of the element in $env where the
1.608     albertel 8214:            filename, and the contents of the file to create/modifed exist
1.620     albertel 8215:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   8216:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 8217:  coursedoc - if true, store the file in the course of the active role
                   8218:              of the current user
                   8219:  subdir - required - subdirectory to put the file in under ../userfiles/
                   8220:          if undefined, it will be placed in "unknown"
                   8221: 
                   8222:  (This routine calls clean_filename() to remove any dangerous
                   8223:  characters from the filename, and then calls finuserfileupload() to
                   8224:  complete the transaction)
                   8225: 
                   8226:  returns either the url of the uploaded file (/uploaded/....) if successful
                   8227:  and /adm/notfound.html if unsuccessful
                   8228: 
                   8229: =item *
                   8230: 
                   8231: clean_filename(): routine for cleaing a filename up for storage in
                   8232:                  userfile space, argument is:
                   8233: 
                   8234:  filename - proposed filename
                   8235: 
                   8236: returns: the new clean filename
                   8237: 
                   8238: =item *
                   8239: 
                   8240: finishuserfileupload(): routine that creaes and sends the file to
                   8241: userspace, probably shouldn't be called directly
                   8242: 
                   8243:   docuname: username or courseid of destination for the file
                   8244:   docudom: domain of user/course of destination for the file
                   8245:   formname: same as for userfileupload()
                   8246:   fname: filename (inculding subdirectories) for the file
                   8247: 
                   8248:  returns either the url of the uploaded file (/uploaded/....) if successful
                   8249:  and /adm/notfound.html if unsuccessful
                   8250: 
                   8251: =item *
                   8252: 
                   8253: renameuserfile(): renames an existing userfile to a new name
                   8254: 
                   8255:   Args:
                   8256:    docuname: username or courseid of destination for the file
                   8257:    docudom: domain of user/course of destination for the file
                   8258:    old: current file name (including any subdirs under userfiles)
                   8259:    new: desired file name (including any subdirs under userfiles)
                   8260: 
                   8261: =item *
                   8262: 
                   8263: mkdiruserfile(): creates a directory is a userfiles dir
                   8264: 
                   8265:   Args:
                   8266:    docuname: username or courseid of destination for the file
                   8267:    docudom: domain of user/course of destination for the file
                   8268:    dir: dir to create (including any subdirs under userfiles)
                   8269: 
                   8270: =item *
                   8271: 
                   8272: removeuserfile(): removes a file that exists in userfiles
                   8273: 
                   8274:   Args:
                   8275:    docuname: username or courseid of destination for the file
                   8276:    docudom: domain of user/course of destination for the file
                   8277:    fname: filname to delete (including any subdirs under userfiles)
                   8278: 
                   8279: =item *
                   8280: 
                   8281: removeuploadedurl(): convience function for removeuserfile()
                   8282: 
                   8283:   Args:
                   8284:    url:  a full /uploaded/... url to delete
                   8285: 
1.747     albertel 8286: =item * 
                   8287: 
                   8288: get_portfile_permissions():
                   8289:   Args:
                   8290:     domain: domain of user or course contain the portfolio files
                   8291:     user: name of user or num of course contain the portfolio files
                   8292:   Returns:
                   8293:     hashref of a dump of the proper file_permissions.db
                   8294:    
                   8295: 
                   8296: =item * 
                   8297: 
                   8298: get_access_controls():
                   8299: 
                   8300: Args:
                   8301:   current_permissions: the hash ref returned from get_portfile_permissions()
                   8302:   group: (optional) the group you want the files associated with
                   8303:   file: (optional) the file you want access info on
                   8304: 
                   8305: Returns:
1.749     raeburn  8306:     a hash (keys are file names) of hashes containing
                   8307:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   8308:         values are XML containing access control settings (see below) 
1.747     albertel 8309: 
                   8310: Internal notes:
                   8311: 
1.749     raeburn  8312:  access controls are stored in file_permissions.db as key=value pairs.
                   8313:     key -> path to file/file_name\0uniqueID:scope_end_start
                   8314:         where scope -> public,guest,course,group,domains or users.
                   8315:               end -> UNIX time for end of access (0 -> no end date)
                   8316:               start -> UNIX time for start of access
                   8317: 
                   8318:     value -> XML description of access control
                   8319:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   8320:             <start></start>
                   8321:             <end></end>
                   8322: 
                   8323:             <password></password>  for scope type = guest
                   8324: 
                   8325:             <domain></domain>     for scope type = course or group
                   8326:             <number></number>
                   8327:             <roles id="">
                   8328:              <role></role>
                   8329:              <access></access>
                   8330:              <section></section>
                   8331:              <group></group>
                   8332:             </roles>
                   8333: 
                   8334:             <dom></dom>         for scope type = domains
                   8335: 
                   8336:             <users>             for scope type = users
                   8337:              <user>
                   8338:               <uname></uname>
                   8339:               <udom></udom>
                   8340:              </user>
                   8341:             </users>
                   8342:            </scope> 
                   8343:               
                   8344:  Access data is also aggregated for each file in an additional key=value pair:
                   8345:  key -> path to file/file_name\0accesscontrol 
                   8346:  value -> reference to hash
                   8347:           hash contains key = value pairs
                   8348:           where key = uniqueID:scope_end_start
                   8349:                 value = UNIX time record was last updated
                   8350: 
                   8351:           Used to improve speed of look-ups of access controls for each file.  
                   8352:  
                   8353:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   8354: 
                   8355: modify_access_controls():
                   8356: 
                   8357: Modifies access controls for a portfolio file
                   8358: Args
                   8359: 1. file name
                   8360: 2. reference to hash of required changes,
                   8361: 3. domain
                   8362: 4. username
                   8363:   where domain,username are the domain of the portfolio owner 
                   8364:   (either a user or a course) 
                   8365: 
                   8366: Returns:
                   8367: 1. result of additions or updates ('ok' or 'error', with error message). 
                   8368: 2. result of deletions ('ok' or 'error', with error message).
                   8369: 3. reference to hash of any new or updated access controls.
                   8370: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   8371:    key = integer (inbound ID)
                   8372:    value = uniqueID  
1.747     albertel 8373: 
1.608     albertel 8374: =back
                   8375: 
1.243     albertel 8376: =head2 HTTP Helper Routines
                   8377: 
                   8378: =over 4
                   8379: 
1.191     harris41 8380: =item *
                   8381: 
                   8382: escape() : unpack non-word characters into CGI-compatible hex codes
                   8383: 
                   8384: =item *
                   8385: 
                   8386: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   8387: 
1.243     albertel 8388: =back
                   8389: 
                   8390: =head1 PRIVATE SUBROUTINES
                   8391: 
                   8392: =head2 Underlying communication routines (Shouldn't call)
                   8393: 
                   8394: =over 4
                   8395: 
                   8396: =item *
                   8397: 
                   8398: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   8399: 
                   8400: =item *
                   8401: 
                   8402: reply() : uses subreply to send a message to remote machine, logs all failures
                   8403: 
                   8404: =item *
                   8405: 
                   8406: critical() : passes a critical message to another server; if cannot
                   8407: get through then place message in connection buffer directory and
                   8408: returns con_delayed, if incapable of saving message, returns
                   8409: con_failed
                   8410: 
                   8411: =item *
                   8412: 
                   8413: reconlonc() : tries to reconnect lonc client processes.
                   8414: 
                   8415: =back
                   8416: 
                   8417: =head2 Resource Access Logging
                   8418: 
                   8419: =over 4
                   8420: 
                   8421: =item *
                   8422: 
                   8423: flushcourselogs() : flush (save) buffer logs and access logs
                   8424: 
                   8425: =item *
                   8426: 
                   8427: courselog($what) : save message for course in hash
                   8428: 
                   8429: =item *
                   8430: 
                   8431: courseacclog($what) : save message for course using &courselog().  Perform
                   8432: special processing for specific resource types (problems, exams, quizzes, etc).
                   8433: 
1.191     harris41 8434: =item *
                   8435: 
                   8436: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   8437: as a PerlChildExitHandler
1.243     albertel 8438: 
                   8439: =back
                   8440: 
                   8441: =head2 Other
                   8442: 
                   8443: =over 4
                   8444: 
                   8445: =item *
                   8446: 
                   8447: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 8448: 
                   8449: =back
                   8450: 
                   8451: =cut

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