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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.796   ! raeburn     4: # $Id: lonnet.pm,v 1.795 2006/10/17 15:15:51 albertel Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.1       albertel   30: package Apache::lonnet;
                     31: 
                     32: use strict;
1.8       www        33: use LWP::UserAgent();
1.15      www        34: use HTTP::Headers;
1.486     www        35: use HTTP::Date;
                     36: # use Date::Parse;
1.11      www        37: use vars 
1.599     albertel   38: qw(%perlvar %hostname %badServerCache %iphost %spareid %hostdom 
                     39:    %libserv %pr %prp $memcache %packagetab 
1.662     raeburn    40:    %courselogs %accesshash %userrolehash %domainrolehash $processmarker $dumpcount 
1.741     raeburn    41:    %coursedombuf %coursenumbuf %coursehombuf %coursedescrbuf %courseinstcodebuf %courseownerbuf %coursetypebuf
1.599     albertel   42:    %domaindescription %domain_auth_def %domain_auth_arg_def 
1.685     raeburn    43:    %domain_lang_def %domain_city %domain_longi %domain_lati %domain_primary
                     44:    $tmpdir $_64bit %env);
1.403     www        45: 
1.1       albertel   46: use IO::Socket;
1.31      www        47: use GDBM_File;
1.208     albertel   48: use HTML::LCParser;
1.637     raeburn    49: use HTML::Parser;
1.88      www        50: use Fcntl qw(:flock);
1.557     albertel   51: use Storable qw(lock_store lock_nstore lock_retrieve freeze thaw nfreeze);
1.539     albertel   52: use Time::HiRes qw( gettimeofday tv_interval );
1.599     albertel   53: use Cache::Memcached;
1.676     albertel   54: use Digest::MD5;
1.790     albertel   55: use Math::Random;
1.740     www        56: use lib '/home/httpd/lib/perl';
                     57: use LONCAPA;
                     58: use LONCAPA::Configuration;
1.676     albertel   59: 
1.195     www        60: my $readit;
1.550     foxr       61: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel   62: 
1.619     albertel   63: require Exporter;
                     64: 
                     65: our @ISA = qw (Exporter);
                     66: our @EXPORT = qw(%env);
                     67: 
1.449     matthew    68: =pod
                     69: 
                     70: =head1 Package Variables
                     71: 
                     72: These are largely undocumented, so if you decipher one please note it here.
                     73: 
                     74: =over 4
                     75: 
                     76: =item $processmarker
                     77: 
                     78: Contains the time this process was started and this servers host id.
                     79: 
                     80: =item $dumpcount
                     81: 
                     82: Counts the number of times a message log flush has been attempted (regardless
                     83: of success) by this process.  Used as part of the filename when messages are
                     84: delayed.
                     85: 
                     86: =back
                     87: 
                     88: =cut
                     89: 
                     90: 
1.1       albertel   91: # --------------------------------------------------------------------- Logging
1.729     www        92: {
                     93:     my $logid;
                     94:     sub instructor_log {
                     95: 	my ($hash_name,$storehash,$delflag,$uname,$udom)=@_;
                     96: 	$logid++;
                     97: 	my $id=time().'00000'.$$.'00000'.$logid;
                     98: 	return &Apache::lonnet::put('nohist_'.$hash_name,
1.730     www        99: 				    { $id => {
                    100: 					'exe_uname' => $env{'user.name'},
                    101: 					'exe_udom'  => $env{'user.domain'},
                    102: 					'exe_time'  => time(),
                    103: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    104: 					'delflag'   => $delflag,
                    105: 					'logentry'  => $storehash,
                    106: 					'uname'     => $uname,
                    107: 					'udom'      => $udom,
                    108: 				    }
                    109: 				  },
1.729     www       110: 				    $env{'course.'.$env{'request.course.id'}.'.domain'},
                    111: 				    $env{'course.'.$env{'request.course.id'}.'.num'}
                    112: 				    );
                    113:     }
                    114: }
1.1       albertel  115: 
1.163     harris41  116: sub logtouch {
                    117:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  118:     unless (-e "$execdir/logs/lonnet.log") {	
                    119: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  120: 	close $fh;
                    121:     }
                    122:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    123:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    124: }
                    125: 
1.1       albertel  126: sub logthis {
                    127:     my $message=shift;
                    128:     my $execdir=$perlvar{'lonDaemons'};
                    129:     my $now=time;
                    130:     my $local=localtime($now);
1.448     albertel  131:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
                    132: 	print $fh "$local ($$): $message\n";
                    133: 	close($fh);
                    134:     }
1.1       albertel  135:     return 1;
                    136: }
                    137: 
                    138: sub logperm {
                    139:     my $message=shift;
                    140:     my $execdir=$perlvar{'lonDaemons'};
                    141:     my $now=time;
                    142:     my $local=localtime($now);
1.448     albertel  143:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    144: 	print $fh "$now:$message:$local\n";
                    145: 	close($fh);
                    146:     }
1.1       albertel  147:     return 1;
                    148: }
                    149: 
                    150: # -------------------------------------------------- Non-critical communication
                    151: sub subreply {
                    152:     my ($cmd,$server)=@_;
1.704     albertel  153:     my $peerfile="$perlvar{'lonSockDir'}/".$hostname{$server};
1.549     foxr      154:     #
                    155:     #  With loncnew process trimming, there's a timing hole between lonc server
                    156:     #  process exit and the master server picking up the listen on the AF_UNIX
                    157:     #  socket.  In that time interval, a lock file will exist:
                    158: 
                    159:     my $lockfile=$peerfile.".lock";
                    160:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    161: 	sleep(1);
                    162:     }
                    163:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      164:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      165:     #
1.550     foxr      166:     #   We'll give the connection a few tries before abandoning it.  If
                    167:     #   connection is not possible, we'll con_lost back to the client.
                    168:     #   
                    169:     my $client;
                    170:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    171: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    172: 				      Type    => SOCK_STREAM,
                    173: 				      Timeout => 10);
                    174: 	if($client) {
                    175: 	    last;		# Connected!
                    176: 	}
                    177: 	sleep(1);		# Try again later if failed connection.
                    178:     }
                    179:     my $answer;
                    180:     if ($client) {
1.704     albertel  181: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      182: 	$answer=<$client>;
                    183: 	if (!$answer) { $answer="con_lost"; }
                    184: 	chomp($answer);
                    185:     } else {
                    186: 	$answer = 'con_lost';	# Failed connection.
                    187:     }
1.1       albertel  188:     return $answer;
                    189: }
                    190: 
                    191: sub reply {
                    192:     my ($cmd,$server)=@_;
1.205     www       193:     unless (defined($hostname{$server})) { return 'no_such_host'; }
1.1       albertel  194:     my $answer=subreply($cmd,$server);
1.65      www       195:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  196:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       197:                 " $cmd to $server returned $answer</font>");
                    198:     }
1.1       albertel  199:     return $answer;
                    200: }
                    201: 
                    202: # ----------------------------------------------------------- Send USR1 to lonc
                    203: 
                    204: sub reconlonc {
                    205:     my $peerfile=shift;
                    206:     &logthis("Trying to reconnect for $peerfile");
                    207:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  208:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  209: 	my $loncpid=<$fh>;
                    210:         chomp($loncpid);
                    211:         if (kill 0 => $loncpid) {
                    212: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    213:             kill USR1 => $loncpid;
                    214:             sleep 1;
                    215:             if (-e "$peerfile") { return; }
                    216:             &logthis("$peerfile still not there, give it another try");
                    217:             sleep 5;
                    218:             if (-e "$peerfile") { return; }
1.12      www       219:             &logthis(
1.672     albertel  220:   "<font color=\"blue\">WARNING: $peerfile still not there, giving up</font>");
1.1       albertel  221:         } else {
1.12      www       222: 	    &logthis(
1.672     albertel  223:                "<font color=\"blue\">WARNING:".
1.12      www       224:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  225:         }
                    226:     } else {
1.672     albertel  227:      &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  228:     }
                    229: }
                    230: 
                    231: # ------------------------------------------------------ Critical communication
1.12      www       232: 
1.1       albertel  233: sub critical {
                    234:     my ($cmd,$server)=@_;
1.89      www       235:     unless ($hostname{$server}) {
1.672     albertel  236:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       237:                " Critical message to unknown server ($server)</font>");
                    238:         return 'no_such_host';
                    239:     }
1.1       albertel  240:     my $answer=reply($cmd,$server);
                    241:     if ($answer eq 'con_lost') {
                    242: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  243: 	my $answer=reply($cmd,$server);
1.1       albertel  244:         if ($answer eq 'con_lost') {
                    245:             my $now=time;
                    246:             my $middlename=$cmd;
1.5       www       247:             $middlename=substr($middlename,0,16);
1.1       albertel  248:             $middlename=~s/\W//g;
                    249:             my $dfilename=
1.305     www       250:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    251:             $dumpcount++;
1.1       albertel  252:             {
1.448     albertel  253: 		my $dfh;
                    254: 		if (open($dfh,">$dfilename")) {
                    255: 		    print $dfh "$cmd\n"; 
                    256: 		    close($dfh);
                    257: 		}
1.1       albertel  258:             }
                    259:             sleep 2;
                    260:             my $wcmd='';
                    261:             {
1.448     albertel  262: 		my $dfh;
                    263: 		if (open($dfh,"<$dfilename")) {
                    264: 		    $wcmd=<$dfh>; 
                    265: 		    close($dfh);
                    266: 		}
1.1       albertel  267:             }
                    268:             chomp($wcmd);
1.7       www       269:             if ($wcmd eq $cmd) {
1.672     albertel  270: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       271:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  272:                 &logperm("D:$server:$cmd");
                    273: 	        return 'con_delayed';
                    274:             } else {
1.672     albertel  275:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       276:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  277:                 &logperm("F:$server:$cmd");
                    278:                 return 'con_failed';
                    279:             }
                    280:         }
                    281:     }
                    282:     return $answer;
1.405     albertel  283: }
                    284: 
1.755     albertel  285: # ------------------------------------------- check if return value is an error
                    286: 
                    287: sub error {
                    288:     my ($result) = @_;
1.756     albertel  289:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  290: 	if ($2 == 2) { return undef; }
                    291: 	return $1;
                    292:     }
                    293:     return undef;
                    294: }
                    295: 
1.783     albertel  296: sub convert_and_load_session_env {
                    297:     my ($lonidsdir,$handle)=@_;
                    298:     my @profile;
                    299:     {
                    300: 	open(my $idf,"$lonidsdir/$handle.id");
                    301: 	flock($idf,LOCK_SH);
                    302: 	@profile=<$idf>;
                    303: 	close($idf);
                    304:     }
                    305:     my %temp_env;
                    306:     foreach my $line (@profile) {
1.786     albertel  307: 	if ($line !~ m/=/) {
                    308: 	    return 0;
                    309: 	}
1.783     albertel  310: 	chomp($line);
                    311: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    312: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    313:     }
                    314:     unlink("$lonidsdir/$handle.id");
                    315:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    316: 	    0640)) {
                    317: 	%disk_env = %temp_env;
                    318: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    319: 	untie(%disk_env);
                    320:     }
1.786     albertel  321:     return 1;
1.783     albertel  322: }
                    323: 
1.374     www       324: # ------------------------------------------- Transfer profile into environment
1.780     albertel  325: my $env_loaded;
                    326: sub transfer_profile_to_env {
1.788     albertel  327:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    328:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       329: 
1.720     albertel  330:     if (!defined($lonidsdir)) {
                    331: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    332:     }
                    333:     if (!defined($handle)) {
                    334:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    335:     }
                    336: 
1.786     albertel  337:     my $convert;
                    338:     {
                    339:     	open(my $idf,"$lonidsdir/$handle.id");
                    340: 	flock($idf,LOCK_SH);
                    341: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    342: 		&GDBM_READER(),0640)) {
                    343: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    344: 	    untie(%disk_env);
                    345: 	} else {
                    346: 	    $convert = 1;
                    347: 	}
                    348:     }
                    349:     if ($convert) {
                    350: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    351: 	    &logthis("Failed to load session, or convert session.");
                    352: 	}
1.374     www       353:     }
1.783     albertel  354: 
1.786     albertel  355:     my %remove;
1.783     albertel  356:     while ( my $envname = each(%env) ) {
1.433     matthew   357:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    358:             if ($time < time-300) {
1.783     albertel  359:                 $remove{$key}++;
1.433     matthew   360:             }
                    361:         }
                    362:     }
1.783     albertel  363: 
1.619     albertel  364:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  365:     $env_loaded=1;
1.783     albertel  366:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   367:         &delenv($expired_key);
1.374     www       368:     }
1.1       albertel  369: }
                    370: 
1.5       www       371: # ---------------------------------------------------------- Append Environment
                    372: 
                    373: sub appenv {
1.6       www       374:     my %newenv=@_;
1.692     albertel  375:     foreach my $key (keys(%newenv)) {
                    376: 	if (($newenv{$key}=~/^user\.role/) || ($newenv{$key}=~/^user\.priv/)) {
1.672     albertel  377:             &logthis("<font color=\"blue\">WARNING: ".
1.692     albertel  378:                 "Attempt to modify environment ".$key." to ".$newenv{$key}
1.151     www       379:                 .'</font>');
1.692     albertel  380: 	    delete($newenv{$key});
1.35      www       381:         } else {
1.692     albertel  382:             $env{$key}=$newenv{$key};
1.35      www       383:         }
1.191     harris41  384:     }
1.783     albertel  385:     if (tie(my %disk_env,'GDBM_File',$env{'user.environment'},&GDBM_WRITER(),
                    386: 	    0640)) {
                    387: 	while (my ($key,$value) = each(%newenv)) {
                    388: 	    $disk_env{$key} = $value;
1.448     albertel  389: 	}
1.783     albertel  390: 	untie(%disk_env);
1.56      www       391:     }
                    392:     return 'ok';
                    393: }
                    394: # ----------------------------------------------------- Delete from Environment
                    395: 
                    396: sub delenv {
                    397:     my $delthis=shift;
                    398:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672     albertel  399:         &logthis("<font color=\"blue\">WARNING: ".
1.56      www       400:                 "Attempt to delete from environment ".$delthis);
                    401:         return 'error';
                    402:     }
1.783     albertel  403:     if (tie(my %disk_env,'GDBM_File',$env{'user.environment'},&GDBM_WRITER(),
                    404: 	    0640)) {
                    405: 	foreach my $key (keys(%disk_env)) {
                    406: 	    if ($key=~/^$delthis/) { 
1.619     albertel  407:                 delete($env{$key});
1.783     albertel  408:                 delete($disk_env{$key});
1.473     matthew   409:             }
1.448     albertel  410: 	}
1.783     albertel  411: 	untie(%disk_env);
1.5       www       412:     }
                    413:     return 'ok';
1.369     albertel  414: }
                    415: 
1.790     albertel  416: 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();
                   5029:                 $newkey =~ s/^(\d+)/$newid/;
                   5030:                 $translation{$1} = $newid;
                   5031:                 $new_values{$file_name."\0".$newkey} = 
                   5032:                                           $$changes{'activate'}{$newitems[$i]};
                   5033:                 $new_control{$newkey} = $now;
                   5034:             }
                   5035:         }
                   5036:     }
                   5037:     my %todelete;
                   5038:     my %changed_items;
                   5039:     foreach my $action ('delete','update') {
                   5040:         if (exists($$changes{$action})) {
                   5041:             if (ref($$changes{$action}) eq 'HASH') {
                   5042:                 foreach my $key (keys(%{$$changes{$action}})) {
                   5043:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   5044:                     if ($action eq 'delete') { 
                   5045:                         $todelete{$itemnum} = 1;
                   5046:                     } else {
                   5047:                         $changed_items{$itemnum} = $key;
                   5048:                     }
                   5049:                 }
1.745     raeburn  5050:             }
                   5051:         }
1.749     raeburn  5052:     }
                   5053:     # get lock on access controls for file.
                   5054:     my $lockhash = {
                   5055:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   5056:                                                        ':'.$env{'user.domain'},
                   5057:                    }; 
                   5058:     my $tries = 0;
                   5059:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5060:    
                   5061:     while (($gotlock ne 'ok') && $tries <3) {
                   5062:         $tries ++;
                   5063:         sleep 1;
                   5064:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5065:     }
                   5066:     if ($gotlock eq 'ok') {
                   5067:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   5068:         my ($tmp)=keys(%curr_permissions);
                   5069:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   5070:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   5071:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   5072:             if (ref($curr_controls) eq 'HASH') {
                   5073:                 foreach my $control_item (keys(%{$curr_controls})) {
                   5074:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   5075:                     if (defined($todelete{$itemnum})) {
                   5076:                         push(@deletions,$file_name."\0".$control_item);
                   5077:                     } else {
                   5078:                         if (defined($changed_items{$itemnum})) {
                   5079:                             $new_control{$changed_items{$itemnum}} = $now;
                   5080:                             push(@deletions,$file_name."\0".$control_item);
                   5081:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   5082:                         } else {
                   5083:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   5084:                         }
                   5085:                     }
1.745     raeburn  5086:                 }
                   5087:             }
                   5088:         }
1.749     raeburn  5089:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   5090:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   5091:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   5092:         #  remove lock
                   5093:         my @del_lock = ($file_name."\0".'locked_access_records');
                   5094:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
                   5095:     } else {
                   5096:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  5097:     }
1.749     raeburn  5098:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  5099: }
                   5100: 
                   5101: #------------------------------------------------------Get Marked as Read Only
                   5102: 
                   5103: sub get_marked_as_readonly {
                   5104:     my ($domain,$user,$what,$group) = @_;
                   5105:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 5106:     my @readonly_files;
1.629     banghart 5107:     my $cmp1=$what;
                   5108:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  5109:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5110:         if (defined($group)) {
                   5111:             if ($file_name !~ m-^\Q$group\E/-) {
                   5112:                 next;
                   5113:             }
                   5114:         }
1.561     banghart 5115:         if (ref($value) eq "ARRAY"){
                   5116:             foreach my $stored_what (@{$value}) {
1.629     banghart 5117:                 my $cmp2=$stored_what;
1.759     albertel 5118:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  5119:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  5120:                 }
1.629     banghart 5121:                 if ($cmp1 eq $cmp2) {
1.561     banghart 5122:                     push(@readonly_files, $file_name);
1.745     raeburn  5123:                     last;
1.563     banghart 5124:                 } elsif (!defined($what)) {
                   5125:                     push(@readonly_files, $file_name);
1.745     raeburn  5126:                     last;
1.561     banghart 5127:                 }
                   5128:             }
1.745     raeburn  5129:         }
1.561     banghart 5130:     }
                   5131:     return @readonly_files;
                   5132: }
1.577     banghart 5133: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 5134: 
1.577     banghart 5135: sub get_marked_as_readonly_hash {
1.745     raeburn  5136:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 5137:     my %readonly_files;
1.745     raeburn  5138:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5139:         if (defined($group)) {
                   5140:             if ($file_name !~ m-^\Q$group\E/-) {
                   5141:                 next;
                   5142:             }
                   5143:         }
1.577     banghart 5144:         if (ref($value) eq "ARRAY"){
                   5145:             foreach my $stored_what (@{$value}) {
1.745     raeburn  5146:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 5147:                     foreach my $lock_descriptor(@{$stored_what}) {
                   5148:                         if ($lock_descriptor eq 'graded') {
                   5149:                             $readonly_files{$file_name} = 'graded';
                   5150:                         } elsif ($lock_descriptor eq 'handback') {
                   5151:                             $readonly_files{$file_name} = 'handback';
                   5152:                         } else {
                   5153:                             if (!exists($readonly_files{$file_name})) {
                   5154:                                 $readonly_files{$file_name} = 'locked';
                   5155:                             }
                   5156:                         }
1.745     raeburn  5157:                     }
1.750     banghart 5158:                 } 
1.577     banghart 5159:             }
                   5160:         } 
                   5161:     }
                   5162:     return %readonly_files;
                   5163: }
1.559     banghart 5164: # ------------------------------------------------------------ Unmark as Read Only
                   5165: 
                   5166: sub unmark_as_readonly {
1.629     banghart 5167:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   5168:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  5169:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 5170:     $file_name = &declutter_portfile($file_name);
1.634     albertel 5171:     my $symb_crs = $what;
                   5172:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  5173:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 5174:     my ($tmp)=keys(%current_permissions);
                   5175:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5176:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 5177:     foreach my $file (@readonly_files) {
1.759     albertel 5178: 	my $clean_file = &declutter_portfile($file);
                   5179: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 5180: 	my $current_locks = $current_permissions{$file};
1.563     banghart 5181:         my @new_locks;
                   5182:         my @del_keys;
                   5183:         if (ref($current_locks) eq "ARRAY"){
                   5184:             foreach my $locker (@{$current_locks}) {
1.632     albertel 5185:                 my $compare=$locker;
1.749     raeburn  5186:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  5187:                     $compare=join('',@{$locker});
1.746     raeburn  5188:                     if ($compare ne $symb_crs) {
                   5189:                         push(@new_locks, $locker);
                   5190:                     }
1.563     banghart 5191:                 }
                   5192:             }
1.650     albertel 5193:             if (scalar(@new_locks) > 0) {
1.563     banghart 5194:                 $current_permissions{$file} = \@new_locks;
                   5195:             } else {
                   5196:                 push(@del_keys, $file);
1.613     albertel 5197:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 5198:                 delete($current_permissions{$file});
1.563     banghart 5199:             }
                   5200:         }
1.561     banghart 5201:     }
1.613     albertel 5202:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5203:     return;
                   5204: }
1.512     banghart 5205: 
1.17      www      5206: # ------------------------------------------------------------ Directory lister
                   5207: 
                   5208: sub dirlist {
1.253     stredwic 5209:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
                   5210: 
1.18      www      5211:     $uri=~s/^\///;
                   5212:     $uri=~s/\/$//;
1.253     stredwic 5213:     my ($udom, $uname);
                   5214:     (undef,$udom,$uname)=split(/\//,$uri);
                   5215:     if(defined($userdomain)) {
                   5216:         $udom = $userdomain;
                   5217:     }
                   5218:     if(defined($username)) {
                   5219:         $uname = $username;
                   5220:     }
                   5221: 
                   5222:     my $dirRoot = $perlvar{'lonDocRoot'};
                   5223:     if(defined($alternateDirectoryRoot)) {
                   5224:         $dirRoot = $alternateDirectoryRoot;
                   5225:         $dirRoot =~ s/\/$//;
1.751     banghart 5226:     }
1.253     stredwic 5227: 
                   5228:     if($udom) {
                   5229:         if($uname) {
1.605     matthew  5230:             my $listing=reply('ls2:'.$dirRoot.'/'.$uri,
1.253     stredwic 5231:                               homeserver($uname,$udom));
1.605     matthew  5232:             my @listing_results;
                   5233:             if ($listing eq 'unknown_cmd') {
                   5234:                 $listing=reply('ls:'.$dirRoot.'/'.$uri,
                   5235:                                homeserver($uname,$udom));
                   5236:                 @listing_results = split(/:/,$listing);
                   5237:             } else {
                   5238:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   5239:             }
                   5240:             return @listing_results;
1.253     stredwic 5241:         } elsif(!defined($alternateDirectoryRoot)) {
                   5242:             my $tryserver;
                   5243:             my %allusers=();
                   5244:             foreach $tryserver (keys %libserv) {
                   5245:                 if($hostdom{$tryserver} eq $udom) {
1.605     matthew  5246:                     my $listing=reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
1.253     stredwic 5247:                                       $udom, $tryserver);
1.605     matthew  5248:                     my @listing_results;
                   5249:                     if ($listing eq 'unknown_cmd') {
                   5250:                         $listing=reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   5251:                                        $udom, $tryserver);
                   5252:                         @listing_results = split(/:/,$listing);
                   5253:                     } else {
                   5254:                         @listing_results =
                   5255:                             map { &unescape($_); } split(/:/,$listing);
                   5256:                     }
                   5257:                     if ($listing_results[0] ne 'no_such_dir' && 
                   5258:                         $listing_results[0] ne 'empty'       &&
                   5259:                         $listing_results[0] ne 'con_lost') {
                   5260:                         foreach (@listing_results) {
1.253     stredwic 5261:                             my ($entry,@stat)=split(/&/,$_);
                   5262:                             $allusers{$entry}=1;
                   5263:                         }
                   5264:                     }
1.191     harris41 5265:                 }
1.253     stredwic 5266:             }
                   5267:             my $alluserstr='';
                   5268:             foreach (sort keys %allusers) {
                   5269:                 $alluserstr.=$_.'&user:';
                   5270:             }
                   5271:             $alluserstr=~s/:$//;
                   5272:             return split(/:/,$alluserstr);
                   5273:         } else {
                   5274:             my @emptyResults = ();
                   5275:             push(@emptyResults, 'missing user name');
                   5276:             return split(':',@emptyResults);
                   5277:         }
                   5278:     } elsif(!defined($alternateDirectoryRoot)) {
                   5279:         my $tryserver;
                   5280:         my %alldom=();
                   5281:         foreach $tryserver (keys %libserv) {
                   5282:             $alldom{$hostdom{$tryserver}}=1;
                   5283:         }
                   5284:         my $alldomstr='';
                   5285:         foreach (sort keys %alldom) {
1.397     albertel 5286:             $alldomstr.=$perlvar{'lonDocRoot'}.'/res/'.$_.'/&domain:';
1.253     stredwic 5287:         }
                   5288:         $alldomstr=~s/:$//;
                   5289:         return split(/:/,$alldomstr);       
                   5290:     } else {
                   5291:         my @emptyResults = ();
                   5292:         push(@emptyResults, 'missing domain');
                   5293:         return split(':',@emptyResults);
1.275     stredwic 5294:     }
                   5295: }
                   5296: 
                   5297: # --------------------------------------------- GetFileTimestamp
                   5298: # This function utilizes dirlist and returns the date stamp for
                   5299: # when it was last modified.  It will also return an error of -1
                   5300: # if an error occurs
                   5301: 
1.410     matthew  5302: ##
                   5303: ## FIXME: This subroutine assumes its caller knows something about the
                   5304: ## directory structure of the home server for the student ($root).
                   5305: ## Not a good assumption to make.  Since this is for looking up files
                   5306: ## in user directories, the full path should be constructed by lond, not
                   5307: ## whatever machine we request data from.
                   5308: ##
1.275     stredwic 5309: sub GetFileTimestamp {
                   5310:     my ($studentDomain,$studentName,$filename,$root)=@_;
                   5311:     $studentDomain=~s/\W//g;
                   5312:     $studentName=~s/\W//g;
                   5313:     my $subdir=$studentName.'__';
                   5314:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   5315:     my $proname="$studentDomain/$subdir/$studentName";
                   5316:     $proname .= '/'.$filename;
1.375     matthew  5317:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
                   5318:                                               $studentName, $root);
1.275     stredwic 5319:     my @stats = split('&', $fileStat);
                   5320:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  5321:         # @stats contains first the filename, then the stat output
                   5322:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 5323:     } else {
                   5324:         return -1;
1.253     stredwic 5325:     }
1.26      www      5326: }
                   5327: 
1.712     albertel 5328: sub stat_file {
                   5329:     my ($uri) = @_;
1.787     albertel 5330:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 5331: 
1.712     albertel 5332:     my ($udom,$uname,$file,$dir);
                   5333:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   5334: 	($udom,$uname,$file) =
                   5335: 	    ($uri =~ m-/(?:uploaded|editupload)/?([^/]*)/?([^/]*)/?(.*)-);
                   5336: 	$file = 'userfiles/'.$file;
1.740     www      5337: 	$dir = &propath($udom,$uname);
1.712     albertel 5338:     }
                   5339:     if ($uri =~ m-^/res/-) {
                   5340: 	($udom,$uname) = 
                   5341: 	    ($uri =~ m-/(?:res)/?([^/]*)/?([^/]*)/-);
                   5342: 	$file = $uri;
                   5343:     }
                   5344: 
                   5345:     if (!$udom || !$uname || !$file) {
                   5346: 	# unable to handle the uri
                   5347: 	return ();
                   5348:     }
                   5349: 
                   5350:     my ($result) = &dirlist($file,$udom,$uname,$dir);
                   5351:     my @stats = split('&', $result);
1.721     banghart 5352:     
1.712     albertel 5353:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   5354: 	shift(@stats); #filename is first
                   5355: 	return @stats;
                   5356:     }
                   5357:     return ();
                   5358: }
                   5359: 
1.26      www      5360: # -------------------------------------------------------- Value of a Condition
                   5361: 
1.713     albertel 5362: # gets the value of a specific preevaluated condition
                   5363: #    stored in the string  $env{user.state.<cid>}
                   5364: # or looks up a condition reference in the bighash and if if hasn't
                   5365: # already been evaluated recurses into docondval to get the value of
                   5366: # the condition, then memoizing it to 
                   5367: #   $env{user.state.<cid>.<condition>}
1.40      www      5368: sub directcondval {
                   5369:     my $number=shift;
1.620     albertel 5370:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 5371: 	&Apache::lonuserstate::evalstate();
                   5372:     }
1.713     albertel 5373:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   5374: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   5375:     } elsif ($number =~ /^_/) {
                   5376: 	my $sub_condition;
                   5377: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   5378: 		&GDBM_READER(),0640)) {
                   5379: 	    $sub_condition=$bighash{'conditions'.$number};
                   5380: 	    untie(%bighash);
                   5381: 	}
                   5382: 	my $value = &docondval($sub_condition);
                   5383: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
                   5384: 	return $value;
                   5385:     }
1.620     albertel 5386:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   5387:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      5388:     } else {
                   5389:        return 2;
                   5390:     }
                   5391: }
                   5392: 
1.713     albertel 5393: # get the collection of conditions for this resource
1.26      www      5394: sub condval {
                   5395:     my $condidx=shift;
1.54      www      5396:     my $allpathcond='';
1.713     albertel 5397:     foreach my $cond (split(/\|/,$condidx)) {
                   5398: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   5399: 	    $allpathcond.=
                   5400: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   5401: 	}
1.191     harris41 5402:     }
1.54      www      5403:     $allpathcond=~s/\|$//;
1.713     albertel 5404:     return &docondval($allpathcond);
                   5405: }
                   5406: 
                   5407: #evaluates an expression of conditions
                   5408: sub docondval {
                   5409:     my ($allpathcond) = @_;
                   5410:     my $result=0;
                   5411:     if ($env{'request.course.id'}
                   5412: 	&& defined($allpathcond)) {
                   5413: 	my $operand='|';
                   5414: 	my @stack;
                   5415: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   5416: 	    if ($chunk eq '(') {
                   5417: 		push @stack,($operand,$result);
                   5418: 	    } elsif ($chunk eq ')') {
                   5419: 		my $before=pop @stack;
                   5420: 		if (pop @stack eq '&') {
                   5421: 		    $result=$result>$before?$before:$result;
                   5422: 		} else {
                   5423: 		    $result=$result>$before?$result:$before;
                   5424: 		}
                   5425: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   5426: 		$operand=$chunk;
                   5427: 	    } else {
                   5428: 		my $new=directcondval($chunk);
                   5429: 		if ($operand eq '&') {
                   5430: 		    $result=$result>$new?$new:$result;
                   5431: 		} else {
                   5432: 		    $result=$result>$new?$result:$new;
                   5433: 		}
                   5434: 	    }
                   5435: 	}
1.26      www      5436:     }
                   5437:     return $result;
1.421     albertel 5438: }
                   5439: 
                   5440: # ---------------------------------------------------- Devalidate courseresdata
                   5441: 
                   5442: sub devalidatecourseresdata {
                   5443:     my ($coursenum,$coursedomain)=@_;
                   5444:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 5445:     &devalidate_cache_new('courseres',$hashid);
1.28      www      5446: }
                   5447: 
1.763     www      5448: 
1.200     www      5449: # --------------------------------------------------- Course Resourcedata Query
                   5450: 
1.624     albertel 5451: sub get_courseresdata {
                   5452:     my ($coursenum,$coursedomain)=@_;
1.200     www      5453:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   5454:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 5455:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 5456:     my %dumpreply;
1.417     albertel 5457:     unless (defined($cached)) {
1.624     albertel 5458: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 5459: 	$result=\%dumpreply;
1.251     albertel 5460: 	my ($tmp) = keys(%dumpreply);
                   5461: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 5462: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 5463: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   5464: 	    return $tmp;
1.416     albertel 5465: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 5466: 	    $result=undef;
1.599     albertel 5467: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 5468: 	}
                   5469:     }
1.624     albertel 5470:     return $result;
                   5471: }
                   5472: 
1.633     albertel 5473: sub devalidateuserresdata {
                   5474:     my ($uname,$udom)=@_;
                   5475:     my $hashid="$udom:$uname";
                   5476:     &devalidate_cache_new('userres',$hashid);
                   5477: }
                   5478: 
1.624     albertel 5479: sub get_userresdata {
                   5480:     my ($uname,$udom)=@_;
                   5481:     #most student don\'t have any data set, check if there is some data
                   5482:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   5483: 
                   5484:     my $hashid="$udom:$uname";
                   5485:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   5486:     if (!defined($cached)) {
                   5487: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   5488: 	$result=\%resourcedata;
                   5489: 	&do_cache_new('userres',$hashid,$result,600);
                   5490:     }
                   5491:     my ($tmp)=keys(%$result);
                   5492:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   5493: 	return $result;
                   5494:     }
                   5495:     #error 2 occurs when the .db doesn't exist
                   5496:     if ($tmp!~/error: 2 /) {
1.672     albertel 5497: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 5498: 		 " Trying to get resource data for ".
                   5499: 		 $uname." at ".$udom.": ".
                   5500: 		 $tmp."</font>");
                   5501:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 5502: 	#&EXT_cache_set($udom,$uname);
                   5503: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 5504: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 5505:     }
                   5506:     return $tmp;
                   5507: }
                   5508: 
                   5509: sub resdata {
                   5510:     my ($name,$domain,$type,@which)=@_;
                   5511:     my $result;
                   5512:     if ($type eq 'course') {
                   5513: 	$result=&get_courseresdata($name,$domain);
                   5514:     } elsif ($type eq 'user') {
                   5515: 	$result=&get_userresdata($name,$domain);
                   5516:     }
                   5517:     if (!ref($result)) { return $result; }    
1.251     albertel 5518:     foreach my $item (@which) {
1.417     albertel 5519: 	if (defined($result->{$item})) {
                   5520: 	    return $result->{$item};
1.251     albertel 5521: 	}
1.250     albertel 5522:     }
1.291     albertel 5523:     return undef;
1.200     www      5524: }
                   5525: 
1.379     matthew  5526: #
                   5527: # EXT resource caching routines
                   5528: #
                   5529: 
                   5530: sub clear_EXT_cache_status {
1.383     albertel 5531:     &delenv('cache.EXT.');
1.379     matthew  5532: }
                   5533: 
                   5534: sub EXT_cache_status {
                   5535:     my ($target_domain,$target_user) = @_;
1.383     albertel 5536:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 5537:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  5538:         # We know already the user has no data
                   5539:         return 1;
                   5540:     } else {
                   5541:         return 0;
                   5542:     }
                   5543: }
                   5544: 
                   5545: sub EXT_cache_set {
                   5546:     my ($target_domain,$target_user) = @_;
1.383     albertel 5547:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.633     albertel 5548:     #&appenv($cachename => time);
1.379     matthew  5549: }
                   5550: 
1.28      www      5551: # --------------------------------------------------------- Value of a Variable
1.58      www      5552: sub EXT {
1.715     albertel 5553: 
1.395     albertel 5554:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      5555:     unless ($varname) { return ''; }
1.218     albertel 5556:     #get real user name/domain, courseid and symb
                   5557:     my $courseid;
1.359     albertel 5558:     my $publicuser;
1.427     www      5559:     if ($symbparm) {
                   5560: 	$symbparm=&get_symb_from_alias($symbparm);
                   5561:     }
1.218     albertel 5562:     if (!($uname && $udom)) {
1.790     albertel 5563:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 5564:       if (!$symbparm) {	$symbparm=$cursymb; }
                   5565:     } else {
1.620     albertel 5566: 	$courseid=$env{'request.course.id'};
1.218     albertel 5567:     }
1.48      www      5568:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   5569:     my $rest;
1.320     albertel 5570:     if (defined($therest[0])) {
1.48      www      5571:        $rest=join('.',@therest);
                   5572:     } else {
                   5573:        $rest='';
                   5574:     }
1.320     albertel 5575: 
1.57      www      5576:     my $qualifierrest=$qualifier;
                   5577:     if ($rest) { $qualifierrest.='.'.$rest; }
                   5578:     my $spacequalifierrest=$space;
                   5579:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      5580:     if ($realm eq 'user') {
1.48      www      5581: # --------------------------------------------------------------- user.resource
                   5582: 	if ($space eq 'resource') {
1.651     albertel 5583: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   5584: 		  || defined($Apache::lonhomework::parsing_a_task))
                   5585: 		 &&
1.744     albertel 5586: 		 ($symbparm eq &symbread()) ) {	
                   5587: 		# if we are in the middle of processing the resource the
                   5588: 		# get the value we are planning on committing
                   5589:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   5590:                     return $Apache::lonhomework::results{$qualifierrest};
                   5591:                 } else {
                   5592:                     return $Apache::lonhomework::history{$qualifierrest};
                   5593:                 }
1.335     albertel 5594: 	    } else {
1.359     albertel 5595: 		my %restored;
1.620     albertel 5596: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 5597: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   5598: 		} else {
                   5599: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   5600: 		}
1.335     albertel 5601: 		return $restored{$qualifierrest};
                   5602: 	    }
1.48      www      5603: # ----------------------------------------------------------------- user.access
                   5604:         } elsif ($space eq 'access') {
1.218     albertel 5605: 	    # FIXME - not supporting calls for a specific user
1.48      www      5606:             return &allowed($qualifier,$rest);
                   5607: # ------------------------------------------ user.preferences, user.environment
                   5608:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 5609: 	    if (($uname eq $env{'user.name'}) &&
                   5610: 		($udom eq $env{'user.domain'})) {
                   5611: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 5612: 	    } else {
1.359     albertel 5613: 		my %returnhash;
                   5614: 		if (!$publicuser) {
                   5615: 		    %returnhash=&userenvironment($udom,$uname,
                   5616: 						 $qualifierrest);
                   5617: 		}
1.218     albertel 5618: 		return $returnhash{$qualifierrest};
                   5619: 	    }
1.48      www      5620: # ----------------------------------------------------------------- user.course
                   5621:         } elsif ($space eq 'course') {
1.218     albertel 5622: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 5623:             return $env{join('.',('request.course',$qualifier))};
1.48      www      5624: # ------------------------------------------------------------------- user.role
                   5625:         } elsif ($space eq 'role') {
1.218     albertel 5626: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 5627:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      5628:             if ($qualifier eq 'value') {
                   5629: 		return $role;
                   5630:             } elsif ($qualifier eq 'extent') {
                   5631:                 return $where;
                   5632:             }
                   5633: # ----------------------------------------------------------------- user.domain
                   5634:         } elsif ($space eq 'domain') {
1.218     albertel 5635:             return $udom;
1.48      www      5636: # ------------------------------------------------------------------- user.name
                   5637:         } elsif ($space eq 'name') {
1.218     albertel 5638:             return $uname;
1.48      www      5639: # ---------------------------------------------------- Any other user namespace
1.29      www      5640:         } else {
1.359     albertel 5641: 	    my %reply;
                   5642: 	    if (!$publicuser) {
                   5643: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   5644: 	    }
                   5645: 	    return $reply{$qualifierrest};
1.48      www      5646:         }
1.236     www      5647:     } elsif ($realm eq 'query') {
                   5648: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 5649:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   5650: 						[$spacequalifierrest]);
1.620     albertel 5651: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      5652:    } elsif ($realm eq 'request') {
1.48      www      5653: # ------------------------------------------------------------- request.browser
                   5654:         if ($space eq 'browser') {
1.430     www      5655: 	    if ($qualifier eq 'textremote') {
1.676     albertel 5656: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      5657: 		    return 1;
                   5658: 		} else {
                   5659: 		    return 0;
                   5660: 		}
                   5661: 	    } else {
1.620     albertel 5662: 		return $env{'browser.'.$qualifier};
1.430     www      5663: 	    }
1.57      www      5664: # ------------------------------------------------------------ request.filename
                   5665:         } else {
1.620     albertel 5666:             return $env{'request.'.$spacequalifierrest};
1.29      www      5667:         }
1.28      www      5668:     } elsif ($realm eq 'course') {
1.48      www      5669: # ---------------------------------------------------------- course.description
1.620     albertel 5670:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      5671:     } elsif ($realm eq 'resource') {
1.165     www      5672: 
1.620     albertel 5673: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 5674: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   5675: 	}
1.693     albertel 5676: 
                   5677: 	if ($space eq 'title') {
                   5678: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   5679: 	    return &gettitle($symbparm);
                   5680: 	}
                   5681: 	
                   5682: 	if ($space eq 'map') {
                   5683: 	    my ($map) = &decode_symb($symbparm);
                   5684: 	    return &symbread($map);
                   5685: 	}
                   5686: 
                   5687: 	my ($section, $group, @groups);
1.593     albertel 5688: 	my ($courselevelm,$courselevel);
1.539     albertel 5689: 	if ($symbparm && defined($courseid) && 
1.620     albertel 5690: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      5691: 
1.218     albertel 5692: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      5693: 
1.60      www      5694: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 5695: 	    my $symbp=$symbparm;
1.735     albertel 5696: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 5697: 
                   5698: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   5699: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   5700: 
1.620     albertel 5701: 	    if (($env{'user.name'} eq $uname) &&
                   5702: 		($env{'user.domain'} eq $udom)) {
                   5703: 		$section=$env{'request.course.sec'};
1.733     raeburn  5704:                 @groups = split(/:/,$env{'request.course.groups'});  
                   5705:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 5706: 	    } else {
1.539     albertel 5707: 		if (! defined($usection)) {
1.551     albertel 5708: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 5709: 		} else {
                   5710: 		    $section = $usection;
                   5711: 		}
1.733     raeburn  5712:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 5713: 	    }
                   5714: 
                   5715: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   5716: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   5717: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   5718: 
1.593     albertel 5719: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 5720: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 5721: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      5722: 
1.60      www      5723: # ----------------------------------------------------------- first, check user
1.624     albertel 5724: 
                   5725: 	    my $userreply=&resdata($uname,$udom,'user',
                   5726: 				       ($courselevelr,$courselevelm,
                   5727: 					$courselevel));
                   5728: 	    if (defined($userreply)) { return $userreply; }
1.95      www      5729: 
1.594     albertel 5730: # ------------------------------------------------ second, check some of course
1.684     raeburn  5731:             my $coursereply;
1.691     raeburn  5732:             if (@groups > 0) {
                   5733:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   5734:                                        $mapparm,$spacequalifierrest);
1.684     raeburn  5735:                 if (defined($coursereply)) { return $coursereply; }
                   5736:             }
1.96      www      5737: 
1.684     raeburn  5738: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.624     albertel 5739: 				     $env{'course.'.$courseid.'.domain'},
                   5740: 				     'course',
                   5741: 				     ($seclevelr,$seclevelm,$seclevel,
                   5742: 				      $courselevelr));
1.287     albertel 5743: 	    if (defined($coursereply)) { return $coursereply; }
1.200     www      5744: 
1.60      www      5745: # ------------------------------------------------------ third, check map parms
1.218     albertel 5746: 	    my %parmhash=();
                   5747: 	    my $thisparm='';
                   5748: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 5749: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 5750: 		    &GDBM_READER(),0640)) {
1.218     albertel 5751: 		$thisparm=$parmhash{$symbparm};
                   5752: 		untie(%parmhash);
                   5753: 	    }
                   5754: 	    if ($thisparm) { return $thisparm; }
                   5755: 	}
1.594     albertel 5756: # ------------------------------------------ fourth, look in resource metadata
1.71      www      5757: 
1.218     albertel 5758: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 5759: 	my $filename;
                   5760: 	if (!$symbparm) { $symbparm=&symbread(); }
                   5761: 	if ($symbparm) {
1.409     www      5762: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 5763: 	} else {
1.620     albertel 5764: 	    $filename=$env{'request.filename'};
1.282     albertel 5765: 	}
                   5766: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.288     albertel 5767: 	if (defined($metadata)) { return $metadata; }
1.282     albertel 5768: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.288     albertel 5769: 	if (defined($metadata)) { return $metadata; }
1.142     www      5770: 
1.594     albertel 5771: # ---------------------------------------------- fourth, look in rest pf course
1.593     albertel 5772: 	if ($symbparm && defined($courseid) && 
1.620     albertel 5773: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 5774: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   5775: 				     $env{'course.'.$courseid.'.domain'},
                   5776: 				     'course',
                   5777: 				     ($courselevelm,$courselevel));
1.593     albertel 5778: 	    if (defined($coursereply)) { return $coursereply; }
                   5779: 	}
1.145     www      5780: # ------------------------------------------------------------------ Cascade up
1.218     albertel 5781: 	unless ($space eq '0') {
1.336     albertel 5782: 	    my @parts=split(/_/,$space);
                   5783: 	    my $id=pop(@parts);
                   5784: 	    my $part=join('_',@parts);
                   5785: 	    if ($part eq '') { $part='0'; }
                   5786: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 5787: 				 $symbparm,$udom,$uname,$section,1);
1.337     albertel 5788: 	    if (defined($partgeneral)) { return $partgeneral; }
1.218     albertel 5789: 	}
1.395     albertel 5790: 	if ($recurse) { return undef; }
                   5791: 	my $pack_def=&packages_tab_default($filename,$varname);
                   5792: 	if (defined($pack_def)) { return $pack_def; }
1.71      www      5793: 
1.48      www      5794: # ---------------------------------------------------- Any other user namespace
                   5795:     } elsif ($realm eq 'environment') {
                   5796: # ----------------------------------------------------------------- environment
1.620     albertel 5797: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   5798: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 5799: 	} else {
1.770     albertel 5800: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   5801: 		return '';
                   5802: 	    }
1.219     albertel 5803: 	    my %returnhash=&userenvironment($udom,$uname,
                   5804: 					    $spacequalifierrest);
                   5805: 	    return $returnhash{$spacequalifierrest};
                   5806: 	}
1.28      www      5807:     } elsif ($realm eq 'system') {
1.48      www      5808: # ----------------------------------------------------------------- system.time
                   5809: 	if ($space eq 'time') {
                   5810: 	    return time;
                   5811:         }
1.696     albertel 5812:     } elsif ($realm eq 'server') {
                   5813: # ----------------------------------------------------------------- system.time
                   5814: 	if ($space eq 'name') {
                   5815: 	    return $ENV{'SERVER_NAME'};
                   5816:         }
1.28      www      5817:     }
1.48      www      5818:     return '';
1.61      www      5819: }
                   5820: 
1.691     raeburn  5821: sub check_group_parms {
                   5822:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   5823:     my @groupitems = ();
                   5824:     my $resultitem;
                   5825:     my @levels = ($symbparm,$mapparm,$what);
                   5826:     foreach my $group (@{$groups}) {
                   5827:         foreach my $level (@levels) {
                   5828:              my $item = $courseid.'.['.$group.'].'.$level;
                   5829:              push(@groupitems,$item);
                   5830:         }
                   5831:     }
                   5832:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   5833:                             $env{'course.'.$courseid.'.domain'},
                   5834:                                      'course',@groupitems);
                   5835:     return $coursereply;
                   5836: }
                   5837: 
                   5838: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  5839:     my ($courseid,@groups) = @_;
                   5840:     @groups = sort(@groups);
1.691     raeburn  5841:     return @groups;
                   5842: }
                   5843: 
1.395     albertel 5844: sub packages_tab_default {
                   5845:     my ($uri,$varname)=@_;
                   5846:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 5847: 
                   5848:     my (@extension,@specifics,$do_default);
                   5849:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 5850: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 5851: 	if ($pack_type eq 'default') {
                   5852: 	    $do_default=1;
                   5853: 	} elsif ($pack_type eq 'extension') {
                   5854: 	    push(@extension,[$package,$pack_type,$pack_part]);
                   5855: 	} else {
                   5856: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   5857: 	}
                   5858:     }
                   5859:     # first look for a package that matches the requested part id
                   5860:     foreach my $package (@specifics) {
                   5861: 	my (undef,$pack_type,$pack_part)=@{$package};
                   5862: 	next if ($pack_part ne $part);
                   5863: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   5864: 	    return $packagetab{"$pack_type&$name&default"};
                   5865: 	}
                   5866:     }
                   5867:     # look for any possible matching non extension_ package
                   5868:     foreach my $package (@specifics) {
                   5869: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 5870: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   5871: 	    return $packagetab{"$pack_type&$name&default"};
                   5872: 	}
1.585     albertel 5873: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 5874: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   5875: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 5876: 	}
                   5877:     }
1.738     albertel 5878:     # look for any posible extension_ match
                   5879:     foreach my $package (@extension) {
                   5880: 	my ($package,$pack_type)=@{$package};
                   5881: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   5882: 	    return $packagetab{"$pack_type&$name&default"};
                   5883: 	}
                   5884: 	if (defined($packagetab{$package."&$name&default"})) {
                   5885: 	    return $packagetab{$package."&$name&default"};
                   5886: 	}
                   5887:     }
                   5888:     # look for a global default setting
                   5889:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   5890: 	return $packagetab{"default&$name&default"};
                   5891:     }
1.395     albertel 5892:     return undef;
                   5893: }
                   5894: 
1.334     albertel 5895: sub add_prefix_and_part {
                   5896:     my ($prefix,$part)=@_;
                   5897:     my $keyroot;
                   5898:     if (defined($prefix) && $prefix !~ /^__/) {
                   5899: 	# prefix that has a part already
                   5900: 	$keyroot=$prefix;
                   5901:     } elsif (defined($prefix)) {
                   5902: 	# prefix that is missing a part
                   5903: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   5904:     } else {
                   5905: 	# no prefix at all
                   5906: 	if (defined($part)) { $keyroot='_'.$part; }
                   5907:     }
                   5908:     return $keyroot;
                   5909: }
                   5910: 
1.71      www      5911: # ---------------------------------------------------------------- Get metadata
                   5912: 
1.599     albertel 5913: my %metaentry;
1.71      www      5914: sub metadata {
1.176     www      5915:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      5916:     $uri=&declutter($uri);
1.288     albertel 5917:     # if it is a non metadata possible uri return quickly
1.529     albertel 5918:     if (($uri eq '') || 
                   5919: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 5920: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.423     albertel 5921:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
1.489     albertel 5922: 	($uri =~ m|home/[^/]+/public_html/|)) {
1.468     albertel 5923: 	return undef;
1.288     albertel 5924:     }
1.73      www      5925:     my $filename=$uri;
                   5926:     $uri=~s/\.meta$//;
1.172     www      5927: #
                   5928: # Is the metadata already cached?
1.177     www      5929: # Look at timestamp of caching
1.172     www      5930: # Everything is cached by the main uri, libraries are never directly cached
                   5931: #
1.428     albertel 5932:     if (!defined($liburi)) {
1.599     albertel 5933: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 5934: 	if (defined($cached)) { return $result->{':'.$what}; }
                   5935:     }
                   5936:     {
1.172     www      5937: #
                   5938: # Is this a recursive call for a library?
                   5939: #
1.599     albertel 5940: #	if (! exists($metacache{$uri})) {
                   5941: #	    $metacache{$uri}={};
                   5942: #	}
1.171     www      5943:         if ($liburi) {
                   5944: 	    $liburi=&declutter($liburi);
                   5945:             $filename=$liburi;
1.401     bowersj2 5946:         } else {
1.599     albertel 5947: 	    &devalidate_cache_new('meta',$uri);
                   5948: 	    undef(%metaentry);
1.401     bowersj2 5949: 	}
1.140     www      5950:         my %metathesekeys=();
1.73      www      5951:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 5952: 	my $metastring;
1.768     albertel 5953: 	if ($uri !~ m -^(editupload)/-) {
1.543     albertel 5954: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 5955: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 5956: 	    $metastring=&getfile($file);
1.489     albertel 5957: 	}
1.208     albertel 5958:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      5959:         my $token;
1.140     www      5960:         undef %metathesekeys;
1.71      www      5961:         while ($token=$parser->get_token) {
1.339     albertel 5962: 	    if ($token->[0] eq 'S') {
                   5963: 		if (defined($token->[2]->{'package'})) {
1.172     www      5964: #
                   5965: # This is a package - get package info
                   5966: #
1.339     albertel 5967: 		    my $package=$token->[2]->{'package'};
                   5968: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   5969: 		    if (defined($token->[2]->{'id'})) { 
                   5970: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   5971: 		    }
1.599     albertel 5972: 		    if ($metaentry{':packages'}) {
                   5973: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 5974: 		    } else {
1.599     albertel 5975: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 5976: 		    }
1.736     albertel 5977: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 5978: 			my $part=$keyroot;
                   5979: 			$part=~s/^\_//;
1.736     albertel 5980: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   5981: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   5982: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 5983: 			    # ignore package.tab specified default values
                   5984:                             # here &package_tab_default() will fetch those
                   5985: 			    if ($subp eq 'default') { next; }
1.736     albertel 5986: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 5987: 			    my $unikey;
                   5988: 			    if ($pack =~ /_0$/) {
                   5989: 				$unikey='parameter_0_'.$name;
                   5990: 				$part=0;
                   5991: 			    } else {
                   5992: 				$unikey='parameter'.$keyroot.'_'.$name;
                   5993: 			    }
1.339     albertel 5994: 			    if ($subp eq 'display') {
                   5995: 				$value.=' [Part: '.$part.']';
                   5996: 			    }
1.599     albertel 5997: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 5998: 			    $metathesekeys{$unikey}=1;
1.599     albertel 5999: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6000: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 6001: 			    }
1.599     albertel 6002: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   6003: 				$metaentry{':'.$unikey}=
                   6004: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 6005: 			    }
1.339     albertel 6006: 			}
                   6007: 		    }
                   6008: 		} else {
1.172     www      6009: #
                   6010: # This is not a package - some other kind of start tag
1.339     albertel 6011: #
                   6012: 		    my $entry=$token->[1];
                   6013: 		    my $unikey;
                   6014: 		    if ($entry eq 'import') {
                   6015: 			$unikey='';
                   6016: 		    } else {
                   6017: 			$unikey=$entry;
                   6018: 		    }
                   6019: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6020: 
                   6021: 		    if (defined($token->[2]->{'id'})) { 
                   6022: 			$unikey.='_'.$token->[2]->{'id'}; 
                   6023: 		    }
1.175     www      6024: 
1.339     albertel 6025: 		    if ($entry eq 'import') {
1.175     www      6026: #
                   6027: # Importing a library here
1.339     albertel 6028: #
                   6029: 			if ($depthcount<20) {
                   6030: 			    my $location=$parser->get_text('/import');
                   6031: 			    my $dir=$filename;
                   6032: 			    $dir=~s|[^/]*$||;
                   6033: 			    $location=&filelocation($dir,$location);
1.736     albertel 6034: 			    my $metadata = 
                   6035: 				&metadata($uri,'keys', $location,$unikey,
                   6036: 					  $depthcount+1);
                   6037: 			    foreach my $meta (split(',',$metadata)) {
                   6038: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   6039: 				$metathesekeys{$meta}=1;
1.339     albertel 6040: 			    }
                   6041: 			}
                   6042: 		    } else { 
                   6043: 			
                   6044: 			if (defined($token->[2]->{'name'})) { 
                   6045: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   6046: 			}
                   6047: 			$metathesekeys{$unikey}=1;
1.736     albertel 6048: 			foreach my $param (@{$token->[3]}) {
                   6049: 			    $metaentry{':'.$unikey.'.'.$param} =
                   6050: 				$token->[2]->{$param};
1.339     albertel 6051: 			}
                   6052: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 6053: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 6054: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   6055: 		 # only ws inside the tag, and not in default, so use default
                   6056: 		 # as value
1.599     albertel 6057: 			    $metaentry{':'.$unikey}=$default;
1.339     albertel 6058: 			} else {
1.321     albertel 6059: 		  # either something interesting inside the tag or default
                   6060:                   # uninteresting
1.599     albertel 6061: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 6062: 			}
1.172     www      6063: # end of not-a-package not-a-library import
1.339     albertel 6064: 		    }
1.172     www      6065: # end of not-a-package start tag
1.339     albertel 6066: 		}
1.172     www      6067: # the next is the end of "start tag"
1.339     albertel 6068: 	    }
                   6069: 	}
1.483     albertel 6070: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.737     albertel 6071: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 6072: 	    #no specific packages #how's our extension
                   6073: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 6074: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 6075: 					 \%metathesekeys);
                   6076: 	}
1.599     albertel 6077: 	if (!exists($metaentry{':packages'})) {
1.737     albertel 6078: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 6079: 		#no specific packages well let's get default then
                   6080: 		if ($key!~/^default&/) { next; }
1.488     albertel 6081: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 6082: 					     \%metathesekeys);
                   6083: 	    }
                   6084: 	}
1.338     www      6085: # are there custom rights to evaluate
1.599     albertel 6086: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 6087: 
1.338     www      6088:     #
                   6089:     # Importing a rights file here
1.339     albertel 6090:     #
                   6091: 	    unless ($depthcount) {
1.599     albertel 6092: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 6093: 		my $dir=$filename;
                   6094: 		$dir=~s|[^/]*$||;
                   6095: 		$location=&filelocation($dir,$location);
1.736     albertel 6096: 		my $rights_metadata =
                   6097: 		    &metadata($uri,'keys',$location,'_rights',
                   6098: 			      $depthcount+1);
                   6099: 		foreach my $rights (split(',',$rights_metadata)) {
                   6100: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   6101: 		    $metathesekeys{$rights}=1;
1.339     albertel 6102: 		}
                   6103: 	    }
                   6104: 	}
1.737     albertel 6105: 	# uniqifiy package listing
                   6106: 	my %seen;
                   6107: 	my @uniq_packages =
                   6108: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   6109: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   6110: 
                   6111: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 6112: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   6113: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.699     albertel 6114: 	&do_cache_new('meta',$uri,\%metaentry,60*60);
1.177     www      6115: # this is the end of "was not already recently cached
1.71      www      6116:     }
1.599     albertel 6117:     return $metaentry{':'.$what};
1.261     albertel 6118: }
                   6119: 
1.488     albertel 6120: sub metadata_create_package_def {
1.483     albertel 6121:     my ($uri,$key,$package,$metathesekeys)=@_;
                   6122:     my ($pack,$name,$subp)=split(/\&/,$key);
                   6123:     if ($subp eq 'default') { next; }
                   6124:     
1.599     albertel 6125:     if (defined($metaentry{':packages'})) {
                   6126: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 6127:     } else {
1.599     albertel 6128: 	$metaentry{':packages'}=$package;
1.483     albertel 6129:     }
                   6130:     my $value=$packagetab{$key};
                   6131:     my $unikey;
                   6132:     $unikey='parameter_0_'.$name;
1.599     albertel 6133:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 6134:     $$metathesekeys{$unikey}=1;
1.599     albertel 6135:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6136: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 6137:     }
1.599     albertel 6138:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   6139: 	$metaentry{':'.$unikey}=
                   6140: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 6141:     }
                   6142: }
                   6143: 
1.261     albertel 6144: sub metadata_generate_part0 {
                   6145:     my ($metadata,$metacache,$uri) = @_;
                   6146:     my %allnames;
1.737     albertel 6147:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 6148: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 6149: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   6150: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 6151: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 6152: 	    $allnames{$name}=$part;
                   6153: 	  }
                   6154: 	}
                   6155:     }
                   6156:     foreach my $name (keys(%allnames)) {
                   6157:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 6158:       my $key=":parameter_0_$name";
1.261     albertel 6159:       $$metacache{"$key.part"}='0';
                   6160:       $$metacache{"$key.name"}=$name;
1.428     albertel 6161:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 6162: 					   $allnames{$name}.'_'.$name.
                   6163: 					   '.type'};
1.428     albertel 6164:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 6165: 			     '.display'};
1.644     www      6166:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 6167:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 6168:       $$metacache{"$key.display"}=$olddis;
                   6169:     }
1.71      www      6170: }
                   6171: 
1.764     albertel 6172: # ------------------------------------------------------ Devalidate title cache
                   6173: 
                   6174: sub devalidate_title_cache {
                   6175:     my ($url)=@_;
                   6176:     if (!$env{'request.course.id'}) { return; }
                   6177:     my $symb=&symbread($url);
                   6178:     if (!$symb) { return; }
                   6179:     my $key=$env{'request.course.id'}."\0".$symb;
                   6180:     &devalidate_cache_new('title',$key);
                   6181: }
                   6182: 
1.301     www      6183: # ------------------------------------------------- Get the title of a resource
                   6184: 
                   6185: sub gettitle {
                   6186:     my $urlsymb=shift;
                   6187:     my $symb=&symbread($urlsymb);
1.534     albertel 6188:     if ($symb) {
1.620     albertel 6189: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 6190: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 6191: 	if (defined($cached)) { 
                   6192: 	    return $result;
                   6193: 	}
1.534     albertel 6194: 	my ($map,$resid,$url)=&decode_symb($symb);
                   6195: 	my $title='';
                   6196: 	my %bighash;
1.620     albertel 6197: 	if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.534     albertel 6198: 		&GDBM_READER(),0640)) {
                   6199: 	    my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   6200: 	    $title=$bighash{'title_'.$mapid.'.'.$resid};
                   6201: 	    untie %bighash;
                   6202: 	}
                   6203: 	$title=~s/\&colon\;/\:/gs;
                   6204: 	if ($title) {
1.599     albertel 6205: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 6206: 	}
                   6207: 	$urlsymb=$url;
                   6208:     }
                   6209:     my $title=&metadata($urlsymb,'title');
                   6210:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   6211:     return $title;
1.301     www      6212: }
1.613     albertel 6213: 
1.614     albertel 6214: sub get_slot {
                   6215:     my ($which,$cnum,$cdom)=@_;
                   6216:     if (!$cnum || !$cdom) {
1.790     albertel 6217: 	(undef,my $courseid)=&whichuser();
1.620     albertel 6218: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   6219: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 6220:     }
1.703     albertel 6221:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   6222:     my %slotinfo;
                   6223:     if (exists($remembered{$key})) {
                   6224: 	$slotinfo{$which} = $remembered{$key};
                   6225:     } else {
                   6226: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   6227: 	&Apache::lonhomework::showhash(%slotinfo);
                   6228: 	my ($tmp)=keys(%slotinfo);
                   6229: 	if ($tmp=~/^error:/) { return (); }
                   6230: 	$remembered{$key} = $slotinfo{$which};
                   6231:     }
1.616     albertel 6232:     if (ref($slotinfo{$which}) eq 'HASH') {
                   6233: 	return %{$slotinfo{$which}};
                   6234:     }
                   6235:     return $slotinfo{$which};
1.614     albertel 6236: }
1.31      www      6237: # ------------------------------------------------- Update symbolic store links
                   6238: 
                   6239: sub symblist {
                   6240:     my ($mapname,%newhash)=@_;
1.438     www      6241:     $mapname=&deversion(&declutter($mapname));
1.31      www      6242:     my %hash;
1.620     albertel 6243:     if (($env{'request.course.fn'}) && (%newhash)) {
                   6244:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6245:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 6246: 	    foreach my $url (keys %newhash) {
                   6247: 		next if ($url eq 'last_known'
                   6248: 			 && $env{'form.no_update_last_known'});
                   6249: 		$hash{declutter($url)}=&encode_symb($mapname,
                   6250: 						    $newhash{$url}->[1],
                   6251: 						    $newhash{$url}->[0]);
1.191     harris41 6252:             }
1.31      www      6253:             if (untie(%hash)) {
                   6254: 		return 'ok';
                   6255:             }
                   6256:         }
                   6257:     }
                   6258:     return 'error';
1.212     www      6259: }
                   6260: 
                   6261: # --------------------------------------------------------------- Verify a symb
                   6262: 
                   6263: sub symbverify {
1.510     www      6264:     my ($symb,$thisurl)=@_;
                   6265:     my $thisfn=$thisurl;
1.439     www      6266:     $thisfn=&declutter($thisfn);
1.215     www      6267: # direct jump to resource in page or to a sequence - will construct own symbs
                   6268:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   6269: # check URL part
1.409     www      6270:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      6271: 
1.431     www      6272:     unless ($url eq $thisfn) { return 0; }
1.213     www      6273: 
1.216     www      6274:     $symb=&symbclean($symb);
1.510     www      6275:     $thisurl=&deversion($thisurl);
1.439     www      6276:     $thisfn=&deversion($thisfn);
1.213     www      6277: 
                   6278:     my %bighash;
                   6279:     my $okay=0;
1.431     www      6280: 
1.620     albertel 6281:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6282:                             &GDBM_READER(),0640)) {
1.510     www      6283:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      6284:         unless ($ids) { 
1.510     www      6285:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      6286:         }
                   6287:         if ($ids) {
                   6288: # ------------------------------------------------------------------- Has ID(s)
                   6289: 	    foreach (split(/\,/,$ids)) {
1.644     www      6290: 	       my ($mapid,$resid)=split(/\./,$_);
1.216     www      6291:                if (
                   6292:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   6293:    eq $symb) { 
1.620     albertel 6294: 		   if (($env{'request.role.adv'}) ||
                   6295: 		       $bighash{'encrypted_'.$_} eq $env{'request.enc'}) {
1.582     albertel 6296: 		       $okay=1; 
                   6297: 		   }
                   6298: 	       }
1.216     www      6299: 	   }
                   6300:         }
1.213     www      6301: 	untie(%bighash);
                   6302:     }
                   6303:     return $okay;
1.31      www      6304: }
                   6305: 
1.210     www      6306: # --------------------------------------------------------------- Clean-up symb
                   6307: 
                   6308: sub symbclean {
                   6309:     my $symb=shift;
1.568     albertel 6310:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      6311: # remove version from map
                   6312:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      6313: 
1.210     www      6314: # remove version from URL
                   6315:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      6316: 
1.507     www      6317: # remove wrapper
                   6318: 
1.510     www      6319:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 6320:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      6321:     return $symb;
1.409     www      6322: }
                   6323: 
                   6324: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 6325: 
                   6326: sub encode_symb {
                   6327:     my ($map,$resid,$url)=@_;
                   6328:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   6329: }
1.409     www      6330: 
                   6331: sub decode_symb {
1.568     albertel 6332:     my $symb=shift;
                   6333:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   6334:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      6335:     return (&fixversion($map),$resid,&fixversion($url));
                   6336: }
                   6337: 
                   6338: sub fixversion {
                   6339:     my $fn=shift;
1.609     banghart 6340:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      6341:     my %bighash;
                   6342:     my $uri=&clutter($fn);
1.620     albertel 6343:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      6344: # is this cached?
1.599     albertel 6345:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      6346:     if (defined($cached)) { return $result; }
                   6347: # unfortunately not cached, or expired
1.620     albertel 6348:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      6349: 	    &GDBM_READER(),0640)) {
                   6350:  	if ($bighash{'version_'.$uri}) {
                   6351:  	    my $version=$bighash{'version_'.$uri};
1.444     www      6352:  	    unless (($version eq 'mostrecent') || 
                   6353: 		    ($version==&getversion($uri))) {
1.440     www      6354:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   6355:  	    }
                   6356:  	}
                   6357:  	untie %bighash;
1.413     www      6358:     }
1.599     albertel 6359:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      6360: }
                   6361: 
                   6362: sub deversion {
                   6363:     my $url=shift;
                   6364:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   6365:     return $url;
1.210     www      6366: }
                   6367: 
1.31      www      6368: # ------------------------------------------------------ Return symb list entry
                   6369: 
                   6370: sub symbread {
1.249     www      6371:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 6372:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 6373:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      6374: # no filename provided? try from environment
1.44      www      6375:     unless ($thisfn) {
1.620     albertel 6376:         if ($env{'request.symb'}) {
                   6377: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 6378: 	}
1.620     albertel 6379: 	$thisfn=$env{'request.filename'};
1.44      www      6380:     }
1.569     albertel 6381:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      6382: # is that filename actually a symb? Verify, clean, and return
                   6383:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 6384: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 6385: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 6386: 	}
1.242     www      6387:     }
1.44      www      6388:     $thisfn=declutter($thisfn);
1.31      www      6389:     my %hash;
1.37      www      6390:     my %bighash;
                   6391:     my $syval='';
1.620     albertel 6392:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  6393:         my $targetfn = $thisfn;
1.609     banghart 6394:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  6395:             $targetfn = 'adm/wrapper/'.$thisfn;
                   6396:         }
1.687     albertel 6397: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   6398: 	    $targetfn=$1;
                   6399: 	}
1.620     albertel 6400:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6401:                       &GDBM_READER(),0640)) {
1.481     raeburn  6402: 	    $syval=$hash{$targetfn};
1.37      www      6403:             untie(%hash);
                   6404:         }
                   6405: # ---------------------------------------------------------- There was an entry
                   6406:         if ($syval) {
1.601     albertel 6407: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 6408: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.601     albertel 6409: 		    #&appenv('request.ambiguous' => $thisfn);
1.620     albertel 6410: 		    #return $env{$cache_str}='';
1.601     albertel 6411: 		#}    
                   6412: 		#$syval.=$1;
                   6413: 	    #}
1.37      www      6414:         } else {
                   6415: # ------------------------------------------------------- Was not in symb table
1.620     albertel 6416:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6417:                             &GDBM_READER(),0640)) {
1.37      www      6418: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      6419:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      6420:               unless ($ids) { 
                   6421:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      6422:               }
                   6423:               unless ($ids) {
                   6424: # alias?
                   6425: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      6426:               }
1.37      www      6427:               if ($ids) {
                   6428: # ------------------------------------------------------------------- Has ID(s)
                   6429:                  my @possibilities=split(/\,/,$ids);
1.39      www      6430:                  if ($#possibilities==0) {
                   6431: # ----------------------------------------------- There is only one possibility
1.37      www      6432: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 6433: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6434: 						    $resid,$thisfn);
1.249     www      6435:                  } elsif (!$donotrecurse) {
1.39      www      6436: # ------------------------------------------ There is more than one possibility
                   6437:                      my $realpossible=0;
1.191     harris41 6438:                      foreach (@possibilities) {
1.39      www      6439: 			 my $file=$bighash{'src_'.$_};
                   6440:                          if (&allowed('bre',$file)) {
                   6441:          		    my ($mapid,$resid)=split(/\./,$_);
                   6442:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   6443: 				$realpossible++;
1.626     albertel 6444:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6445: 						    $resid,$thisfn);
1.39      www      6446:                             }
                   6447: 			 }
1.191     harris41 6448:                      }
1.39      www      6449: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      6450:                  } else {
                   6451:                      $syval='';
1.37      www      6452:                  }
                   6453: 	      }
                   6454:               untie(%bighash)
1.481     raeburn  6455:            }
1.31      www      6456:         }
1.62      www      6457:         if ($syval) {
1.620     albertel 6458: 	    return $env{$cache_str}=$syval;
1.62      www      6459:         }
1.31      www      6460:     }
1.44      www      6461:     &appenv('request.ambiguous' => $thisfn);
1.620     albertel 6462:     return $env{$cache_str}='';
1.31      www      6463: }
                   6464: 
                   6465: # ---------------------------------------------------------- Return random seed
                   6466: 
1.32      www      6467: sub numval {
                   6468:     my $txt=shift;
                   6469:     $txt=~tr/A-J/0-9/;
                   6470:     $txt=~tr/a-j/0-9/;
                   6471:     $txt=~tr/K-T/0-9/;
                   6472:     $txt=~tr/k-t/0-9/;
                   6473:     $txt=~tr/U-Z/0-5/;
                   6474:     $txt=~tr/u-z/0-5/;
                   6475:     $txt=~s/\D//g;
1.564     albertel 6476:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      6477:     return int($txt);
1.368     albertel 6478: }
                   6479: 
1.484     albertel 6480: sub numval2 {
                   6481:     my $txt=shift;
                   6482:     $txt=~tr/A-J/0-9/;
                   6483:     $txt=~tr/a-j/0-9/;
                   6484:     $txt=~tr/K-T/0-9/;
                   6485:     $txt=~tr/k-t/0-9/;
                   6486:     $txt=~tr/U-Z/0-5/;
                   6487:     $txt=~tr/u-z/0-5/;
                   6488:     $txt=~s/\D//g;
                   6489:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   6490:     my $total;
                   6491:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 6492:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 6493:     return int($total);
                   6494: }
                   6495: 
1.575     albertel 6496: sub numval3 {
                   6497:     use integer;
                   6498:     my $txt=shift;
                   6499:     $txt=~tr/A-J/0-9/;
                   6500:     $txt=~tr/a-j/0-9/;
                   6501:     $txt=~tr/K-T/0-9/;
                   6502:     $txt=~tr/k-t/0-9/;
                   6503:     $txt=~tr/U-Z/0-5/;
                   6504:     $txt=~tr/u-z/0-5/;
                   6505:     $txt=~s/\D//g;
                   6506:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   6507:     my $total;
                   6508:     foreach my $val (@txts) { $total+=$val; }
                   6509:     if ($_64bit) { $total=(($total<<32)>>32); }
                   6510:     return $total;
                   6511: }
                   6512: 
1.675     albertel 6513: sub digest {
                   6514:     my ($data)=@_;
                   6515:     my $digest=&Digest::MD5::md5($data);
                   6516:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   6517:     my ($e,$f);
                   6518:     {
                   6519:         use integer;
                   6520:         $e=($a+$b);
                   6521:         $f=($c+$d);
                   6522:         if ($_64bit) {
                   6523:             $e=(($e<<32)>>32);
                   6524:             $f=(($f<<32)>>32);
                   6525:         }
                   6526:     }
                   6527:     if (wantarray) {
                   6528: 	return ($e,$f);
                   6529:     } else {
                   6530: 	my $g;
                   6531: 	{
                   6532: 	    use integer;
                   6533: 	    $g=($e+$f);
                   6534: 	    if ($_64bit) {
                   6535: 		$g=(($g<<32)>>32);
                   6536: 	    }
                   6537: 	}
                   6538: 	return $g;
                   6539:     }
                   6540: }
                   6541: 
1.368     albertel 6542: sub latest_rnd_algorithm_id {
1.675     albertel 6543:     return '64bit5';
1.366     albertel 6544: }
1.32      www      6545: 
1.503     albertel 6546: sub get_rand_alg {
                   6547:     my ($courseid)=@_;
1.790     albertel 6548:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 6549:     if ($courseid) {
1.620     albertel 6550: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 6551:     }
                   6552:     return &latest_rnd_algorithm_id();
                   6553: }
                   6554: 
1.562     albertel 6555: sub validCODE {
                   6556:     my ($CODE)=@_;
                   6557:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   6558:     return 0;
                   6559: }
                   6560: 
1.491     albertel 6561: sub getCODE {
1.620     albertel 6562:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 6563:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   6564: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   6565: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 6566: 	return $Apache::lonhomework::history{'resource.CODE'};
                   6567:     }
                   6568:     return undef;
                   6569: }
                   6570: 
1.31      www      6571: sub rndseed {
1.155     albertel 6572:     my ($symb,$courseid,$domain,$username)=@_;
1.366     albertel 6573: 
1.790     albertel 6574:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.155     albertel 6575:     if (!$symb) {
1.366     albertel 6576: 	unless ($symb=$wsymb) { return time; }
                   6577:     }
                   6578:     if (!$courseid) { $courseid=$wcourseid; }
                   6579:     if (!$domain) { $domain=$wdomain; }
                   6580:     if (!$username) { $username=$wusername }
1.503     albertel 6581:     my $which=&get_rand_alg();
1.491     albertel 6582:     if (defined(&getCODE())) {
1.675     albertel 6583: 	if ($which eq '64bit5') {
                   6584: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   6585: 	} elsif ($which eq '64bit4') {
1.575     albertel 6586: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   6587: 	} else {
                   6588: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   6589: 	}
1.675     albertel 6590:     } elsif ($which eq '64bit5') {
                   6591: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 6592:     } elsif ($which eq '64bit4') {
                   6593: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 6594:     } elsif ($which eq '64bit3') {
                   6595: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 6596:     } elsif ($which eq '64bit2') {
                   6597: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 6598:     } elsif ($which eq '64bit') {
                   6599: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   6600:     }
                   6601:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   6602: }
                   6603: 
                   6604: sub rndseed_32bit {
                   6605:     my ($symb,$courseid,$domain,$username)=@_;
                   6606:     {
                   6607: 	use integer;
                   6608: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   6609: 	my $symbseed=numval($symb) << 22;
                   6610: 	my $namechck=unpack("%32C*",$username) << 17;
                   6611: 	my $nameseed=numval($username) << 12;
                   6612: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   6613: 	my $courseseed=unpack("%32C*",$courseid);
                   6614: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 6615: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6616: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 6617: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 6618: 	return $num;
                   6619:     }
                   6620: }
                   6621: 
                   6622: sub rndseed_64bit {
                   6623:     my ($symb,$courseid,$domain,$username)=@_;
                   6624:     {
                   6625: 	use integer;
                   6626: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   6627: 	my $symbseed=numval($symb) << 10;
                   6628: 	my $namechck=unpack("%32S*",$username);
                   6629: 	
                   6630: 	my $nameseed=numval($username) << 21;
                   6631: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   6632: 	my $courseseed=unpack("%32S*",$courseid);
                   6633: 	
                   6634: 	my $num1=$symbchck+$symbseed+$namechck;
                   6635: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6636: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6637: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 6638: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6639: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 6640: 	return "$num1,$num2";
1.155     albertel 6641:     }
1.366     albertel 6642: }
                   6643: 
1.443     albertel 6644: sub rndseed_64bit2 {
                   6645:     my ($symb,$courseid,$domain,$username)=@_;
                   6646:     {
                   6647: 	use integer;
                   6648: 	# strings need to be an even # of cahracters long, it it is odd the
                   6649:         # last characters gets thrown away
                   6650: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6651: 	my $symbseed=numval($symb) << 10;
                   6652: 	my $namechck=unpack("%32S*",$username.' ');
                   6653: 	
                   6654: 	my $nameseed=numval($username) << 21;
1.501     albertel 6655: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6656: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6657: 	
                   6658: 	my $num1=$symbchck+$symbseed+$namechck;
                   6659: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6660: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6661: 	#&logthis("rndseed :$num:$symb");
1.501     albertel 6662: 	return "$num1,$num2";
                   6663:     }
                   6664: }
                   6665: 
                   6666: sub rndseed_64bit3 {
                   6667:     my ($symb,$courseid,$domain,$username)=@_;
                   6668:     {
                   6669: 	use integer;
                   6670: 	# strings need to be an even # of cahracters long, it it is odd the
                   6671:         # last characters gets thrown away
                   6672: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6673: 	my $symbseed=numval2($symb) << 10;
                   6674: 	my $namechck=unpack("%32S*",$username.' ');
                   6675: 	
                   6676: 	my $nameseed=numval2($username) << 21;
1.443     albertel 6677: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6678: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6679: 	
                   6680: 	my $num1=$symbchck+$symbseed+$namechck;
                   6681: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6682: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6683: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 6684: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6685: 	
1.503     albertel 6686: 	return "$num1:$num2";
1.443     albertel 6687:     }
                   6688: }
                   6689: 
1.575     albertel 6690: sub rndseed_64bit4 {
                   6691:     my ($symb,$courseid,$domain,$username)=@_;
                   6692:     {
                   6693: 	use integer;
                   6694: 	# strings need to be an even # of cahracters long, it it is odd the
                   6695:         # last characters gets thrown away
                   6696: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6697: 	my $symbseed=numval3($symb) << 10;
                   6698: 	my $namechck=unpack("%32S*",$username.' ');
                   6699: 	
                   6700: 	my $nameseed=numval3($username) << 21;
                   6701: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6702: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6703: 	
                   6704: 	my $num1=$symbchck+$symbseed+$namechck;
                   6705: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6706: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6707: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 6708: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6709: 	
                   6710: 	return "$num1:$num2";
                   6711:     }
                   6712: }
                   6713: 
1.675     albertel 6714: sub rndseed_64bit5 {
                   6715:     my ($symb,$courseid,$domain,$username)=@_;
                   6716:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   6717:     return "$num1:$num2";
                   6718: }
                   6719: 
1.366     albertel 6720: sub rndseed_CODE_64bit {
                   6721:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 6722:     {
1.366     albertel 6723: 	use integer;
1.443     albertel 6724: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 6725: 	my $symbseed=numval2($symb);
1.491     albertel 6726: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   6727: 	my $CODEseed=numval(&getCODE());
1.443     albertel 6728: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 6729: 	my $num1=$symbseed+$CODEchck;
                   6730: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 6731: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   6732: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 6733: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   6734: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 6735: 	return "$num1:$num2";
1.366     albertel 6736:     }
                   6737: }
                   6738: 
1.575     albertel 6739: sub rndseed_CODE_64bit4 {
                   6740:     my ($symb,$courseid,$domain,$username)=@_;
                   6741:     {
                   6742: 	use integer;
                   6743: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   6744: 	my $symbseed=numval3($symb);
                   6745: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   6746: 	my $CODEseed=numval3(&getCODE());
                   6747: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6748: 	my $num1=$symbseed+$CODEchck;
                   6749: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 6750: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   6751: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 6752: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   6753: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   6754: 	return "$num1:$num2";
                   6755:     }
                   6756: }
                   6757: 
1.675     albertel 6758: sub rndseed_CODE_64bit5 {
                   6759:     my ($symb,$courseid,$domain,$username)=@_;
                   6760:     my $code = &getCODE();
                   6761:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   6762:     return "$num1:$num2";
                   6763: }
                   6764: 
1.366     albertel 6765: sub setup_random_from_rndseed {
                   6766:     my ($rndseed)=@_;
1.503     albertel 6767:     if ($rndseed =~/([,:])/) {
                   6768: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 6769: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   6770:     } else {
                   6771: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 6772:     }
1.36      albertel 6773: }
                   6774: 
1.474     albertel 6775: sub latest_receipt_algorithm_id {
                   6776:     return 'receipt2';
                   6777: }
                   6778: 
1.480     www      6779: sub recunique {
                   6780:     my $fucourseid=shift;
                   6781:     my $unique;
1.620     albertel 6782:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   6783: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      6784:     } else {
                   6785: 	$unique=$perlvar{'lonReceipt'};
                   6786:     }
                   6787:     return unpack("%32C*",$unique);
                   6788: }
                   6789: 
                   6790: sub recprefix {
                   6791:     my $fucourseid=shift;
                   6792:     my $prefix;
1.620     albertel 6793:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   6794: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      6795:     } else {
                   6796: 	$prefix=$perlvar{'lonHostID'};
                   6797:     }
                   6798:     return unpack("%32C*",$prefix);
                   6799: }
                   6800: 
1.76      www      6801: sub ireceipt {
1.474     albertel 6802:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.76      www      6803:     my $cuname=unpack("%32C*",$funame);
                   6804:     my $cudom=unpack("%32C*",$fudom);
                   6805:     my $cucourseid=unpack("%32C*",$fucourseid);
                   6806:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      6807:     my $cunique=&recunique($fucourseid);
1.474     albertel 6808:     my $cpart=unpack("%32S*",$part);
1.480     www      6809:     my $return =&recprefix($fucourseid).'-';
1.620     albertel 6810:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   6811: 	$env{'request.state'} eq 'construct') {
1.790     albertel 6812: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 6813: 			       
                   6814: 	$return.= ($cunique%$cuname+
                   6815: 		   $cunique%$cudom+
                   6816: 		   $cusymb%$cuname+
                   6817: 		   $cusymb%$cudom+
                   6818: 		   $cucourseid%$cuname+
                   6819: 		   $cucourseid%$cudom+
                   6820: 		   $cpart%$cuname+
                   6821: 		   $cpart%$cudom);
                   6822:     } else {
                   6823: 	$return.= ($cunique%$cuname+
                   6824: 		   $cunique%$cudom+
                   6825: 		   $cusymb%$cuname+
                   6826: 		   $cusymb%$cudom+
                   6827: 		   $cucourseid%$cuname+
                   6828: 		   $cucourseid%$cudom);
                   6829:     }
                   6830:     return $return;
1.76      www      6831: }
                   6832: 
                   6833: sub receipt {
1.474     albertel 6834:     my ($part)=@_;
1.790     albertel 6835:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 6836:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      6837: }
1.260     ng       6838: 
1.790     albertel 6839: sub whichuser {
                   6840:     my ($passedsymb)=@_;
                   6841:     my ($symb,$courseid,$domain,$name,$publicuser);
                   6842:     if (defined($env{'form.grade_symb'})) {
                   6843: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   6844: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   6845: 	if (!$allowed &&
                   6846: 	    exists($env{'request.course.sec'}) &&
                   6847: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   6848: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   6849: 			      '/'.$env{'request.course.sec'});
                   6850: 	}
                   6851: 	if ($allowed) {
                   6852: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   6853: 	    $courseid=$tmp_courseid;
                   6854: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   6855: 	    ($name)=&get_env_multiple('form.grade_username');
                   6856: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   6857: 	}
                   6858:     }
                   6859:     if (!$passedsymb) {
                   6860: 	$symb=&symbread();
                   6861:     } else {
                   6862: 	$symb=$passedsymb;
                   6863:     }
                   6864:     $courseid=$env{'request.course.id'};
                   6865:     $domain=$env{'user.domain'};
                   6866:     $name=$env{'user.name'};
                   6867:     if ($name eq 'public' && $domain eq 'public') {
                   6868: 	if (!defined($env{'form.username'})) {
                   6869: 	    $env{'form.username'}.=time.rand(10000000);
                   6870: 	}
                   6871: 	$name.=$env{'form.username'};
                   6872:     }
                   6873:     return ($symb,$courseid,$domain,$name,$publicuser);
                   6874: 
                   6875: }
                   6876: 
1.36      albertel 6877: # ------------------------------------------------------------ Serves up a file
1.472     albertel 6878: # returns either the contents of the file or 
                   6879: # -1 if the file doesn't exist
1.481     raeburn  6880: #
                   6881: # if the target is a file that was uploaded via DOCS, 
                   6882: # a check will be made to see if a current copy exists on the local server,
                   6883: # if it does this will be served, otherwise a copy will be retrieved from
                   6884: # the home server for the course and stored in /home/httpd/html/userfiles on
                   6885: # the local server.   
1.472     albertel 6886: 
1.36      albertel 6887: sub getfile {
1.538     albertel 6888:     my ($file) = @_;
1.609     banghart 6889:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 6890:     &repcopy($file);
                   6891:     return &readfile($file);
                   6892: }
                   6893: 
                   6894: sub repcopy_userfile {
                   6895:     my ($file)=@_;
1.609     banghart 6896:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 6897:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 6898:     my ($cdom,$cnum,$filename) = 
                   6899: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+([^/]+)/+([^/]+)/+(.*)|);
                   6900:     my ($info,$rtncode);
                   6901:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   6902:     if (-e "$file") {
                   6903: 	my @fileinfo = stat($file);
                   6904: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 6905: 	if ($lwpresp ne 'ok') {
                   6906: 	    if ($rtncode eq '404') {
1.538     albertel 6907: 		unlink($file);
1.482     albertel 6908: 	    }
1.517     albertel 6909: 	    #my $ua=new LWP::UserAgent;
1.538     albertel 6910: 	    #my $request=new HTTP::Request('GET',&tokenwrapper($uri));
1.517     albertel 6911: 	    #my $response=$ua->request($request);
                   6912: 	    #if ($response->is_success()) {
                   6913: 	#	return $response->content;
                   6914: 	#    } else {
                   6915: 	#	return -1;
                   6916: 	#    }
1.482     albertel 6917: 	    return -1;
                   6918: 	}
                   6919: 	if ($info < $fileinfo[9]) {
1.607     raeburn  6920: 	    return 'ok';
1.482     albertel 6921: 	}
                   6922: 	$info = '';
1.538     albertel 6923: 	$lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 6924: 	if ($lwpresp ne 'ok') {
                   6925: 	    return -1;
                   6926: 	}
                   6927:     } else {
1.538     albertel 6928: 	my $lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 6929: 	if ($lwpresp ne 'ok') {
1.517     albertel 6930: 	    my $ua=new LWP::UserAgent;
1.538     albertel 6931: 	    my $request=new HTTP::Request('GET',&tokenwrapper($uri));
1.517     albertel 6932: 	    my $response=$ua->request($request);
                   6933: 	    if ($response->is_success()) {
1.538     albertel 6934: 		$info=$response->content;
1.517     albertel 6935: 	    } else {
                   6936: 		return -1;
                   6937: 	    }
1.482     albertel 6938: 	}
                   6939: 	my @parts = ($cdom,$cnum); 
                   6940: 	if ($filename =~ m|^(.+)/[^/]+$|) {
                   6941: 	    push @parts, split(/\//,$1);
1.518     albertel 6942: 	}
1.538     albertel 6943: 	my $path = $perlvar{'lonDocRoot'}.'/userfiles';
1.482     albertel 6944: 	foreach my $part (@parts) {
                   6945: 	    $path .= '/'.$part;
                   6946: 	    if (!-e $path) {
                   6947: 		mkdir($path,0770);
                   6948: 	    }
                   6949: 	}
                   6950:     }
1.538     albertel 6951:     open(FILE,">$file");
1.482     albertel 6952:     print FILE $info;
                   6953:     close(FILE);
1.607     raeburn  6954:     return 'ok';
1.481     raeburn  6955: }
                   6956: 
1.517     albertel 6957: sub tokenwrapper {
                   6958:     my $uri=shift;
1.552     albertel 6959:     $uri=~s|^http\://([^/]+)||;
                   6960:     $uri=~s|^/||;
1.620     albertel 6961:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 6962:     my $token=$1;
1.552     albertel 6963:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   6964:     if ($udom && $uname && $file) {
                   6965: 	$file=~s|(\?\.*)*$||;
1.620     albertel 6966:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
1.552     albertel 6967:         return 'http://'.$hostname{ &homeserver($uname,$udom)}.'/'.$uri.
1.517     albertel 6968:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   6969:                                '&tokenissued='.$perlvar{'lonHostID'};
                   6970:     } else {
                   6971:         return '/adm/notfound.html';
                   6972:     }
                   6973: }
                   6974: 
1.481     raeburn  6975: sub getuploaded {
                   6976:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   6977:     $uri=~s/^\///;
                   6978:     $uri = 'http://'.$hostname{ &homeserver($cnum,$cdom)}.'/raw/'.$uri;
                   6979:     my $ua=new LWP::UserAgent;
                   6980:     my $request=new HTTP::Request($reqtype,$uri);
                   6981:     my $response=$ua->request($request);
                   6982:     $$rtncode = $response->code;
1.482     albertel 6983:     if (! $response->is_success()) {
                   6984: 	return 'failed';
                   6985:     }      
                   6986:     if ($reqtype eq 'HEAD') {
1.486     www      6987: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 6988:     } elsif ($reqtype eq 'GET') {
                   6989: 	$$info = $response->content;
1.472     albertel 6990:     }
1.482     albertel 6991:     return 'ok';
1.36      albertel 6992: }
                   6993: 
1.481     raeburn  6994: sub readfile {
                   6995:     my $file = shift;
                   6996:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   6997:     my $fh;
                   6998:     open($fh,"<$file");
                   6999:     my $a='';
                   7000:     while (<$fh>) { $a .=$_; }
                   7001:     return $a;
                   7002: }
                   7003: 
1.36      albertel 7004: sub filelocation {
1.590     banghart 7005:     my ($dir,$file) = @_;
                   7006:     my $location;
                   7007:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 7008: 
                   7009:     if ($file =~ m-^/adm/-) {
                   7010: 	$file=~s-^/adm/wrapper/-/-;
                   7011: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   7012:     }
1.590     banghart 7013:     if ($file=~m:^/~:) { # is a contruction space reference
                   7014:         $location = $file;
                   7015:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.649     albertel 7016:     } elsif ($file=~m:^/home/[^/]*/public_html/:) {
                   7017: 	# is a correct contruction space reference
                   7018:         $location = $file;
1.609     banghart 7019:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 7020:         my ($udom,$uname,$filename)=
1.609     banghart 7021:   	    ($file=~m -^/+(?:uploaded|editupload)/+([^/]+)/+([^/]+)/+(.*)$-);
1.590     banghart 7022:         my $home=&homeserver($uname,$udom);
                   7023:         my $is_me=0;
                   7024:         my @ids=&current_machine_ids();
                   7025:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   7026:         if ($is_me) {
1.740     www      7027:   	    $location=&propath($udom,$uname).
1.590     banghart 7028:   	      '/userfiles/'.$filename;
                   7029:         } else {
                   7030:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   7031:   	      $udom.'/'.$uname.'/'.$filename;
                   7032:         }
                   7033:     } else {
                   7034:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   7035:         $file=~s:^/res/:/:;
                   7036:         if ( !( $file =~ m:^/:) ) {
                   7037:             $location = $dir. '/'.$file;
                   7038:         } else {
                   7039:             $location = '/home/httpd/html/res'.$file;
                   7040:         }
1.59      albertel 7041:     }
1.590     banghart 7042:     $location=~s://+:/:g; # remove duplicate /
                   7043:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
                   7044:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   7045:     return $location;
1.46      www      7046: }
1.36      albertel 7047: 
1.46      www      7048: sub hreflocation {
                   7049:     my ($dir,$file)=@_;
1.460     albertel 7050:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666     albertel 7051: 	$file=filelocation($dir,$file);
1.700     albertel 7052:     } elsif ($file=~m-^/adm/-) {
                   7053: 	$file=~s-^/adm/wrapper/-/-;
                   7054: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 7055:     }
                   7056:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   7057: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   7058:     } elsif ($file=~m-/home/(\w+)/public_html/-) {
1.462     albertel 7059: 	$file=~s-^/home/(\w+)/public_html/-/~$1/-;
1.666     albertel 7060:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
                   7061: 	$file=~s-^/home/httpd/lonUsers/([^/]*)/./././([^/]*)/userfiles/
                   7062: 	    -/uploaded/$1/$2/-x;
1.46      www      7063:     }
1.462     albertel 7064:     return $file;
1.465     albertel 7065: }
                   7066: 
                   7067: sub current_machine_domains {
                   7068:     my $hostname=$hostname{$perlvar{'lonHostID'}};
                   7069:     my @domains;
                   7070:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  7071: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 7072: 	if ($hostname eq $name) {
                   7073: 	    push(@domains,$hostdom{$id});
                   7074: 	}
                   7075:     }
                   7076:     return @domains;
                   7077: }
                   7078: 
                   7079: sub current_machine_ids {
                   7080:     my $hostname=$hostname{$perlvar{'lonHostID'}};
                   7081:     my @ids;
                   7082:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  7083: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 7084: 	if ($hostname eq $name) {
                   7085: 	    push(@ids,$id);
                   7086: 	}
                   7087:     }
                   7088:     return @ids;
1.31      www      7089: }
                   7090: 
                   7091: # ------------------------------------------------------------- Declutters URLs
                   7092: 
                   7093: sub declutter {
                   7094:     my $thisfn=shift;
1.569     albertel 7095:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 7096:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      7097:     $thisfn=~s/^\///;
1.697     albertel 7098:     $thisfn=~s|^adm/wrapper/||;
                   7099:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      7100:     $thisfn=~s/^res\///;
1.235     www      7101:     $thisfn=~s/\?.+$//;
1.268     www      7102:     return $thisfn;
                   7103: }
                   7104: 
                   7105: # ------------------------------------------------------------- Clutter up URLs
                   7106: 
                   7107: sub clutter {
                   7108:     my $thisfn='/'.&declutter(shift);
1.609     banghart 7109:     unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) { 
1.270     www      7110:        $thisfn='/res'.$thisfn; 
                   7111:     }
1.694     albertel 7112:     if ($thisfn !~m|/adm|) {
1.695     albertel 7113: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 7114: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 7115: 	} else {
                   7116: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   7117: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 7118: 	    if ($embstyle eq 'ssi'
                   7119: 		|| ($embstyle eq 'hdn')
                   7120: 		|| ($embstyle eq 'rat')
                   7121: 		|| ($embstyle eq 'prv')
                   7122: 		|| ($embstyle eq 'ign')) {
                   7123: 		#do nothing with these
                   7124: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 7125: 		|| ($embstyle eq 'emb')
                   7126: 		|| ($embstyle eq 'wrp')) {
                   7127: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 7128: 	    } elsif ($embstyle eq 'unk'
                   7129: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 7130: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 7131: 	    } else {
1.718     www      7132: #		&logthis("Got a blank emb style");
1.695     albertel 7133: 	    }
1.694     albertel 7134: 	}
                   7135:     }
1.31      www      7136:     return $thisfn;
1.12      www      7137: }
                   7138: 
1.787     albertel 7139: sub clutter_with_no_wrapper {
                   7140:     my $uri = &clutter(shift);
                   7141:     if ($uri =~ m-^/adm/-) {
                   7142: 	$uri =~ s-^/adm/wrapper/-/-;
                   7143: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   7144:     }
                   7145:     return $uri;
                   7146: }
                   7147: 
1.557     albertel 7148: sub freeze_escape {
                   7149:     my ($value)=@_;
                   7150:     if (ref($value)) {
                   7151: 	$value=&nfreeze($value);
                   7152: 	return '__FROZEN__'.&escape($value);
                   7153:     }
                   7154:     return &escape($value);
                   7155: }
                   7156: 
1.11      www      7157: 
1.557     albertel 7158: sub thaw_unescape {
                   7159:     my ($value)=@_;
                   7160:     if ($value =~ /^__FROZEN__/) {
                   7161: 	substr($value,0,10,undef);
                   7162: 	$value=&unescape($value);
                   7163: 	return &thaw($value);
                   7164:     }
                   7165:     return &unescape($value);
                   7166: }
                   7167: 
1.436     albertel 7168: sub correct_line_ends {
                   7169:     my ($result)=@_;
                   7170:     $$result =~s/\r\n/\n/mg;
                   7171:     $$result =~s/\r/\n/mg;
1.415     albertel 7172: }
1.1       albertel 7173: # ================================================================ Main Program
                   7174: 
1.184     www      7175: sub goodbye {
1.204     albertel 7176:    &logthis("Starting Shut down");
1.443     albertel 7177: #not converted to using infrastruture and probably shouldn't be
1.599     albertel 7178:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&freeze(\%badServerCache))));
1.443     albertel 7179: #converted
1.599     albertel 7180: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
                   7181:    &logthis(sprintf("%-20s is %s",'%homecache',length(&freeze(\%homecache))));
                   7182: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&freeze(\%titlecache))));
                   7183: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&freeze(\%courseresdatacache))));
1.425     albertel 7184: #1.1 only
1.599     albertel 7185: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&freeze(\%userresdatacache))));
                   7186: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&freeze(\%getsectioncache))));
                   7187: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&freeze(\%courseresversioncache))));
                   7188: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&freeze(\%resversioncache))));
                   7189:    &logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
                   7190:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   7191:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      7192:    &flushcourselogs();
                   7193:    &logthis("Shutting down");
                   7194: }
                   7195: 
1.179     www      7196: BEGIN {
1.228     harris41 7197: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
1.195     www      7198:     unless ($readit) {
1.217     harris41 7199: {
1.781     raeburn  7200:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   7201:     %perlvar = (%perlvar,%{$configvars});
1.227     harris41 7202: }
1.1       albertel 7203: 
1.327     albertel 7204: # ------------------------------------------------------------ Read domain file
                   7205: {
                   7206:     %domaindescription = ();
                   7207:     %domain_auth_def = ();
                   7208:     %domain_auth_arg_def = ();
1.448     albertel 7209:     my $fh;
                   7210:     if (open($fh,"<".$Apache::lonnet::perlvar{'lonTabDir'}.'/domain.tab')) {
1.327     albertel 7211:        while (<$fh>) {
1.390     matthew  7212:            next if (/^(\#|\s*$)/);
                   7213: #           next if /^\#/;
1.327     albertel 7214:            chomp;
1.403     www      7215:            my ($domain, $domain_description, $def_auth, $def_auth_arg,
1.685     raeburn  7216: 	       $def_lang, $city, $longi, $lati, $primary) = split(/:/,$_);
1.403     www      7217: 	   $domain_auth_def{$domain}=$def_auth;
1.327     albertel 7218:            $domain_auth_arg_def{$domain}=$def_auth_arg;
1.403     www      7219: 	   $domaindescription{$domain}=$domain_description;
                   7220: 	   $domain_lang_def{$domain}=$def_lang;
                   7221: 	   $domain_city{$domain}=$city;
                   7222: 	   $domain_longi{$domain}=$longi;
                   7223: 	   $domain_lati{$domain}=$lati;
1.685     raeburn  7224:            $domain_primary{$domain}=$primary;
1.403     www      7225: 
1.448     albertel 7226:  #         &logthis("Domain.tab: $domain, $domain_auth_def{$domain}, $domain_auth_arg_def{$domain},$domaindescription{$domain}");
1.327     albertel 7227: #          &logthis("Domain.tab: $domain ".$domaindescription{$domain} );
1.448     albertel 7228: 	}
1.327     albertel 7229:     }
1.448     albertel 7230:     close ($fh);
1.327     albertel 7231: }
                   7232: 
                   7233: 
1.1       albertel 7234: # ------------------------------------------------------------- Read hosts file
                   7235: {
1.448     albertel 7236:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
1.1       albertel 7237: 
                   7238:     while (my $configline=<$config>) {
1.303     matthew  7239:        next if ($configline =~ /^(\#|\s*$)/);
1.154     www      7240:        chomp($configline);
1.595     albertel 7241:        my ($id,$domain,$role,$name)=split(/:/,$configline);
1.597     albertel 7242:        $name=~s/\s//g;
1.595     albertel 7243:        if ($id && $domain && $role && $name) {
1.252     albertel 7244: 	 $hostname{$id}=$name;
                   7245: 	 $hostdom{$id}=$domain;
                   7246: 	 if ($role eq 'library') { $libserv{$id}=$name; }
1.245     www      7247:        }
1.1       albertel 7248:     }
1.448     albertel 7249:     close($config);
1.619     albertel 7250:     # FIXME: dev server don't want this, production servers _do_ want this
1.654     albertel 7251:     #&get_iphost();
1.1       albertel 7252: }
                   7253: 
1.598     albertel 7254: sub get_iphost {
                   7255:     if (%iphost) { return %iphost; }
1.653     albertel 7256:     my %name_to_ip;
1.598     albertel 7257:     foreach my $id (keys(%hostname)) {
                   7258: 	my $name=$hostname{$id};
1.653     albertel 7259: 	my $ip;
                   7260: 	if (!exists($name_to_ip{$name})) {
                   7261: 	    $ip = gethostbyname($name);
                   7262: 	    if (!$ip || length($ip) ne 4) {
                   7263: 		&logthis("Skipping host $id name $name no IP found\n");
                   7264: 		next;
                   7265: 	    }
                   7266: 	    $ip=inet_ntoa($ip);
                   7267: 	    $name_to_ip{$name} = $ip;
                   7268: 	} else {
                   7269: 	    $ip = $name_to_ip{$name};
1.598     albertel 7270: 	}
                   7271: 	push(@{$iphost{$ip}},$id);
                   7272:     }
                   7273:     return %iphost;
                   7274: }
                   7275: 
1.1       albertel 7276: # ------------------------------------------------------ Read spare server file
                   7277: {
1.448     albertel 7278:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 7279: 
                   7280:     while (my $configline=<$config>) {
                   7281:        chomp($configline);
1.284     matthew  7282:        if ($configline) {
1.784     albertel 7283: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 7284: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 7285: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 7286:        }
                   7287:     }
1.448     albertel 7288:     close($config);
1.1       albertel 7289: }
1.11      www      7290: # ------------------------------------------------------------ Read permissions
                   7291: {
1.448     albertel 7292:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      7293: 
                   7294:     while (my $configline=<$config>) {
1.448     albertel 7295: 	chomp($configline);
                   7296: 	if ($configline) {
                   7297: 	    my ($role,$perm)=split(/ /,$configline);
                   7298: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   7299: 	}
1.11      www      7300:     }
1.448     albertel 7301:     close($config);
1.11      www      7302: }
                   7303: 
                   7304: # -------------------------------------------- Read plain texts for permissions
                   7305: {
1.448     albertel 7306:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      7307: 
                   7308:     while (my $configline=<$config>) {
1.448     albertel 7309: 	chomp($configline);
                   7310: 	if ($configline) {
1.742     raeburn  7311: 	    my ($short,@plain)=split(/:/,$configline);
                   7312:             %{$prp{$short}} = ();
                   7313: 	    if (@plain > 0) {
                   7314:                 $prp{$short}{'std'} = $plain[0];
                   7315:                 for (my $i=1; $i<@plain; $i++) {
                   7316:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   7317:                 }
                   7318:             }
1.448     albertel 7319: 	}
1.135     www      7320:     }
1.448     albertel 7321:     close($config);
1.135     www      7322: }
                   7323: 
                   7324: # ---------------------------------------------------------- Read package table
                   7325: {
1.448     albertel 7326:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      7327: 
                   7328:     while (my $configline=<$config>) {
1.483     albertel 7329: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 7330: 	chomp($configline);
                   7331: 	my ($short,$plain)=split(/:/,$configline);
                   7332: 	my ($pack,$name)=split(/\&/,$short);
                   7333: 	if ($plain ne '') {
                   7334: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   7335: 	    $packagetab{$short}=$plain; 
                   7336: 	}
1.11      www      7337:     }
1.448     albertel 7338:     close($config);
1.329     matthew  7339: }
                   7340: 
                   7341: # ------------- set up temporary directory
                   7342: {
                   7343:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   7344: 
1.11      www      7345: }
                   7346: 
1.794     albertel 7347: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   7348: 				'compress_threshold'=> 20_000,
                   7349:  			        });
1.185     www      7350: 
1.281     www      7351: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      7352: $dumpcount=0;
1.22      www      7353: 
1.163     harris41 7354: &logtouch();
1.672     albertel 7355: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      7356: $readit=1;
1.564     albertel 7357:     {
                   7358: 	use integer;
                   7359: 	my $test=(2**32)+1;
1.568     albertel 7360: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 7361: 	&logthis(" Detected 64bit platform ($_64bit)");
                   7362:     }
1.195     www      7363: }
1.1       albertel 7364: }
1.179     www      7365: 
1.1       albertel 7366: 1;
1.191     harris41 7367: __END__
                   7368: 
1.243     albertel 7369: =pod
                   7370: 
1.191     harris41 7371: =head1 NAME
                   7372: 
1.243     albertel 7373: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 7374: 
                   7375: =head1 SYNOPSIS
                   7376: 
1.243     albertel 7377: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 7378: 
                   7379:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   7380: 
1.243     albertel 7381: Common parameters:
                   7382: 
                   7383: =over 4
                   7384: 
                   7385: =item *
                   7386: 
                   7387: $uname : an internal username (if $cname expecting a course Id specifically)
                   7388: 
                   7389: =item *
                   7390: 
                   7391: $udom : a domain (if $cdom expecting a course's domain specifically)
                   7392: 
                   7393: =item *
                   7394: 
                   7395: $symb : a resource instance identifier
                   7396: 
                   7397: =item *
                   7398: 
                   7399: $namespace : the name of a .db file that contains the data needed or
                   7400: being set.
                   7401: 
                   7402: =back
                   7403: 
1.394     bowersj2 7404: =head1 OVERVIEW
1.191     harris41 7405: 
1.394     bowersj2 7406: lonnet provides subroutines which interact with the
                   7407: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   7408: about classes, users, and resources.
1.243     albertel 7409: 
                   7410: For many of these objects you can also use this to store data about
                   7411: them or modify them in various ways.
1.191     harris41 7412: 
1.394     bowersj2 7413: =head2 Symbs
1.191     harris41 7414: 
1.394     bowersj2 7415: To identify a specific instance of a resource, LON-CAPA uses symbols
                   7416: or "symbs"X<symb>. These identifiers are built from the URL of the
                   7417: map, the resource number of the resource in the map, and the URL of
                   7418: the resource itself. The latter is somewhat redundant, but might help
                   7419: if maps change.
                   7420: 
                   7421: An example is
                   7422: 
                   7423:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   7424: 
                   7425: The respective map entry is
                   7426: 
                   7427:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   7428:   title="Problem 2">
                   7429:  </resource>
                   7430: 
                   7431: Symbs are used by the random number generator, as well as to store and
                   7432: restore data specific to a certain instance of for example a problem.
                   7433: 
                   7434: =head2 Storing And Retrieving Data
                   7435: 
                   7436: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   7437: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   7438: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   7439: is is the non-critical message twin of cstore. These functions are for
                   7440: handlers to store a perl hash to a user's permanent data space in an
                   7441: easy manner, and to retrieve it again on another call. It is expected
                   7442: that a handler would use this once at the beginning to retrieve data,
                   7443: and then again once at the end to send only the new data back.
                   7444: 
                   7445: The data is stored in the user's data directory on the user's
                   7446: homeserver under the ID of the course.
                   7447: 
                   7448: The hash that is returned by restore will have all of the previous
                   7449: value for all of the elements of the hash.
                   7450: 
                   7451: Example:
                   7452: 
                   7453:  #creating a hash
                   7454:  my %hash;
                   7455:  $hash{'foo'}='bar';
                   7456: 
                   7457:  #storing it
                   7458:  &Apache::lonnet::cstore(\%hash);
                   7459: 
                   7460:  #changing a value
                   7461:  $hash{'foo'}='notbar';
                   7462: 
                   7463:  #adding a new value
                   7464:  $hash{'bar'}='foo';
                   7465:  &Apache::lonnet::cstore(\%hash);
                   7466: 
                   7467:  #retrieving the hash
                   7468:  my %history=&Apache::lonnet::restore();
                   7469: 
                   7470:  #print the hash
                   7471:  foreach my $key (sort(keys(%history))) {
                   7472:    print("\%history{$key} = $history{$key}");
                   7473:  }
                   7474: 
                   7475: Will print out:
1.191     harris41 7476: 
1.394     bowersj2 7477:  %history{1:foo} = bar
                   7478:  %history{1:keys} = foo:timestamp
                   7479:  %history{1:timestamp} = 990455579
                   7480:  %history{2:bar} = foo
                   7481:  %history{2:foo} = notbar
                   7482:  %history{2:keys} = foo:bar:timestamp
                   7483:  %history{2:timestamp} = 990455580
                   7484:  %history{bar} = foo
                   7485:  %history{foo} = notbar
                   7486:  %history{timestamp} = 990455580
                   7487:  %history{version} = 2
                   7488: 
                   7489: Note that the special hash entries C<keys>, C<version> and
                   7490: C<timestamp> were added to the hash. C<version> will be equal to the
                   7491: total number of versions of the data that have been stored. The
                   7492: C<timestamp> attribute will be the UNIX time the hash was
                   7493: stored. C<keys> is available in every historical section to list which
                   7494: keys were added or changed at a specific historical revision of a
                   7495: hash.
                   7496: 
                   7497: B<Warning>: do not store the hash that restore returns directly. This
                   7498: will cause a mess since it will restore the historical keys as if the
                   7499: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 7500: 
1.394     bowersj2 7501: Calling convention:
1.191     harris41 7502: 
1.394     bowersj2 7503:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   7504:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 7505: 
1.394     bowersj2 7506: For more detailed information, see lonnet specific documentation.
1.191     harris41 7507: 
1.394     bowersj2 7508: =head1 RETURN MESSAGES
1.191     harris41 7509: 
1.394     bowersj2 7510: =over 4
1.191     harris41 7511: 
1.394     bowersj2 7512: =item * B<con_lost>: unable to contact remote host
1.191     harris41 7513: 
1.394     bowersj2 7514: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   7515: when the connection is brought back up
1.191     harris41 7516: 
1.394     bowersj2 7517: =item * B<con_failed>: unable to contact remote host and unable to save message
                   7518: for later delivery
1.191     harris41 7519: 
1.394     bowersj2 7520: =item * B<error:>: an error a occured, a description of the error follows the :
1.191     harris41 7521: 
1.394     bowersj2 7522: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 7523: that was requested
1.191     harris41 7524: 
1.243     albertel 7525: =back
1.191     harris41 7526: 
1.243     albertel 7527: =head1 PUBLIC SUBROUTINES
1.191     harris41 7528: 
1.243     albertel 7529: =head2 Session Environment Functions
1.191     harris41 7530: 
1.243     albertel 7531: =over 4
1.191     harris41 7532: 
1.394     bowersj2 7533: =item * 
                   7534: X<appenv()>
                   7535: B<appenv(%hash)>: the value of %hash is written to
                   7536: the user envirnoment file, and will be restored for each access this
1.620     albertel 7537: user makes during this session, also modifies the %env for the current
1.394     bowersj2 7538: process
1.191     harris41 7539: 
                   7540: =item *
1.394     bowersj2 7541: X<delenv()>
                   7542: B<delenv($regexp)>: removes all items from the session
                   7543: environment file that matches the regular expression in $regexp. The
1.620     albertel 7544: values are also delted from the current processes %env.
1.191     harris41 7545: 
1.795     albertel 7546: =item * get_env_multiple($name) 
                   7547: 
                   7548: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   7549: values may be defined and end up as an array ref.
                   7550: 
                   7551: returns an array of values
                   7552: 
1.243     albertel 7553: =back
                   7554: 
                   7555: =head2 User Information
1.191     harris41 7556: 
1.243     albertel 7557: =over 4
1.191     harris41 7558: 
                   7559: =item *
1.394     bowersj2 7560: X<queryauthenticate()>
                   7561: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 7562: authentication scheme
                   7563: 
                   7564: =item *
1.394     bowersj2 7565: X<authenticate()>
                   7566: B<authenticate($uname,$upass,$udom)>: try to
                   7567: authenticate user from domain's lib servers (first use the current
                   7568: one). C<$upass> should be the users password.
1.191     harris41 7569: 
                   7570: =item *
1.394     bowersj2 7571: X<homeserver()>
                   7572: B<homeserver($uname,$udom)>: find the server which has
                   7573: the user's directory and files (there must be only one), this caches
                   7574: the answer, and also caches if there is a borken connection.
1.191     harris41 7575: 
                   7576: =item *
1.394     bowersj2 7577: X<idget()>
                   7578: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   7579: (IDs are a unique resource in a domain, there must be only 1 ID per
                   7580: username, and only 1 username per ID in a specific domain) (returns
                   7581: hash: id=>name,id=>name)
1.191     harris41 7582: 
                   7583: =item *
1.394     bowersj2 7584: X<idrget()>
                   7585: B<idrget($udom,@unames)>: find the IDs behind a list of
                   7586: usernames (returns hash: name=>id,name=>id)
1.191     harris41 7587: 
                   7588: =item *
1.394     bowersj2 7589: X<idput()>
                   7590: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 7591: 
                   7592: =item *
1.394     bowersj2 7593: X<rolesinit()>
                   7594: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 7595: 
                   7596: =item *
1.551     albertel 7597: X<getsection()>
                   7598: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 7599: course $cname, return section name/number or '' for "not in course"
                   7600: and '-1' for "no section"
                   7601: 
                   7602: =item *
1.394     bowersj2 7603: X<userenvironment()>
                   7604: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 7605: passed in @what from the requested user's environment, returns a hash
                   7606: 
                   7607: =back
                   7608: 
                   7609: =head2 User Roles
                   7610: 
                   7611: =over 4
                   7612: 
                   7613: =item *
                   7614: 
                   7615: allowed($priv,$uri) : check for a user privilege; returns codes for allowed
                   7616: actions
                   7617:  F: full access
                   7618:  U,I,K: authentication modes (cxx only)
                   7619:  '': forbidden
                   7620:  1: user needs to choose course
                   7621:  2: browse allowed
1.766     albertel 7622:  A: passphrase authentication needed
1.243     albertel 7623: 
                   7624: =item *
                   7625: 
                   7626: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   7627: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   7628: and course level
                   7629: 
                   7630: =item *
                   7631: 
                   7632: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   7633: explanation of a user role term
                   7634: 
                   7635: =back
                   7636: 
                   7637: =head2 User Modification
                   7638: 
                   7639: =over 4
                   7640: 
                   7641: =item *
                   7642: 
                   7643: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
                   7644: user for the level given by URL.  Optional start and end dates (leave empty
                   7645: string or zero for "no date")
1.191     harris41 7646: 
                   7647: =item *
                   7648: 
1.243     albertel 7649: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   7650: change a users, password, possible return values are: ok,
                   7651: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   7652: refused
1.191     harris41 7653: 
                   7654: =item *
                   7655: 
1.243     albertel 7656: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 7657: 
                   7658: =item *
                   7659: 
1.243     albertel 7660: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
                   7661: modify user
1.191     harris41 7662: 
                   7663: =item *
                   7664: 
1.286     matthew  7665: modifystudent
                   7666: 
                   7667: modify a students enrollment and identification information.
                   7668: The course id is resolved based on the current users environment.  
                   7669: This means the envoking user must be a course coordinator or otherwise
                   7670: associated with a course.
                   7671: 
1.297     matthew  7672: This call is essentially a wrapper for lonnet::modifyuser and
                   7673: lonnet::modify_student_enrollment
1.286     matthew  7674: 
                   7675: Inputs: 
                   7676: 
                   7677: =over 4
                   7678: 
                   7679: =item B<$udom> Students loncapa domain
                   7680: 
                   7681: =item B<$uname> Students loncapa login name
                   7682: 
                   7683: =item B<$uid> Students id/student number
                   7684: 
                   7685: =item B<$umode> Students authentication mode
                   7686: 
                   7687: =item B<$upass> Students password
                   7688: 
                   7689: =item B<$first> Students first name
                   7690: 
                   7691: =item B<$middle> Students middle name
                   7692: 
                   7693: =item B<$last> Students last name
                   7694: 
                   7695: =item B<$gene> Students generation
                   7696: 
                   7697: =item B<$usec> Students section in course
                   7698: 
                   7699: =item B<$end> Unix time of the roles expiration
                   7700: 
                   7701: =item B<$start> Unix time of the roles start date
                   7702: 
                   7703: =item B<$forceid> If defined, allow $uid to be changed
                   7704: 
                   7705: =item B<$desiredhome> server to use as home server for student
                   7706: 
                   7707: =back
1.297     matthew  7708: 
                   7709: =item *
                   7710: 
                   7711: modify_student_enrollment
                   7712: 
                   7713: Change a students enrollment status in a class.  The environment variable
                   7714: 'role.request.course' must be defined for this function to proceed.
                   7715: 
                   7716: Inputs:
                   7717: 
                   7718: =over 4
                   7719: 
                   7720: =item $udom, students domain
                   7721: 
                   7722: =item $uname, students name
                   7723: 
                   7724: =item $uid, students user id
                   7725: 
                   7726: =item $first, students first name
                   7727: 
                   7728: =item $middle
                   7729: 
                   7730: =item $last
                   7731: 
                   7732: =item $gene
                   7733: 
                   7734: =item $usec
                   7735: 
                   7736: =item $end
                   7737: 
                   7738: =item $start
                   7739: 
                   7740: =back
                   7741: 
1.191     harris41 7742: 
                   7743: =item *
                   7744: 
1.243     albertel 7745: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   7746: custom role; give a custom role to a user for the level given by URL.  Specify
                   7747: name and domain of role author, and role name
1.191     harris41 7748: 
                   7749: =item *
                   7750: 
1.243     albertel 7751: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 7752: 
                   7753: =item *
                   7754: 
1.243     albertel 7755: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   7756: 
                   7757: =back
                   7758: 
                   7759: =head2 Course Infomation
                   7760: 
                   7761: =over 4
1.191     harris41 7762: 
                   7763: =item *
                   7764: 
1.631     albertel 7765: coursedescription($courseid) : returns a hash of information about the
                   7766: specified course id, including all environment settings for the
                   7767: course, the description of the course will be in the hash under the
                   7768: key 'description'
1.191     harris41 7769: 
                   7770: =item *
                   7771: 
1.624     albertel 7772: resdata($name,$domain,$type,@which) : request for current parameter
                   7773: setting for a specific $type, where $type is either 'course' or 'user',
                   7774: @what should be a list of parameters to ask about. This routine caches
                   7775: answers for 5 minutes.
1.243     albertel 7776: 
                   7777: =back
                   7778: 
                   7779: =head2 Course Modification
                   7780: 
                   7781: =over 4
1.191     harris41 7782: 
                   7783: =item *
                   7784: 
1.243     albertel 7785: writecoursepref($courseid,%prefs) : write preferences (environment
                   7786: database) for a course
1.191     harris41 7787: 
                   7788: =item *
                   7789: 
1.243     albertel 7790: createcourse($udom,$description,$url) : make/modify course
                   7791: 
                   7792: =back
                   7793: 
                   7794: =head2 Resource Subroutines
                   7795: 
                   7796: =over 4
1.191     harris41 7797: 
                   7798: =item *
                   7799: 
1.243     albertel 7800: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 7801: 
                   7802: =item *
                   7803: 
1.243     albertel 7804: repcopy($filename) : subscribes to the requested file, and attempts to
                   7805: replicate from the owning library server, Might return
1.607     raeburn  7806: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   7807: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 7808: resource. Expects the local filesystem pathname
                   7809: (/home/httpd/html/res/....)
                   7810: 
                   7811: =back
                   7812: 
                   7813: =head2 Resource Information
                   7814: 
                   7815: =over 4
1.191     harris41 7816: 
                   7817: =item *
                   7818: 
1.243     albertel 7819: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   7820: a vairety of different possible values, $varname should be a request
                   7821: string, and the other parameters can be used to specify who and what
                   7822: one is asking about.
                   7823: 
                   7824: Possible values for $varname are environment.lastname (or other item
                   7825: from the envirnment hash), user.name (or someother aspect about the
                   7826: user), resource.0.maxtries (or some other part and parameter of a
                   7827: resource)
1.204     albertel 7828: 
                   7829: =item *
                   7830: 
1.243     albertel 7831: directcondval($number) : get current value of a condition; reads from a state
                   7832: string
1.204     albertel 7833: 
                   7834: =item *
                   7835: 
1.243     albertel 7836: condval($condidx) : value of condition index based on state
1.204     albertel 7837: 
                   7838: =item *
                   7839: 
1.243     albertel 7840: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   7841: resource's metadata, $what should be either a specific key, or either
                   7842: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   7843: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   7844: 
                   7845: this function automatically caches all requests
1.191     harris41 7846: 
                   7847: =item *
                   7848: 
1.243     albertel 7849: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   7850: network of library servers; returns file handle of where SQL and regex results
                   7851: will be stored for query
1.191     harris41 7852: 
                   7853: =item *
                   7854: 
1.243     albertel 7855: symbread($filename) : return symbolic list entry (filename argument optional);
                   7856: returns the data handle
1.191     harris41 7857: 
                   7858: =item *
                   7859: 
1.243     albertel 7860: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 7861: a possible symb for the URL in $thisfn, and if is an encryypted
                   7862: resource that the user accessed using /enc/ returns a 1 on success, 0
                   7863: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 7864: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 7865: 
1.191     harris41 7866: 
                   7867: =item *
                   7868: 
1.243     albertel 7869: symbclean($symb) : removes versions numbers from a symb, returns the
                   7870: cleaned symb
1.191     harris41 7871: 
                   7872: =item *
                   7873: 
1.243     albertel 7874: is_on_map($uri) : checks if the $uri is somewhere on the current
                   7875: course map, user must be in a course for it to work.
1.191     harris41 7876: 
                   7877: =item *
                   7878: 
1.243     albertel 7879: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 7880: 
                   7881: =item *
                   7882: 
1.243     albertel 7883: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   7884: a random seed, all arguments are optional, if they aren't sent it uses the
                   7885: environment to derive them. Note: if symb isn't sent and it can't get one
                   7886: from &symbread it will use the current time as its return value
1.191     harris41 7887: 
                   7888: =item *
                   7889: 
1.243     albertel 7890: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   7891: unfakeable, receipt
1.191     harris41 7892: 
                   7893: =item *
                   7894: 
1.620     albertel 7895: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 7896: 
                   7897: =item *
                   7898: 
1.243     albertel 7899: countacc($url) : count the number of accesses to a given URL
1.191     harris41 7900: 
                   7901: =item *
                   7902: 
1.243     albertel 7903: 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 7904: 
                   7905: =item *
                   7906: 
1.243     albertel 7907: 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 7908: 
                   7909: =item *
                   7910: 
1.243     albertel 7911: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 7912: 
                   7913: =item *
                   7914: 
1.243     albertel 7915: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   7916: forcing spreadsheet to reevaluate the resource scores next time.
                   7917: 
                   7918: =back
                   7919: 
                   7920: =head2 Storing/Retreiving Data
                   7921: 
                   7922: =over 4
1.191     harris41 7923: 
                   7924: =item *
                   7925: 
1.243     albertel 7926: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   7927: for this url; hashref needs to be given and should be a \%hashname; the
                   7928: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 7929: be derived from the env
1.191     harris41 7930: 
                   7931: =item *
                   7932: 
1.243     albertel 7933: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   7934: uses critical subroutine
1.191     harris41 7935: 
                   7936: =item *
                   7937: 
1.243     albertel 7938: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   7939: all args are optional
1.191     harris41 7940: 
                   7941: =item *
                   7942: 
1.717     albertel 7943: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   7944: dumps the complete (or key matching regexp) namespace into a hash
                   7945: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   7946: normally &store()ed into
                   7947: 
                   7948: $range should be either an integer '100' (give me the first 100
                   7949:                                            matching records)
                   7950:               or be  two integers sperated by a - with no spaces
                   7951:                  '30-50' (give me the 30th through the 50th matching
                   7952:                           records)
                   7953: 
                   7954: 
                   7955: =item *
                   7956: 
                   7957: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   7958: replaces a &store() version of data with a replacement set of data
                   7959: for a particular resource in a namespace passed in the $storehash hash 
                   7960: reference
                   7961: 
                   7962: =item *
                   7963: 
1.243     albertel 7964: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   7965: works very similar to store/cstore, but all data is stored in a
                   7966: temporary location and can be reset using tmpreset, $storehash should
                   7967: be a hash reference, returns nothing on success
1.191     harris41 7968: 
                   7969: =item *
                   7970: 
1.243     albertel 7971: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   7972: similar to restore, but all data is stored in a temporary location and
                   7973: can be reset using tmpreset. Returns a hash of values on success,
                   7974: error string otherwise.
1.191     harris41 7975: 
                   7976: =item *
                   7977: 
1.243     albertel 7978: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   7979: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 7980: 
                   7981: =item *
                   7982: 
1.243     albertel 7983: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   7984: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 7985: 
                   7986: =item *
                   7987: 
1.243     albertel 7988: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   7989: namesp ($udom and $uname are optional)
1.191     harris41 7990: 
                   7991: =item *
                   7992: 
1.702     albertel 7993: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 7994: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 7995: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  7996: 
1.702     albertel 7997: $range should be either an integer '100' (give me the first 100
                   7998:                                            matching records)
                   7999:               or be  two integers sperated by a - with no spaces
                   8000:                  '30-50' (give me the 30th through the 50th matching
                   8001:                           records)
1.449     matthew  8002: =item *
                   8003: 
                   8004: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   8005: $store can be a scalar, an array reference, or if the amount to be 
                   8006: incremented is > 1, a hash reference.
                   8007: 
                   8008: ($udom and $uname are optional)
1.191     harris41 8009: 
                   8010: =item *
                   8011: 
1.243     albertel 8012: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   8013: ($udom and $uname are optional)
1.191     harris41 8014: 
                   8015: =item *
                   8016: 
1.243     albertel 8017: cput($namespace,$storehash,$udom,$uname) : critical put
                   8018: ($udom and $uname are optional)
1.191     harris41 8019: 
                   8020: =item *
                   8021: 
1.748     albertel 8022: newput($namespace,$storehash,$udom,$uname) :
                   8023: 
                   8024: Attempts to store the items in the $storehash, but only if they don't
                   8025: currently exist, if this succeeds you can be certain that you have 
                   8026: successfully created a new key value pair in the $namespace db.
                   8027: 
                   8028: 
                   8029: Args:
                   8030:  $namespace: name of database to store values to
                   8031:  $storehash: hashref to store to the db
                   8032:  $udom: (optional) domain of user containing the db
                   8033:  $uname: (optional) name of user caontaining the db
                   8034: 
                   8035: Returns:
                   8036:  'ok' -> succeeded in storing all keys of $storehash
                   8037:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   8038:                         least <key> already existed in the db (other
                   8039:                         requested keys may also already exist)
                   8040:  'error: <msg>' -> unable to tie the DB or other erorr occured
                   8041:  'con_lost' -> unable to contact request server
                   8042:  'refused' -> action was not allowed by remote machine
                   8043: 
                   8044: 
                   8045: =item *
                   8046: 
1.243     albertel 8047: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   8048: reference filled in from namesp (encrypts the return communication)
                   8049: ($udom and $uname are optional)
1.191     harris41 8050: 
                   8051: =item *
                   8052: 
1.243     albertel 8053: log($udom,$name,$home,$message) : write to permanent log for user; use
                   8054: critical subroutine
                   8055: 
                   8056: =back
                   8057: 
                   8058: =head2 Network Status Functions
                   8059: 
                   8060: =over 4
1.191     harris41 8061: 
                   8062: =item *
                   8063: 
                   8064: dirlist($uri) : return directory list based on URI
                   8065: 
                   8066: =item *
                   8067: 
1.243     albertel 8068: spareserver() : find server with least workload from spare.tab
                   8069: 
                   8070: =back
                   8071: 
                   8072: =head2 Apache Request
                   8073: 
                   8074: =over 4
1.191     harris41 8075: 
                   8076: =item *
                   8077: 
1.243     albertel 8078: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   8079: localhost, posts hash
                   8080: 
                   8081: =back
                   8082: 
                   8083: =head2 Data to String to Data
                   8084: 
                   8085: =over 4
1.191     harris41 8086: 
                   8087: =item *
                   8088: 
1.243     albertel 8089: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   8090: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 8091: 
                   8092: =item *
                   8093: 
1.243     albertel 8094: hashref2str($hashref) : convert a hashref into a string complete with
                   8095: escaping and '=' and '&' separators, supports elements that are
                   8096: arrayrefs and hashrefs
1.191     harris41 8097: 
                   8098: =item *
                   8099: 
1.243     albertel 8100: arrayref2str($arrayref) : convert an arrayref into a string complete
                   8101: with escaping and '&' separators, supports elements that are arrayrefs
                   8102: and hashrefs
1.191     harris41 8103: 
                   8104: =item *
                   8105: 
1.243     albertel 8106: str2hash($string) : convert string to hash using unescaping and
                   8107: splitting on '=' and '&', supports elements that are arrayrefs and
                   8108: hashrefs
1.191     harris41 8109: 
                   8110: =item *
                   8111: 
1.243     albertel 8112: str2array($string) : convert string to hash using unescaping and
                   8113: splitting on '&', supports elements that are arrayrefs and hashrefs
                   8114: 
                   8115: =back
                   8116: 
                   8117: =head2 Logging Routines
                   8118: 
                   8119: =over 4
                   8120: 
                   8121: These routines allow one to make log messages in the lonnet.log and
                   8122: lonnet.perm logfiles.
1.191     harris41 8123: 
                   8124: =item *
                   8125: 
1.243     albertel 8126: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 8127: 
                   8128: =item *
                   8129: 
1.243     albertel 8130: logthis() : append message to the normal lonnet.log file, it gets
                   8131: preiodically rolled over and deleted.
1.191     harris41 8132: 
                   8133: =item *
                   8134: 
1.243     albertel 8135: logperm() : append a permanent message to lonnet.perm.log, this log
                   8136: file never gets deleted by any automated portion of the system, only
                   8137: messages of critical importance should go in here.
                   8138: 
                   8139: =back
                   8140: 
                   8141: =head2 General File Helper Routines
                   8142: 
                   8143: =over 4
1.191     harris41 8144: 
                   8145: =item *
                   8146: 
1.481     raeburn  8147: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   8148: (a) files in /uploaded
                   8149:   (i) If a local copy of the file exists - 
                   8150:       compares modification date of local copy with last-modified date for 
                   8151:       definitive version stored on home server for course. If local copy is 
                   8152:       stale, requests a new version from the home server and stores it. 
                   8153:       If the original has been removed from the home server, then local copy 
                   8154:       is unlinked.
                   8155:   (ii) If local copy does not exist -
                   8156:       requests the file from the home server and stores it. 
                   8157:   
                   8158:   If $caller is 'uploadrep':  
                   8159:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   8160:     for request for files originally uploaded via DOCS. 
                   8161:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   8162:   
                   8163:   Otherwise:
                   8164:      This indicates a call from the content generation phase of the request.
                   8165:      -  returns the entire contents of the file or -1.
                   8166:      
                   8167: (b) files in /res
                   8168:    - returns the entire contents of a file or -1; 
                   8169:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 8170: 
1.712     albertel 8171: 
                   8172: =item *
                   8173: 
                   8174: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   8175:                   reference
                   8176: 
                   8177: returns either a stat() list of data about the file or an empty list
                   8178: if the file doesn't exist or couldn't find out about it (connection
                   8179: problems or user unknown)
                   8180: 
1.191     harris41 8181: =item *
                   8182: 
1.243     albertel 8183: filelocation($dir,$file) : returns file system location of a file
                   8184: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   8185: directory that relative $file lookups are to looked in ($dir of /a/dir
                   8186: and a file of ../bob will become /a/bob)
1.191     harris41 8187: 
                   8188: =item *
                   8189: 
                   8190: hreflocation($dir,$file) : returns file system location or a URL; same as
                   8191: filelocation except for hrefs
                   8192: 
                   8193: =item *
                   8194: 
                   8195: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   8196: 
1.243     albertel 8197: =back
                   8198: 
1.608     albertel 8199: =head2 Usererfile file routines (/uploaded*)
                   8200: 
                   8201: =over 4
                   8202: 
                   8203: =item *
                   8204: 
                   8205: userfileupload(): main rotine for putting a file in a user or course's
                   8206:                   filespace, arguments are,
                   8207: 
1.620     albertel 8208:  formname - required - this is the name of the element in $env where the
1.608     albertel 8209:            filename, and the contents of the file to create/modifed exist
1.620     albertel 8210:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   8211:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 8212:  coursedoc - if true, store the file in the course of the active role
                   8213:              of the current user
                   8214:  subdir - required - subdirectory to put the file in under ../userfiles/
                   8215:          if undefined, it will be placed in "unknown"
                   8216: 
                   8217:  (This routine calls clean_filename() to remove any dangerous
                   8218:  characters from the filename, and then calls finuserfileupload() to
                   8219:  complete the transaction)
                   8220: 
                   8221:  returns either the url of the uploaded file (/uploaded/....) if successful
                   8222:  and /adm/notfound.html if unsuccessful
                   8223: 
                   8224: =item *
                   8225: 
                   8226: clean_filename(): routine for cleaing a filename up for storage in
                   8227:                  userfile space, argument is:
                   8228: 
                   8229:  filename - proposed filename
                   8230: 
                   8231: returns: the new clean filename
                   8232: 
                   8233: =item *
                   8234: 
                   8235: finishuserfileupload(): routine that creaes and sends the file to
                   8236: userspace, probably shouldn't be called directly
                   8237: 
                   8238:   docuname: username or courseid of destination for the file
                   8239:   docudom: domain of user/course of destination for the file
                   8240:   formname: same as for userfileupload()
                   8241:   fname: filename (inculding subdirectories) for the file
                   8242: 
                   8243:  returns either the url of the uploaded file (/uploaded/....) if successful
                   8244:  and /adm/notfound.html if unsuccessful
                   8245: 
                   8246: =item *
                   8247: 
                   8248: renameuserfile(): renames an existing userfile to a new name
                   8249: 
                   8250:   Args:
                   8251:    docuname: username or courseid of destination for the file
                   8252:    docudom: domain of user/course of destination for the file
                   8253:    old: current file name (including any subdirs under userfiles)
                   8254:    new: desired file name (including any subdirs under userfiles)
                   8255: 
                   8256: =item *
                   8257: 
                   8258: mkdiruserfile(): creates a directory is a userfiles dir
                   8259: 
                   8260:   Args:
                   8261:    docuname: username or courseid of destination for the file
                   8262:    docudom: domain of user/course of destination for the file
                   8263:    dir: dir to create (including any subdirs under userfiles)
                   8264: 
                   8265: =item *
                   8266: 
                   8267: removeuserfile(): removes a file that exists in userfiles
                   8268: 
                   8269:   Args:
                   8270:    docuname: username or courseid of destination for the file
                   8271:    docudom: domain of user/course of destination for the file
                   8272:    fname: filname to delete (including any subdirs under userfiles)
                   8273: 
                   8274: =item *
                   8275: 
                   8276: removeuploadedurl(): convience function for removeuserfile()
                   8277: 
                   8278:   Args:
                   8279:    url:  a full /uploaded/... url to delete
                   8280: 
1.747     albertel 8281: =item * 
                   8282: 
                   8283: get_portfile_permissions():
                   8284:   Args:
                   8285:     domain: domain of user or course contain the portfolio files
                   8286:     user: name of user or num of course contain the portfolio files
                   8287:   Returns:
                   8288:     hashref of a dump of the proper file_permissions.db
                   8289:    
                   8290: 
                   8291: =item * 
                   8292: 
                   8293: get_access_controls():
                   8294: 
                   8295: Args:
                   8296:   current_permissions: the hash ref returned from get_portfile_permissions()
                   8297:   group: (optional) the group you want the files associated with
                   8298:   file: (optional) the file you want access info on
                   8299: 
                   8300: Returns:
1.749     raeburn  8301:     a hash (keys are file names) of hashes containing
                   8302:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   8303:         values are XML containing access control settings (see below) 
1.747     albertel 8304: 
                   8305: Internal notes:
                   8306: 
1.749     raeburn  8307:  access controls are stored in file_permissions.db as key=value pairs.
                   8308:     key -> path to file/file_name\0uniqueID:scope_end_start
                   8309:         where scope -> public,guest,course,group,domains or users.
                   8310:               end -> UNIX time for end of access (0 -> no end date)
                   8311:               start -> UNIX time for start of access
                   8312: 
                   8313:     value -> XML description of access control
                   8314:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   8315:             <start></start>
                   8316:             <end></end>
                   8317: 
                   8318:             <password></password>  for scope type = guest
                   8319: 
                   8320:             <domain></domain>     for scope type = course or group
                   8321:             <number></number>
                   8322:             <roles id="">
                   8323:              <role></role>
                   8324:              <access></access>
                   8325:              <section></section>
                   8326:              <group></group>
                   8327:             </roles>
                   8328: 
                   8329:             <dom></dom>         for scope type = domains
                   8330: 
                   8331:             <users>             for scope type = users
                   8332:              <user>
                   8333:               <uname></uname>
                   8334:               <udom></udom>
                   8335:              </user>
                   8336:             </users>
                   8337:            </scope> 
                   8338:               
                   8339:  Access data is also aggregated for each file in an additional key=value pair:
                   8340:  key -> path to file/file_name\0accesscontrol 
                   8341:  value -> reference to hash
                   8342:           hash contains key = value pairs
                   8343:           where key = uniqueID:scope_end_start
                   8344:                 value = UNIX time record was last updated
                   8345: 
                   8346:           Used to improve speed of look-ups of access controls for each file.  
                   8347:  
                   8348:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   8349: 
                   8350: modify_access_controls():
                   8351: 
                   8352: Modifies access controls for a portfolio file
                   8353: Args
                   8354: 1. file name
                   8355: 2. reference to hash of required changes,
                   8356: 3. domain
                   8357: 4. username
                   8358:   where domain,username are the domain of the portfolio owner 
                   8359:   (either a user or a course) 
                   8360: 
                   8361: Returns:
                   8362: 1. result of additions or updates ('ok' or 'error', with error message). 
                   8363: 2. result of deletions ('ok' or 'error', with error message).
                   8364: 3. reference to hash of any new or updated access controls.
                   8365: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   8366:    key = integer (inbound ID)
                   8367:    value = uniqueID  
1.747     albertel 8368: 
1.608     albertel 8369: =back
                   8370: 
1.243     albertel 8371: =head2 HTTP Helper Routines
                   8372: 
                   8373: =over 4
                   8374: 
1.191     harris41 8375: =item *
                   8376: 
                   8377: escape() : unpack non-word characters into CGI-compatible hex codes
                   8378: 
                   8379: =item *
                   8380: 
                   8381: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   8382: 
1.243     albertel 8383: =back
                   8384: 
                   8385: =head1 PRIVATE SUBROUTINES
                   8386: 
                   8387: =head2 Underlying communication routines (Shouldn't call)
                   8388: 
                   8389: =over 4
                   8390: 
                   8391: =item *
                   8392: 
                   8393: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   8394: 
                   8395: =item *
                   8396: 
                   8397: reply() : uses subreply to send a message to remote machine, logs all failures
                   8398: 
                   8399: =item *
                   8400: 
                   8401: critical() : passes a critical message to another server; if cannot
                   8402: get through then place message in connection buffer directory and
                   8403: returns con_delayed, if incapable of saving message, returns
                   8404: con_failed
                   8405: 
                   8406: =item *
                   8407: 
                   8408: reconlonc() : tries to reconnect lonc client processes.
                   8409: 
                   8410: =back
                   8411: 
                   8412: =head2 Resource Access Logging
                   8413: 
                   8414: =over 4
                   8415: 
                   8416: =item *
                   8417: 
                   8418: flushcourselogs() : flush (save) buffer logs and access logs
                   8419: 
                   8420: =item *
                   8421: 
                   8422: courselog($what) : save message for course in hash
                   8423: 
                   8424: =item *
                   8425: 
                   8426: courseacclog($what) : save message for course using &courselog().  Perform
                   8427: special processing for specific resource types (problems, exams, quizzes, etc).
                   8428: 
1.191     harris41 8429: =item *
                   8430: 
                   8431: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   8432: as a PerlChildExitHandler
1.243     albertel 8433: 
                   8434: =back
                   8435: 
                   8436: =head2 Other
                   8437: 
                   8438: =over 4
                   8439: 
                   8440: =item *
                   8441: 
                   8442: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 8443: 
                   8444: =back
                   8445: 
                   8446: =cut

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