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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.806   ! raeburn     4: # $Id: lonnet.pm,v 1.805 2006/11/20 23:50:51 raeburn Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.1       albertel   30: package Apache::lonnet;
                     31: 
                     32: use strict;
1.8       www        33: use LWP::UserAgent();
1.15      www        34: use HTTP::Headers;
1.486     www        35: use HTTP::Date;
                     36: # use Date::Parse;
1.11      www        37: use vars 
1.599     albertel   38: qw(%perlvar %hostname %badServerCache %iphost %spareid %hostdom 
                     39:    %libserv %pr %prp $memcache %packagetab 
1.662     raeburn    40:    %courselogs %accesshash %userrolehash %domainrolehash $processmarker $dumpcount 
1.741     raeburn    41:    %coursedombuf %coursenumbuf %coursehombuf %coursedescrbuf %courseinstcodebuf %courseownerbuf %coursetypebuf
1.599     albertel   42:    %domaindescription %domain_auth_def %domain_auth_arg_def 
1.685     raeburn    43:    %domain_lang_def %domain_city %domain_longi %domain_lati %domain_primary
                     44:    $tmpdir $_64bit %env);
1.403     www        45: 
1.1       albertel   46: use IO::Socket;
1.31      www        47: use GDBM_File;
1.208     albertel   48: use HTML::LCParser;
1.637     raeburn    49: use HTML::Parser;
1.88      www        50: use Fcntl qw(:flock);
1.557     albertel   51: use Storable qw(lock_store lock_nstore lock_retrieve freeze thaw nfreeze);
1.539     albertel   52: use Time::HiRes qw( gettimeofday tv_interval );
1.599     albertel   53: use Cache::Memcached;
1.676     albertel   54: use Digest::MD5;
1.790     albertel   55: use Math::Random;
1.740     www        56: use lib '/home/httpd/lib/perl';
                     57: use LONCAPA;
                     58: use LONCAPA::Configuration;
1.676     albertel   59: 
1.195     www        60: my $readit;
1.550     foxr       61: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel   62: 
1.619     albertel   63: require Exporter;
                     64: 
                     65: our @ISA = qw (Exporter);
                     66: our @EXPORT = qw(%env);
                     67: 
1.449     matthew    68: =pod
                     69: 
                     70: =head1 Package Variables
                     71: 
                     72: These are largely undocumented, so if you decipher one please note it here.
                     73: 
                     74: =over 4
                     75: 
                     76: =item $processmarker
                     77: 
                     78: Contains the time this process was started and this servers host id.
                     79: 
                     80: =item $dumpcount
                     81: 
                     82: Counts the number of times a message log flush has been attempted (regardless
                     83: of success) by this process.  Used as part of the filename when messages are
                     84: delayed.
                     85: 
                     86: =back
                     87: 
                     88: =cut
                     89: 
                     90: 
1.1       albertel   91: # --------------------------------------------------------------------- Logging
1.729     www        92: {
                     93:     my $logid;
                     94:     sub instructor_log {
                     95: 	my ($hash_name,$storehash,$delflag,$uname,$udom)=@_;
                     96: 	$logid++;
                     97: 	my $id=time().'00000'.$$.'00000'.$logid;
                     98: 	return &Apache::lonnet::put('nohist_'.$hash_name,
1.730     www        99: 				    { $id => {
                    100: 					'exe_uname' => $env{'user.name'},
                    101: 					'exe_udom'  => $env{'user.domain'},
                    102: 					'exe_time'  => time(),
                    103: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    104: 					'delflag'   => $delflag,
                    105: 					'logentry'  => $storehash,
                    106: 					'uname'     => $uname,
                    107: 					'udom'      => $udom,
                    108: 				    }
                    109: 				  },
1.729     www       110: 				    $env{'course.'.$env{'request.course.id'}.'.domain'},
                    111: 				    $env{'course.'.$env{'request.course.id'}.'.num'}
                    112: 				    );
                    113:     }
                    114: }
1.1       albertel  115: 
1.163     harris41  116: sub logtouch {
                    117:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  118:     unless (-e "$execdir/logs/lonnet.log") {	
                    119: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  120: 	close $fh;
                    121:     }
                    122:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    123:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    124: }
                    125: 
1.1       albertel  126: sub logthis {
                    127:     my $message=shift;
                    128:     my $execdir=$perlvar{'lonDaemons'};
                    129:     my $now=time;
                    130:     my $local=localtime($now);
1.448     albertel  131:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
                    132: 	print $fh "$local ($$): $message\n";
                    133: 	close($fh);
                    134:     }
1.1       albertel  135:     return 1;
                    136: }
                    137: 
                    138: sub logperm {
                    139:     my $message=shift;
                    140:     my $execdir=$perlvar{'lonDaemons'};
                    141:     my $now=time;
                    142:     my $local=localtime($now);
1.448     albertel  143:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    144: 	print $fh "$now:$message:$local\n";
                    145: 	close($fh);
                    146:     }
1.1       albertel  147:     return 1;
                    148: }
                    149: 
                    150: # -------------------------------------------------- Non-critical communication
                    151: sub subreply {
                    152:     my ($cmd,$server)=@_;
1.704     albertel  153:     my $peerfile="$perlvar{'lonSockDir'}/".$hostname{$server};
1.549     foxr      154:     #
                    155:     #  With loncnew process trimming, there's a timing hole between lonc server
                    156:     #  process exit and the master server picking up the listen on the AF_UNIX
                    157:     #  socket.  In that time interval, a lock file will exist:
                    158: 
                    159:     my $lockfile=$peerfile.".lock";
                    160:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    161: 	sleep(1);
                    162:     }
                    163:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      164:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      165:     #
1.550     foxr      166:     #   We'll give the connection a few tries before abandoning it.  If
                    167:     #   connection is not possible, we'll con_lost back to the client.
                    168:     #   
                    169:     my $client;
                    170:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    171: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    172: 				      Type    => SOCK_STREAM,
                    173: 				      Timeout => 10);
                    174: 	if($client) {
                    175: 	    last;		# Connected!
                    176: 	}
                    177: 	sleep(1);		# Try again later if failed connection.
                    178:     }
                    179:     my $answer;
                    180:     if ($client) {
1.704     albertel  181: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      182: 	$answer=<$client>;
                    183: 	if (!$answer) { $answer="con_lost"; }
                    184: 	chomp($answer);
                    185:     } else {
                    186: 	$answer = 'con_lost';	# Failed connection.
                    187:     }
1.1       albertel  188:     return $answer;
                    189: }
                    190: 
                    191: sub reply {
                    192:     my ($cmd,$server)=@_;
1.205     www       193:     unless (defined($hostname{$server})) { return 'no_such_host'; }
1.1       albertel  194:     my $answer=subreply($cmd,$server);
1.65      www       195:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  196:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       197:                 " $cmd to $server returned $answer</font>");
                    198:     }
1.1       albertel  199:     return $answer;
                    200: }
                    201: 
                    202: # ----------------------------------------------------------- Send USR1 to lonc
                    203: 
                    204: sub reconlonc {
                    205:     my $peerfile=shift;
                    206:     &logthis("Trying to reconnect for $peerfile");
                    207:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  208:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  209: 	my $loncpid=<$fh>;
                    210:         chomp($loncpid);
                    211:         if (kill 0 => $loncpid) {
                    212: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    213:             kill USR1 => $loncpid;
                    214:             sleep 1;
                    215:             if (-e "$peerfile") { return; }
                    216:             &logthis("$peerfile still not there, give it another try");
                    217:             sleep 5;
                    218:             if (-e "$peerfile") { return; }
1.12      www       219:             &logthis(
1.672     albertel  220:   "<font color=\"blue\">WARNING: $peerfile still not there, giving up</font>");
1.1       albertel  221:         } else {
1.12      www       222: 	    &logthis(
1.672     albertel  223:                "<font color=\"blue\">WARNING:".
1.12      www       224:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  225:         }
                    226:     } else {
1.672     albertel  227:      &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  228:     }
                    229: }
                    230: 
                    231: # ------------------------------------------------------ Critical communication
1.12      www       232: 
1.1       albertel  233: sub critical {
                    234:     my ($cmd,$server)=@_;
1.89      www       235:     unless ($hostname{$server}) {
1.672     albertel  236:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       237:                " Critical message to unknown server ($server)</font>");
                    238:         return 'no_such_host';
                    239:     }
1.1       albertel  240:     my $answer=reply($cmd,$server);
                    241:     if ($answer eq 'con_lost') {
                    242: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  243: 	my $answer=reply($cmd,$server);
1.1       albertel  244:         if ($answer eq 'con_lost') {
                    245:             my $now=time;
                    246:             my $middlename=$cmd;
1.5       www       247:             $middlename=substr($middlename,0,16);
1.1       albertel  248:             $middlename=~s/\W//g;
                    249:             my $dfilename=
1.305     www       250:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    251:             $dumpcount++;
1.1       albertel  252:             {
1.448     albertel  253: 		my $dfh;
                    254: 		if (open($dfh,">$dfilename")) {
                    255: 		    print $dfh "$cmd\n"; 
                    256: 		    close($dfh);
                    257: 		}
1.1       albertel  258:             }
                    259:             sleep 2;
                    260:             my $wcmd='';
                    261:             {
1.448     albertel  262: 		my $dfh;
                    263: 		if (open($dfh,"<$dfilename")) {
                    264: 		    $wcmd=<$dfh>; 
                    265: 		    close($dfh);
                    266: 		}
1.1       albertel  267:             }
                    268:             chomp($wcmd);
1.7       www       269:             if ($wcmd eq $cmd) {
1.672     albertel  270: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       271:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  272:                 &logperm("D:$server:$cmd");
                    273: 	        return 'con_delayed';
                    274:             } else {
1.672     albertel  275:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       276:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  277:                 &logperm("F:$server:$cmd");
                    278:                 return 'con_failed';
                    279:             }
                    280:         }
                    281:     }
                    282:     return $answer;
1.405     albertel  283: }
                    284: 
1.755     albertel  285: # ------------------------------------------- check if return value is an error
                    286: 
                    287: sub error {
                    288:     my ($result) = @_;
1.756     albertel  289:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  290: 	if ($2 == 2) { return undef; }
                    291: 	return $1;
                    292:     }
                    293:     return undef;
                    294: }
                    295: 
1.783     albertel  296: sub convert_and_load_session_env {
                    297:     my ($lonidsdir,$handle)=@_;
                    298:     my @profile;
                    299:     {
                    300: 	open(my $idf,"$lonidsdir/$handle.id");
                    301: 	flock($idf,LOCK_SH);
                    302: 	@profile=<$idf>;
                    303: 	close($idf);
                    304:     }
                    305:     my %temp_env;
                    306:     foreach my $line (@profile) {
1.786     albertel  307: 	if ($line !~ m/=/) {
                    308: 	    return 0;
                    309: 	}
1.783     albertel  310: 	chomp($line);
                    311: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    312: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    313:     }
                    314:     unlink("$lonidsdir/$handle.id");
                    315:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    316: 	    0640)) {
                    317: 	%disk_env = %temp_env;
                    318: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    319: 	untie(%disk_env);
                    320:     }
1.786     albertel  321:     return 1;
1.783     albertel  322: }
                    323: 
1.374     www       324: # ------------------------------------------- Transfer profile into environment
1.780     albertel  325: my $env_loaded;
                    326: sub transfer_profile_to_env {
1.788     albertel  327:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    328:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       329: 
1.720     albertel  330:     if (!defined($lonidsdir)) {
                    331: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    332:     }
                    333:     if (!defined($handle)) {
                    334:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    335:     }
                    336: 
1.786     albertel  337:     my $convert;
                    338:     {
                    339:     	open(my $idf,"$lonidsdir/$handle.id");
                    340: 	flock($idf,LOCK_SH);
                    341: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    342: 		&GDBM_READER(),0640)) {
                    343: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    344: 	    untie(%disk_env);
                    345: 	} else {
                    346: 	    $convert = 1;
                    347: 	}
                    348:     }
                    349:     if ($convert) {
                    350: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    351: 	    &logthis("Failed to load session, or convert session.");
                    352: 	}
1.374     www       353:     }
1.783     albertel  354: 
1.786     albertel  355:     my %remove;
1.783     albertel  356:     while ( my $envname = each(%env) ) {
1.433     matthew   357:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    358:             if ($time < time-300) {
1.783     albertel  359:                 $remove{$key}++;
1.433     matthew   360:             }
                    361:         }
                    362:     }
1.783     albertel  363: 
1.619     albertel  364:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  365:     $env_loaded=1;
1.783     albertel  366:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   367:         &delenv($expired_key);
1.374     www       368:     }
1.1       albertel  369: }
                    370: 
1.5       www       371: # ---------------------------------------------------------- Append Environment
                    372: 
                    373: sub appenv {
1.6       www       374:     my %newenv=@_;
1.692     albertel  375:     foreach my $key (keys(%newenv)) {
                    376: 	if (($newenv{$key}=~/^user\.role/) || ($newenv{$key}=~/^user\.priv/)) {
1.672     albertel  377:             &logthis("<font color=\"blue\">WARNING: ".
1.692     albertel  378:                 "Attempt to modify environment ".$key." to ".$newenv{$key}
1.151     www       379:                 .'</font>');
1.692     albertel  380: 	    delete($newenv{$key});
1.35      www       381:         } else {
1.692     albertel  382:             $env{$key}=$newenv{$key};
1.35      www       383:         }
1.191     harris41  384:     }
1.783     albertel  385:     if (tie(my %disk_env,'GDBM_File',$env{'user.environment'},&GDBM_WRITER(),
                    386: 	    0640)) {
                    387: 	while (my ($key,$value) = each(%newenv)) {
                    388: 	    $disk_env{$key} = $value;
1.448     albertel  389: 	}
1.783     albertel  390: 	untie(%disk_env);
1.56      www       391:     }
                    392:     return 'ok';
                    393: }
                    394: # ----------------------------------------------------- Delete from Environment
                    395: 
                    396: sub delenv {
                    397:     my $delthis=shift;
                    398:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672     albertel  399:         &logthis("<font color=\"blue\">WARNING: ".
1.56      www       400:                 "Attempt to delete from environment ".$delthis);
                    401:         return 'error';
                    402:     }
1.783     albertel  403:     if (tie(my %disk_env,'GDBM_File',$env{'user.environment'},&GDBM_WRITER(),
                    404: 	    0640)) {
                    405: 	foreach my $key (keys(%disk_env)) {
                    406: 	    if ($key=~/^$delthis/) { 
1.619     albertel  407:                 delete($env{$key});
1.783     albertel  408:                 delete($disk_env{$key});
1.473     matthew   409:             }
1.448     albertel  410: 	}
1.783     albertel  411: 	untie(%disk_env);
1.5       www       412:     }
                    413:     return 'ok';
1.369     albertel  414: }
                    415: 
1.790     albertel  416: sub get_env_multiple {
                    417:     my ($name) = @_;
                    418:     my @values;
                    419:     if (defined($env{$name})) {
                    420:         # exists is it an array
                    421:         if (ref($env{$name})) {
                    422:             @values=@{ $env{$name} };
                    423:         } else {
                    424:             $values[0]=$env{$name};
                    425:         }
                    426:     }
                    427:     return(@values);
                    428: }
                    429: 
1.369     albertel  430: # ------------------------------------------ Find out current server userload
                    431: # there is a copy in lond
                    432: sub userload {
                    433:     my $numusers=0;
                    434:     {
                    435: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    436: 	my $filename;
                    437: 	my $curtime=time;
                    438: 	while ($filename=readdir(LONIDS)) {
                    439: 	    if ($filename eq '.' || $filename eq '..') {next;}
1.404     albertel  440: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  441: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  442: 	}
                    443: 	closedir(LONIDS);
                    444:     }
                    445:     my $userloadpercent=0;
                    446:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    447:     if ($maxuserload) {
1.371     albertel  448: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  449:     }
1.372     albertel  450:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  451:     return $userloadpercent;
1.283     www       452: }
                    453: 
                    454: # ------------------------------------------ Fight off request when overloaded
                    455: 
                    456: sub overloaderror {
                    457:     my ($r,$checkserver)=@_;
                    458:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
                    459:     my $loadavg;
                    460:     if ($checkserver eq $perlvar{'lonHostID'}) {
1.448     albertel  461:        open(my $loadfile,'/proc/loadavg');
1.283     www       462:        $loadavg=<$loadfile>;
                    463:        $loadavg =~ s/\s.*//g;
1.285     matthew   464:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448     albertel  465:        close($loadfile);
1.283     www       466:     } else {
                    467:        $loadavg=&reply('load',$checkserver);
                    468:     }
1.285     matthew   469:     my $overload=$loadavg-100;
1.283     www       470:     if ($overload>0) {
1.285     matthew   471: 	$r->err_headers_out->{'Retry-After'}=$overload;
1.283     www       472:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554     www       473:         return 413;
1.283     www       474:     }    
                    475:     return '';
1.5       www       476: }
1.1       albertel  477: 
                    478: # ------------------------------ Find server with least workload from spare.tab
1.11      www       479: 
1.1       albertel  480: sub spareserver {
1.670     albertel  481:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.784     albertel  482:     my $spare_server;
1.370     albertel  483:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  484:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    485:                                                      :  $userloadpercent;
                    486:     
                    487:     foreach my $try_server (@{ $spareid{'primary'} }) {
                    488: 	($spare_server, $lowest_load) =
                    489: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
                    490:     }
                    491: 
                    492:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    493: 
                    494:     if (!$found_server) {
                    495: 	foreach my $try_server (@{ $spareid{'default'} }) {
                    496: 	    ($spare_server, $lowest_load) =
                    497: 		&compare_server_load($try_server, $spare_server, $lowest_load);
                    498: 	}
                    499:     }
                    500: 
                    501:     if (!$want_server_name) {
                    502: 	$spare_server="http://$hostname{$spare_server}";
                    503:     }
                    504:     return $spare_server;
                    505: }
                    506: 
                    507: sub compare_server_load {
                    508:     my ($try_server, $spare_server, $lowest_load) = @_;
                    509: 
                    510:     my $loadans     = &reply('load',    $try_server);
                    511:     my $userloadans = &reply('userload',$try_server);
                    512: 
                    513:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
                    514: 	next; #didn't get a number from the server
                    515:     }
                    516: 
                    517:     my $load;
                    518:     if ($loadans =~ /\d/) {
                    519: 	if ($userloadans =~ /\d/) {
                    520: 	    #both are numbers, pick the bigger one
                    521: 	    $load = ($loadans > $userloadans) ? $loadans 
                    522: 		                              : $userloadans;
1.411     albertel  523: 	} else {
1.784     albertel  524: 	    $load = $loadans;
1.411     albertel  525: 	}
1.784     albertel  526:     } else {
                    527: 	$load = $userloadans;
                    528:     }
                    529: 
                    530:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    531: 	$spare_server = $try_server;
                    532: 	$lowest_load  = $load;
1.370     albertel  533:     }
1.784     albertel  534:     return ($spare_server,$lowest_load);
1.202     matthew   535: }
                    536: # --------------------------------------------- Try to change a user's password
                    537: 
                    538: sub changepass {
1.799     raeburn   539:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   540:     $currentpass = &escape($currentpass);
                    541:     $newpass     = &escape($newpass);
1.799     raeburn   542:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
1.202     matthew   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.800     albertel  667:     foreach my $uname (@unames) {
                    668:         $returnhash{$uname}=(&userenvironment($udom,$uname,'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.800     albertel  678:     foreach my $uname (keys(%ids)) {
                    679: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                    680:         my $uhom=&homeserver($uname,$udom);
1.70      www       681:         if ($uhom ne 'no_host') {
1.800     albertel  682:             my $id=&escape($ids{$uname});
1.70      www       683:             $id=~tr/A-Z/a-z/;
1.800     albertel  684:             my $esc_unam=&escape($uname);
1.70      www       685: 	    if ($servers{$uhom}) {
1.800     albertel  686: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www       687:             } else {
1.800     albertel  688:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www       689:             }
                    690:         }
1.191     harris41  691:     }
1.800     albertel  692:     foreach my $server (keys(%servers)) {
                    693:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41  694:     }
1.344     www       695: }
                    696: 
1.806   ! raeburn   697: # ------------------------------------------- get items from domain db files   
        !           698: 
        !           699: sub get_dom {
        !           700:     my ($namespace,$storearr,$udom)=@_;
        !           701:     my $items='';
        !           702:     foreach my $item (@$storearr) {
        !           703:         $items.=&escape($item).'&';
        !           704:     }
        !           705:     $items=~s/\&$//;
        !           706:     if (!$udom) { $udom=$env{'user.domain'}; }
        !           707:     if (exists($domain_primary{$udom})) {
        !           708:         my $uhome=$domain_primary{$udom};
        !           709:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
        !           710:         my @pairs=split(/\&/,$rep);
        !           711:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
        !           712:             return @pairs;
        !           713:         }
        !           714:         my %returnhash=();
        !           715:         my $i=0;
        !           716:         foreach my $item (@$storearr) {
        !           717:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
        !           718:             $i++;
        !           719:         }
        !           720:         return %returnhash;
        !           721:     } else {
        !           722:         &logthis("get_dom failed - no primary domain server for $udom");
        !           723:     }
        !           724: }
        !           725: 
        !           726: # -------------------------------------------- put items in domain db files 
        !           727: 
        !           728: sub put_dom {
        !           729:     my ($namespace,$storehash,$udom)=@_;
        !           730:     if (!$udom) { $udom=$env{'user.domain'}; }
        !           731:     if (exists($domain_primary{$udom})) {
        !           732:         my $uhome=$domain_primary{$udom};
        !           733:         my $items='';
        !           734:         foreach my $item (keys(%$storehash)) {
        !           735:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
        !           736:         }
        !           737:         $items=~s/\&$//;
        !           738:         return &reply("putdom:$udom:$namespace:$items",$uhome);
        !           739:     } else {
        !           740:         &logthis("put_dom failed - no primary domain server for $udom");
        !           741:     }
        !           742: }
        !           743: 
1.344     www       744: # --------------------------------------------------- Assign a key to a student
                    745: 
                    746: sub assign_access_key {
1.364     www       747: #
                    748: # a valid key looks like uname:udom#comments
                    749: # comments are being appended
                    750: #
1.498     www       751:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                    752:     $kdom=
1.620     albertel  753:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www       754:     $knum=
1.620     albertel  755:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www       756:     $cdom=
1.620     albertel  757:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       758:     $cnum=
1.620     albertel  759:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    760:     $udom=$env{'user.name'} unless (defined($udom));
                    761:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www       762:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www       763:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel  764:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www       765:                                                   # assigned to this person
                    766:                                                   # - this should not happen,
1.345     www       767:                                                   # unless something went wrong
                    768:                                                   # the first time around
                    769: # ready to assign
1.364     www       770:         $logentry=$1.'; '.$logentry;
1.496     www       771:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www       772:                                                  $kdom,$knum) eq 'ok') {
1.345     www       773: # key now belongs to user
1.346     www       774: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www       775:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
                    776:                 &appenv('environment.'.$envkey => $ckey);
                    777:                 return 'ok';
                    778:             } else {
                    779:                 return 
                    780:   'error: Count not permanently assign key, will need to be re-entered later.';
                    781: 	    }
                    782:         } else {
                    783:             return 'error: Could not assign key, try again later.';
                    784:         }
1.364     www       785:     } elsif (!$existing{$ckey}) {
1.345     www       786: # the key does not exist
                    787: 	return 'error: The key does not exist';
                    788:     } else {
                    789: # the key is somebody else's
                    790: 	return 'error: The key is already in use';
                    791:     }
1.344     www       792: }
                    793: 
1.364     www       794: # ------------------------------------------ put an additional comment on a key
                    795: 
                    796: sub comment_access_key {
                    797: #
                    798: # a valid key looks like uname:udom#comments
                    799: # comments are being appended
                    800: #
                    801:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                    802:     $cdom=
1.620     albertel  803:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www       804:     $cnum=
1.620     albertel  805:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www       806:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                    807:     if ($existing{$ckey}) {
                    808:         $existing{$ckey}.='; '.$logentry;
                    809: # ready to assign
1.367     www       810:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www       811:                                                  $cdom,$cnum) eq 'ok') {
                    812: 	    return 'ok';
                    813:         } else {
                    814: 	    return 'error: Count not store comment.';
                    815:         }
                    816:     } else {
                    817: # the key does not exist
                    818: 	return 'error: The key does not exist';
                    819:     }
                    820: }
                    821: 
1.344     www       822: # ------------------------------------------------------ Generate a set of keys
                    823: 
                    824: sub generate_access_keys {
1.364     www       825:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www       826:     $cdom=
1.620     albertel  827:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       828:     $cnum=
1.620     albertel  829:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www       830:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www       831:     unless (($cdom) && ($cnum)) { return 0; }
                    832:     if ($number>10000) { return 0; }
                    833:     sleep(2); # make sure don't get same seed twice
                    834:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                    835:     my $total=0;
                    836:     for (my $i=1;$i<=$number;$i++) {
                    837:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                    838:                   sprintf("%lx",int(100000*rand)).'-'.
                    839:                   sprintf("%lx",int(100000*rand));
                    840:        $newkey=~s/1/g/g; # folks mix up 1 and l
                    841:        $newkey=~s/0/h/g; # and also 0 and O
                    842:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                    843:        if ($existing{$newkey}) {
                    844:            $i--;
                    845:        } else {
1.364     www       846: 	  if (&put('accesskeys',
                    847:               { $newkey => '# generated '.localtime().
1.620     albertel  848:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www       849:                            '; '.$logentry },
                    850: 		   $cdom,$cnum) eq 'ok') {
1.344     www       851:               $total++;
                    852: 	  }
                    853:        }
                    854:     }
1.620     albertel  855:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www       856:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                    857:     return $total;
                    858: }
                    859: 
                    860: # ------------------------------------------------------- Validate an accesskey
                    861: 
                    862: sub validate_access_key {
                    863:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                    864:     $cdom=
1.620     albertel  865:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       866:     $cnum=
1.620     albertel  867:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    868:     $udom=$env{'user.domain'} unless (defined($udom));
                    869:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www       870:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel  871:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www       872: }
                    873: 
                    874: # ------------------------------------- Find the section of student in a course
1.652     albertel  875: sub devalidate_getsection_cache {
                    876:     my ($udom,$unam,$courseid)=@_;
                    877:     $courseid=~s/\_/\//g;
                    878:     $courseid=~s/^(\w)/\/$1/;
                    879:     my $hashid="$udom:$unam:$courseid";
                    880:     &devalidate_cache_new('getsection',$hashid);
                    881: }
1.298     matthew   882: 
                    883: sub getsection {
                    884:     my ($udom,$unam,$courseid)=@_;
1.599     albertel  885:     my $cachetime=1800;
1.298     matthew   886:     $courseid=~s/\_/\//g;
                    887:     $courseid=~s/^(\w)/\/$1/;
1.551     albertel  888: 
                    889:     my $hashid="$udom:$unam:$courseid";
1.599     albertel  890:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel  891:     if (defined($cached)) { return $result; }
                    892: 
1.298     matthew   893:     my %Pending; 
                    894:     my %Expired;
                    895:     #
                    896:     # Each role can either have not started yet (pending), be active, 
                    897:     #    or have expired.
                    898:     #
                    899:     # If there is an active role, we are done.
                    900:     #
                    901:     # If there is more than one role which has not started yet, 
                    902:     #     choose the one which will start sooner
                    903:     # If there is one role which has not started yet, return it.
                    904:     #
                    905:     # If there is more than one expired role, choose the one which ended last.
                    906:     # If there is a role which has expired, return it.
                    907:     #
1.800     albertel  908:     foreach my $line (split(/\&/,&reply('dump:'.$udom.':'.$unam.':roles',
                    909: 					&homeserver($unam,$udom)))) {
                    910:         my ($key,$value)=split(/\=/,$line,2);
1.298     matthew   911:         $key=&unescape($key);
1.479     albertel  912:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew   913:         my $section=$1;
                    914:         if ($key eq $courseid.'_st') { $section=''; }
                    915:         my ($dummy,$end,$start)=split(/\_/,&unescape($value));
                    916:         my $now=time;
1.548     albertel  917:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew   918:             $Expired{$end}=$section;
                    919:             next;
                    920:         }
1.548     albertel  921:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew   922:             $Pending{$start}=$section;
                    923:             next;
                    924:         }
1.599     albertel  925:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew   926:     }
                    927:     #
                    928:     # Presumedly there will be few matching roles from the above
                    929:     # loop and the sorting time will be negligible.
                    930:     if (scalar(keys(%Pending))) {
                    931:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel  932:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew   933:     } 
                    934:     if (scalar(keys(%Expired))) {
                    935:         my @sorted = sort {$a <=> $b} keys(%Expired);
                    936:         my $time = pop(@sorted);
1.599     albertel  937:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew   938:     }
1.599     albertel  939:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew   940: }
1.70      www       941: 
1.599     albertel  942: sub save_cache {
                    943:     &purge_remembered();
1.722     albertel  944:     #&Apache::loncommon::validate_page();
1.620     albertel  945:     undef(%env);
1.780     albertel  946:     undef($env_loaded);
1.599     albertel  947: }
1.452     albertel  948: 
1.599     albertel  949: my $to_remember=-1;
                    950: my %remembered;
                    951: my %accessed;
                    952: my $kicks=0;
                    953: my $hits=0;
                    954: sub devalidate_cache_new {
                    955:     my ($name,$id,$debug) = @_;
                    956:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
                    957:     $id=&escape($name.':'.$id);
                    958:     $memcache->delete($id);
                    959:     delete($remembered{$id});
                    960:     delete($accessed{$id});
                    961: }
                    962: 
                    963: sub is_cached_new {
                    964:     my ($name,$id,$debug) = @_;
                    965:     $id=&escape($name.':'.$id);
                    966:     if (exists($remembered{$id})) {
                    967: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                    968: 	$accessed{$id}=[&gettimeofday()];
                    969: 	$hits++;
                    970: 	return ($remembered{$id},1);
                    971:     }
                    972:     my $value = $memcache->get($id);
                    973:     if (!(defined($value))) {
                    974: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel  975: 	return (undef,undef);
1.416     albertel  976:     }
1.599     albertel  977:     if ($value eq '__undef__') {
                    978: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                    979: 	$value=undef;
                    980:     }
                    981:     &make_room($id,$value,$debug);
                    982:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                    983:     return ($value,1);
                    984: }
                    985: 
                    986: sub do_cache_new {
                    987:     my ($name,$id,$value,$time,$debug) = @_;
                    988:     $id=&escape($name.':'.$id);
                    989:     my $setvalue=$value;
                    990:     if (!defined($setvalue)) {
                    991: 	$setvalue='__undef__';
                    992:     }
1.623     albertel  993:     if (!defined($time) ) {
                    994: 	$time=600;
                    995:     }
1.599     albertel  996:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.600     albertel  997:     $memcache->set($id,$setvalue,$time);
                    998:     # need to make a copy of $value
                    999:     #&make_room($id,$value,$debug);
1.599     albertel 1000:     return $value;
                   1001: }
                   1002: 
                   1003: sub make_room {
                   1004:     my ($id,$value,$debug)=@_;
                   1005:     $remembered{$id}=$value;
                   1006:     if ($to_remember<0) { return; }
                   1007:     $accessed{$id}=[&gettimeofday()];
                   1008:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   1009:     my $to_kick;
                   1010:     my $max_time=0;
                   1011:     foreach my $other (keys(%accessed)) {
                   1012: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   1013: 	    $to_kick=$other;
                   1014: 	    $max_time=&tv_interval($accessed{$other});
                   1015: 	}
                   1016:     }
                   1017:     delete($remembered{$to_kick});
                   1018:     delete($accessed{$to_kick});
                   1019:     $kicks++;
                   1020:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 1021:     return;
                   1022: }
                   1023: 
1.599     albertel 1024: sub purge_remembered {
1.604     albertel 1025:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   1026:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 1027:     undef(%remembered);
                   1028:     undef(%accessed);
1.428     albertel 1029: }
1.70      www      1030: # ------------------------------------- Read an entry from a user's environment
                   1031: 
                   1032: sub userenvironment {
                   1033:     my ($udom,$unam,@what)=@_;
                   1034:     my %returnhash=();
                   1035:     my @answer=split(/\&/,
                   1036:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
                   1037:                       &homeserver($unam,$udom)));
                   1038:     my $i;
                   1039:     for ($i=0;$i<=$#what;$i++) {
                   1040: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                   1041:     }
                   1042:     return %returnhash;
1.1       albertel 1043: }
                   1044: 
1.617     albertel 1045: # ---------------------------------------------------------- Get a studentphoto
                   1046: sub studentphoto {
                   1047:     my ($udom,$unam,$ext) = @_;
                   1048:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1049:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1050:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1051:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1052:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1053:             } else {
                   1054:                 my ($result,$perm_reqd)=
1.707     albertel 1055: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1056:                 if ($result eq 'ok') {
                   1057:                     if (!($perm_reqd eq 'yes')) {
                   1058:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1059:                     }
                   1060:                 }
                   1061:             }
                   1062:         }
                   1063:     } else {
                   1064:         my ($result,$perm_reqd) = 
1.707     albertel 1065: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1066:         if ($result eq 'ok') {
                   1067:             if (!($perm_reqd eq 'yes')) {
                   1068:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1069:             }
                   1070:         }
                   1071:     }
                   1072:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1073: }
                   1074: 
                   1075: sub retrievestudentphoto {
                   1076:     my ($udom,$unam,$ext,$type) = @_;
                   1077:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1078:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1079:     if ($ret eq 'ok') {
                   1080:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1081:         if ($type eq 'thumbnail') {
                   1082:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1083:         }
                   1084:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1085:         return $tokenurl;
                   1086:     } else {
                   1087:         if ($type eq 'thumbnail') {
                   1088:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1089:         } else { 
                   1090:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1091:         }
1.617     albertel 1092:     }
                   1093: }
                   1094: 
1.263     www      1095: # -------------------------------------------------------------------- New chat
                   1096: 
                   1097: sub chatsend {
1.724     raeburn  1098:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1099:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1100:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1101:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1102:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1103: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1104: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1105: }
                   1106: 
                   1107: # ------------------------------------------ Find current version of a resource
                   1108: 
                   1109: sub getversion {
                   1110:     my $fname=&clutter(shift);
                   1111:     unless ($fname=~/^\/res\//) { return -1; }
                   1112:     return &currentversion(&filelocation('',$fname));
                   1113: }
                   1114: 
                   1115: sub currentversion {
                   1116:     my $fname=shift;
1.599     albertel 1117:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1118:     if (defined($cached)) { return $result; }
1.292     www      1119:     my $author=$fname;
                   1120:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1121:     my ($udom,$uname)=split(/\//,$author);
                   1122:     my $home=homeserver($uname,$udom);
                   1123:     if ($home eq 'no_host') { 
                   1124:         return -1; 
                   1125:     }
                   1126:     my $answer=reply("currentversion:$fname",$home);
                   1127:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1128: 	return -1;
                   1129:     }
1.599     albertel 1130:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1131: }
                   1132: 
1.1       albertel 1133: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1134: 
1.1       albertel 1135: sub subscribe {
                   1136:     my $fname=shift;
1.761     raeburn  1137:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1138:     $fname=~s/[\n\r]//g;
1.1       albertel 1139:     my $author=$fname;
                   1140:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1141:     my ($udom,$uname)=split(/\//,$author);
                   1142:     my $home=homeserver($uname,$udom);
1.335     albertel 1143:     if ($home eq 'no_host') {
                   1144:         return 'not_found';
1.1       albertel 1145:     }
                   1146:     my $answer=reply("sub:$fname",$home);
1.64      www      1147:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1148: 	$answer.=' by '.$home;
                   1149:     }
1.1       albertel 1150:     return $answer;
                   1151: }
                   1152:     
1.8       www      1153: # -------------------------------------------------------------- Replicate file
                   1154: 
                   1155: sub repcopy {
                   1156:     my $filename=shift;
1.23      www      1157:     $filename=~s/\/+/\//g;
1.607     raeburn  1158:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1159:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1160:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1161: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1162: 	return &repcopy_userfile($filename);
                   1163:     }
1.532     albertel 1164:     $filename=~s/[\n\r]//g;
1.8       www      1165:     my $transname="$filename.in.transfer";
1.607     raeburn  1166:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1167:     my $remoteurl=subscribe($filename);
1.64      www      1168:     if ($remoteurl =~ /^con_lost by/) {
                   1169: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1170:            return 'unavailable';
1.8       www      1171:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1172: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1173: 	   return 'not_found';
1.64      www      1174:     } elsif ($remoteurl =~ /^rejected by/) {
                   1175: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1176:            return 'forbidden';
1.20      www      1177:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1178:            return 'ok';
1.8       www      1179:     } else {
1.290     www      1180:         my $author=$filename;
                   1181:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1182:         my ($udom,$uname)=split(/\//,$author);
                   1183:         my $home=homeserver($uname,$udom);
                   1184:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1185:            my @parts=split(/\//,$filename);
                   1186:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1187:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1188:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1189: 	       return 'bad_request';
1.8       www      1190:            }
                   1191:            my $count;
                   1192:            for ($count=5;$count<$#parts;$count++) {
                   1193:                $path.="/$parts[$count]";
                   1194:                if ((-e $path)!=1) {
                   1195: 		   mkdir($path,0777);
                   1196:                }
                   1197:            }
                   1198:            my $ua=new LWP::UserAgent;
                   1199:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1200:            my $response=$ua->request($request,$transname);
                   1201:            if ($response->is_error()) {
                   1202: 	       unlink($transname);
                   1203:                my $message=$response->status_line;
1.672     albertel 1204:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      1205:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1206:                return 'unavailable';
1.8       www      1207:            } else {
1.16      www      1208: 	       if ($remoteurl!~/\.meta$/) {
                   1209:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1210:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1211:                   if ($mresponse->is_error()) {
                   1212: 		      unlink($filename.'.meta');
                   1213:                       &logthis(
1.672     albertel 1214:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      1215:                   }
                   1216: 	       }
1.8       www      1217:                rename($transname,$filename);
1.607     raeburn  1218:                return 'ok';
1.8       www      1219:            }
1.290     www      1220:        }
1.8       www      1221:     }
1.330     www      1222: }
                   1223: 
                   1224: # ------------------------------------------------ Get server side include body
                   1225: sub ssi_body {
1.381     albertel 1226:     my ($filelink,%form)=@_;
1.606     matthew  1227:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1228:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1229:     }
1.330     www      1230:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
1.381     albertel 1231:                                      &ssi($filelink,%form));
1.778     albertel 1232:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1233:     $output=~s/^.*?\<body[^\>]*\>//si;
                   1234:     $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
1.330     www      1235:     return $output;
1.8       www      1236: }
                   1237: 
1.15      www      1238: # --------------------------------------------------------- Server Side Include
                   1239: 
1.782     albertel 1240: sub absolute_url {
                   1241:     my ($host_name) = @_;
                   1242:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   1243:     if ($host_name eq '') {
                   1244: 	$host_name = $ENV{'SERVER_NAME'};
                   1245:     }
                   1246:     return $protocol.$host_name;
                   1247: }
                   1248: 
1.15      www      1249: sub ssi {
                   1250: 
1.23      www      1251:     my ($fn,%form)=@_;
1.15      www      1252: 
                   1253:     my $ua=new LWP::UserAgent;
1.23      www      1254:     
                   1255:     my $request;
1.711     albertel 1256: 
                   1257:     $form{'no_update_last_known'}=1;
                   1258: 
1.23      www      1259:     if (%form) {
1.782     albertel 1260:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.201     albertel 1261:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www      1262:     } else {
1.782     albertel 1263:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      1264:     }
                   1265: 
1.15      www      1266:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1267:     my $response=$ua->request($request);
                   1268: 
1.324     www      1269:     return $response->content;
                   1270: }
                   1271: 
                   1272: sub externalssi {
                   1273:     my ($url)=@_;
                   1274:     my $ua=new LWP::UserAgent;
                   1275:     my $request=new HTTP::Request('GET',$url);
                   1276:     my $response=$ua->request($request);
1.15      www      1277:     return $response->content;
                   1278: }
1.254     www      1279: 
1.492     albertel 1280: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1281: 
                   1282: sub allowuploaded {
                   1283:     my ($srcurl,$url)=@_;
                   1284:     $url=&clutter(&declutter($url));
                   1285:     my $dir=$url;
                   1286:     $dir=~s/\/[^\/]+$//;
                   1287:     my %httpref=();
                   1288:     my $httpurl=&hreflocation('',$url);
                   1289:     $httpref{'httpref.'.$httpurl}=$srcurl;
                   1290:     &Apache::lonnet::appenv(%httpref);
1.254     www      1291: }
1.477     raeburn  1292: 
1.478     albertel 1293: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 1294: # input: action, courseID, current domain, intended
1.637     raeburn  1295: #        path to file, source of file, instruction to parse file for objects,
                   1296: #        ref to hash for embedded objects,
                   1297: #        ref to hash for codebase of java objects.
                   1298: #
1.485     raeburn  1299: # output: url to file (if action was uploaddoc), 
                   1300: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  1301: #
1.478     albertel 1302: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   1303: # course.
1.477     raeburn  1304: #
1.478     albertel 1305: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1306: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   1307: #          course's home server.
1.477     raeburn  1308: #
1.478     albertel 1309: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   1310: #          be copied from $source (current location) to 
                   1311: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1312: #         and will then be copied to
                   1313: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   1314: #         course's home server.
1.485     raeburn  1315: #
1.481     raeburn  1316: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 1317: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  1318: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1319: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   1320: #         in course's home server.
1.637     raeburn  1321: #
1.477     raeburn  1322: 
                   1323: sub process_coursefile {
1.638     albertel 1324:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  1325:     my $fetchresult;
1.638     albertel 1326:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  1327:     if ($action eq 'propagate') {
1.638     albertel 1328:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1329: 			     $home);
1.481     raeburn  1330:     } else {
1.477     raeburn  1331:         my $fpath = '';
                   1332:         my $fname = $file;
1.478     albertel 1333:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  1334:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  1335:         my $filepath = &build_filepath($fpath);
1.481     raeburn  1336:         if ($action eq 'copy') {
                   1337:             if ($source eq '') {
                   1338:                 $fetchresult = 'no source file';
                   1339:                 return $fetchresult;
                   1340:             } else {
                   1341:                 my $destination = $filepath.'/'.$fname;
                   1342:                 rename($source,$destination);
                   1343:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1344:                                  $home);
1.481     raeburn  1345:             }
                   1346:         } elsif ($action eq 'uploaddoc') {
                   1347:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 1348:             print $fh $env{'form.'.$source};
1.481     raeburn  1349:             close($fh);
1.637     raeburn  1350:             if ($parser eq 'parse') {
                   1351:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
                   1352:                 unless ($parse_result eq 'ok') {
                   1353:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   1354:                 }
                   1355:             }
1.477     raeburn  1356:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1357:                                  $home);
1.481     raeburn  1358:             if ($fetchresult eq 'ok') {
                   1359:                 return '/uploaded/'.$fpath.'/'.$fname;
                   1360:             } else {
                   1361:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1362:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  1363:                 return '/adm/notfound.html';
                   1364:             }
1.477     raeburn  1365:         }
                   1366:     }
1.485     raeburn  1367:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  1368:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1369:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  1370:     }
                   1371:     return $fetchresult;
                   1372: }
                   1373: 
1.637     raeburn  1374: sub build_filepath {
                   1375:     my ($fpath) = @_;
                   1376:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   1377:     unless ($fpath eq '') {
                   1378:         my @parts=split('/',$fpath);
                   1379:         foreach my $part (@parts) {
                   1380:             $filepath.= '/'.$part;
                   1381:             if ((-e $filepath)!=1) {
                   1382:                 mkdir($filepath,0777);
                   1383:             }
                   1384:         }
                   1385:     }
                   1386:     return $filepath;
                   1387: }
                   1388: 
                   1389: sub store_edited_file {
1.638     albertel 1390:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  1391:     my $file = $primary_url;
                   1392:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   1393:     my $fpath = '';
                   1394:     my $fname = $file;
                   1395:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   1396:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   1397:     my $filepath = &build_filepath($fpath);
                   1398:     open(my $fh,'>'.$filepath.'/'.$fname);
                   1399:     print $fh $content;
                   1400:     close($fh);
1.638     albertel 1401:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  1402:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1403: 			  $home);
1.637     raeburn  1404:     if ($$fetchresult eq 'ok') {
                   1405:         return '/uploaded/'.$fpath.'/'.$fname;
                   1406:     } else {
1.638     albertel 1407:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   1408: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  1409:         return '/adm/notfound.html';
                   1410:     }
                   1411: }
                   1412: 
1.531     albertel 1413: sub clean_filename {
                   1414:     my ($fname)=@_;
1.315     www      1415: # Replace Windows backslashes by forward slashes
1.257     www      1416:     $fname=~s/\\/\//g;
1.315     www      1417: # Get rid of everything but the actual filename
1.257     www      1418:     $fname=~s/^.*\/([^\/]+)$/$1/;
1.315     www      1419: # Replace spaces by underscores
                   1420:     $fname=~s/\s+/\_/g;
                   1421: # Replace all other weird characters by nothing
1.317     www      1422:     $fname=~s/[^\w\.\-]//g;
1.540     albertel 1423: # Replace all .\d. sequences with _\d. so they no longer look like version
                   1424: # numbers
                   1425:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 1426:     return $fname;
                   1427: }
                   1428: 
1.608     albertel 1429: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 1430: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 1431: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 1432: #        $coursedoc - if true up to the current course
                   1433: #                     if false
                   1434: #        $subdir - directory in userfile to store the file into
                   1435: #        $parser, $allfiles, $codebase - unknown
                   1436: #
                   1437: # output: url of file in userspace, or error: <message> 
                   1438: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 1439: 
                   1440: 
1.531     albertel 1441: sub userfileupload {
1.719     banghart 1442:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,$destudom)=@_;
1.531     albertel 1443:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 1444:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 1445:     $fname=&clean_filename($fname);
1.315     www      1446: # See if there is anything left
1.257     www      1447:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 1448:     chop($env{'form.'.$formname});
1.523     raeburn  1449:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   1450:         my $now = time;
                   1451:         my $filepath = 'tmp/helprequests/'.$now;
                   1452:         my @parts=split(/\//,$filepath);
                   1453:         my $fullpath = $perlvar{'lonDaemons'};
                   1454:         for (my $i=0;$i<@parts;$i++) {
                   1455:             $fullpath .= '/'.$parts[$i];
                   1456:             if ((-e $fullpath)!=1) {
                   1457:                 mkdir($fullpath,0777);
                   1458:             }
                   1459:         }
                   1460:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 1461:         print $fh $env{'form.'.$formname};
1.523     raeburn  1462:         close($fh);
1.741     raeburn  1463:         return $fullpath.'/'.$fname;
                   1464:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   1465:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   1466:                        '_'.$env{'user.domain'}.'/pending';
                   1467:         my @parts=split(/\//,$filepath);
                   1468:         my $fullpath = $perlvar{'lonDaemons'};
                   1469:         for (my $i=0;$i<@parts;$i++) {
                   1470:             $fullpath .= '/'.$parts[$i];
                   1471:             if ((-e $fullpath)!=1) {
                   1472:                 mkdir($fullpath,0777);
                   1473:             }
                   1474:         }
                   1475:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   1476:         print $fh $env{'form.'.$formname};
                   1477:         close($fh);
                   1478:         return $fullpath.'/'.$fname;
1.523     raeburn  1479:     }
1.719     banghart 1480:     
1.258     www      1481: # Create the directory if not present
1.493     albertel 1482:     $fname="$subdir/$fname";
1.259     www      1483:     if ($coursedoc) {
1.638     albertel 1484: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1485: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  1486:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 1487:             return &finishuserfileupload($docuname,$docudom,
                   1488: 					 $formname,$fname,$parser,$allfiles,
                   1489: 					 $codebase);
1.481     raeburn  1490:         } else {
1.620     albertel 1491:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 1492:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   1493: 				       $fname,$formname,$parser,
                   1494: 				       $allfiles,$codebase);
1.481     raeburn  1495:         }
1.719     banghart 1496:     } elsif (defined($destuname)) {
                   1497:         my $docuname=$destuname;
                   1498:         my $docudom=$destudom;
                   1499: 	return &finishuserfileupload($docuname,$docudom,$formname,
                   1500: 				     $fname,$parser,$allfiles,$codebase);
                   1501:         
1.259     www      1502:     } else {
1.638     albertel 1503:         my $docuname=$env{'user.name'};
                   1504:         my $docudom=$env{'user.domain'};
1.714     raeburn  1505:         if (exists($env{'form.group'})) {
                   1506:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1507:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1508:         }
1.638     albertel 1509: 	return &finishuserfileupload($docuname,$docudom,$formname,
                   1510: 				     $fname,$parser,$allfiles,$codebase);
1.259     www      1511:     }
1.271     www      1512: }
                   1513: 
                   1514: sub finishuserfileupload {
1.638     albertel 1515:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase) = @_;
1.477     raeburn  1516:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      1517:     my $filepath=$perlvar{'lonDocRoot'};
1.494     albertel 1518:     my ($fnamepath,$file);
                   1519:     $file=$fname;
                   1520:     if ($fname=~m|/|) {
                   1521:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   1522: 	$path.=$fnamepath.'/';
                   1523:     }
1.259     www      1524:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      1525:     my $count;
                   1526:     for ($count=4;$count<=$#parts;$count++) {
                   1527:         $filepath.="/$parts[$count]";
                   1528:         if ((-e $filepath)!=1) {
                   1529: 	    mkdir($filepath,0777);
                   1530:         }
                   1531:     }
                   1532: # Save the file
                   1533:     {
1.701     albertel 1534: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   1535: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   1536: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   1537: 	    return '/adm/notfound.html';
                   1538: 	}
                   1539: 	if (!print FH ($env{'form.'.$formname})) {
                   1540: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   1541: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   1542: 	    return '/adm/notfound.html';
                   1543: 	}
1.570     albertel 1544: 	close(FH);
1.258     www      1545:     }
1.637     raeburn  1546:     if ($parser eq 'parse') {
1.638     albertel 1547:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
                   1548: 						   $codebase);
1.637     raeburn  1549:         unless ($parse_result eq 'ok') {
1.638     albertel 1550:             &logthis('Failed to parse '.$filepath.$file.
                   1551: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  1552:         }
                   1553:     }
1.259     www      1554: # Notify homeserver to grep it
                   1555: #
1.638     albertel 1556:     my $docuhome=&homeserver($docuname,$docudom);
1.494     albertel 1557:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      1558:     if ($fetchresult eq 'ok') {
1.259     www      1559: #
1.258     www      1560: # Return the URL to it
1.494     albertel 1561:         return '/uploaded/'.$path.$file;
1.263     www      1562:     } else {
1.494     albertel 1563:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   1564: 		 ': '.$fetchresult);
1.263     www      1565:         return '/adm/notfound.html';
                   1566:     }    
1.493     albertel 1567: }
                   1568: 
1.637     raeburn  1569: sub extract_embedded_items {
1.648     raeburn  1570:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
1.637     raeburn  1571:     my @state = ();
                   1572:     my %javafiles = (
                   1573:                       codebase => '',
                   1574:                       code => '',
                   1575:                       archive => ''
                   1576:                     );
                   1577:     my %mediafiles = (
                   1578:                       src => '',
                   1579:                       movie => '',
                   1580:                      );
1.648     raeburn  1581:     my $p;
                   1582:     if ($content) {
                   1583:         $p = HTML::LCParser->new($content);
                   1584:     } else {
                   1585:         $p = HTML::LCParser->new($filepath.'/'.$file);
                   1586:     }
1.641     albertel 1587:     while (my $t=$p->get_token()) {
1.640     albertel 1588: 	if ($t->[0] eq 'S') {
                   1589: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
                   1590: 	    push (@state, $tagname);
1.648     raeburn  1591:             if (lc($tagname) eq 'allow') {
                   1592:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   1593:             }
1.640     albertel 1594: 	    if (lc($tagname) eq 'img') {
                   1595: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   1596: 	    }
1.645     raeburn  1597:             if (lc($tagname) eq 'script') {
                   1598:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   1599:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   1600:                 } else {
                   1601:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   1602:                 }
                   1603:             }
                   1604:             if (lc($tagname) eq 'link') {
                   1605:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   1606:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   1607:                 }
                   1608:             }
1.640     albertel 1609: 	    if (lc($tagname) eq 'object' ||
                   1610: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   1611: 		foreach my $item (keys(%javafiles)) {
                   1612: 		    $javafiles{$item} = '';
                   1613: 		}
                   1614: 	    }
                   1615: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   1616: 		my $name = lc($attr->{'name'});
                   1617: 		foreach my $item (keys(%javafiles)) {
                   1618: 		    if ($name eq $item) {
                   1619: 			$javafiles{$item} = $attr->{'value'};
                   1620: 			last;
                   1621: 		    }
                   1622: 		}
                   1623: 		foreach my $item (keys(%mediafiles)) {
                   1624: 		    if ($name eq $item) {
                   1625: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   1626: 			last;
                   1627: 		    }
                   1628: 		}
                   1629: 	    }
                   1630: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   1631: 		foreach my $item (keys(%javafiles)) {
                   1632: 		    if ($attr->{$item}) {
                   1633: 			$javafiles{$item} = $attr->{$item};
                   1634: 			last;
                   1635: 		    }
                   1636: 		}
                   1637: 		foreach my $item (keys(%mediafiles)) {
                   1638: 		    if ($attr->{$item}) {
                   1639: 			&add_filetype($allfiles,$attr->{$item},$item);
                   1640: 			last;
                   1641: 		    }
                   1642: 		}
                   1643: 	    }
                   1644: 	} elsif ($t->[0] eq 'E') {
                   1645: 	    my ($tagname) = ($t->[1]);
                   1646: 	    if ($javafiles{'codebase'} ne '') {
                   1647: 		$javafiles{'codebase'} .= '/';
                   1648: 	    }  
                   1649: 	    if (lc($tagname) eq 'applet' ||
                   1650: 		lc($tagname) eq 'object' ||
                   1651: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   1652: 		) {
                   1653: 		foreach my $item (keys(%javafiles)) {
                   1654: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   1655: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   1656: 			&add_filetype($allfiles,$file,$item);
                   1657: 		    }
                   1658: 		}
                   1659: 	    } 
                   1660: 	    pop @state;
                   1661: 	}
                   1662:     }
1.637     raeburn  1663:     return 'ok';
                   1664: }
                   1665: 
1.639     albertel 1666: sub add_filetype {
                   1667:     my ($allfiles,$file,$type)=@_;
                   1668:     if (exists($allfiles->{$file})) {
                   1669: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   1670: 	    push(@{$allfiles->{$file}}, &escape($type));
                   1671: 	}
                   1672:     } else {
                   1673: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  1674:     }
                   1675: }
                   1676: 
1.493     albertel 1677: sub removeuploadedurl {
                   1678:     my ($url)=@_;
                   1679:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613     albertel 1680:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 1681: }
                   1682: 
                   1683: sub removeuserfile {
                   1684:     my ($docuname,$docudom,$fname)=@_;
                   1685:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  1686:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
                   1687:     if ($result eq 'ok') {
                   1688:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   1689:             my $metafile = $fname.'.meta';
                   1690:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
                   1691:         }
                   1692:     }
                   1693:     return $result;
1.257     www      1694: }
1.15      www      1695: 
1.530     albertel 1696: sub mkdiruserfile {
                   1697:     my ($docuname,$docudom,$dir)=@_;
                   1698:     my $home=&homeserver($docuname,$docudom);
                   1699:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   1700: }
                   1701: 
1.531     albertel 1702: sub renameuserfile {
                   1703:     my ($docuname,$docudom,$old,$new)=@_;
                   1704:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  1705:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   1706:                         &escape("$old").':'.&escape("$new"),$home);
                   1707:     if ($result eq 'ok') {
                   1708:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   1709:             my $oldmeta = $old.'.meta';
                   1710:             my $newmeta = $new.'.meta';
                   1711:             my $metaresult = 
                   1712:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
                   1713:         }
                   1714:     }
                   1715:     return $result;
1.531     albertel 1716: }
                   1717: 
1.14      www      1718: # ------------------------------------------------------------------------- Log
                   1719: 
                   1720: sub log {
                   1721:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      1722:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      1723: }
                   1724: 
                   1725: # ------------------------------------------------------------------ Course Log
1.352     www      1726: #
                   1727: # This routine flushes several buffers of non-mission-critical nature
                   1728: #
1.157     www      1729: 
                   1730: sub flushcourselogs {
1.352     www      1731:     &logthis('Flushing log buffers');
                   1732: #
                   1733: # course logs
                   1734: # This is a log of all transactions in a course, which can be used
                   1735: # for data mining purposes
                   1736: #
                   1737: # It also collects the courseid database, which lists last transaction
                   1738: # times and course titles for all courseids
                   1739: #
                   1740:     my %courseidbuffer=();
1.800     albertel 1741:     foreach my $crsid (keys %courselogs) {
1.352     www      1742:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      1743: 		          &escape($courselogs{$crsid}),
                   1744: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      1745: 	    delete $courselogs{$crsid};
                   1746:         } else {
                   1747:             &logthis('Failed to flush log buffer for '.$crsid);
                   1748:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 1749:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      1750:                         " exceeded maximum size, deleting.</font>");
                   1751:                delete $courselogs{$crsid};
                   1752:             }
1.352     www      1753:         }
                   1754:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
                   1755:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
1.516     raeburn  1756: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  1757:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.352     www      1758:         } else {
                   1759:            $courseidbuffer{$coursehombuf{$crsid}}=
1.516     raeburn  1760: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  1761:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.571     raeburn  1762:         }
1.191     harris41 1763:     }
1.352     www      1764: #
                   1765: # Write course id database (reverse lookup) to homeserver of courses 
                   1766: # Is used in pickcourse
                   1767: #
1.800     albertel 1768:     foreach my $crsid (keys(%courseidbuffer)) {
                   1769:         &courseidput($hostdom{$crsid},$courseidbuffer{$crsid},$crsid);
1.352     www      1770:     }
                   1771: #
                   1772: # File accesses
                   1773: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   1774: #
1.449     matthew  1775:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  1776:         if ($entry =~ /___count$/) {
                   1777:             my ($dom,$name);
                   1778:             ($dom,$name,undef)=($entry=~m:___(\w+)/(\w+)/(.*)___count$:);
                   1779:             if (! defined($dom) || $dom eq '' || 
                   1780:                 ! defined($name) || $name eq '') {
1.620     albertel 1781:                 my $cid = $env{'request.course.id'};
                   1782:                 $dom  = $env{'request.'.$cid.'.domain'};
                   1783:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  1784:             }
1.450     matthew  1785:             my $value = $accesshash{$entry};
                   1786:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   1787:             my %temphash=($url => $value);
1.449     matthew  1788:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   1789:             if ($result eq 'ok') {
                   1790:                 delete $accesshash{$entry};
                   1791:             } elsif ($result eq 'unknown_cmd') {
                   1792:                 # Target server has old code running on it.
1.450     matthew  1793:                 my %temphash=($entry => $value);
1.449     matthew  1794:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1795:                     delete $accesshash{$entry};
                   1796:                 }
                   1797:             }
                   1798:         } else {
1.458     matthew  1799:             my ($dom,$name) = ($entry=~m:___(\w+)/(\w+)/(.*)___(\w+)$:);
1.450     matthew  1800:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  1801:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1802:                 delete $accesshash{$entry};
                   1803:             }
1.185     www      1804:         }
1.191     harris41 1805:     }
1.352     www      1806: #
                   1807: # Roles
                   1808: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   1809: #
1.800     albertel 1810:     foreach my $entry (keys(%userrolehash)) {
1.351     www      1811:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      1812: 	    split(/\:/,$entry);
                   1813:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      1814:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      1815:                 $rudom,$runame) eq 'ok') {
                   1816: 	    delete $userrolehash{$entry};
                   1817:         }
                   1818:     }
1.662     raeburn  1819: #
                   1820: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   1821: #
                   1822:     my %domrolebuffer = ();
                   1823:     foreach my $entry (keys %domainrolehash) {
                   1824:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split/:/,$entry;
                   1825:         if ($domrolebuffer{$rudom}) {
                   1826:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   1827:                       '='.&escape($domainrolehash{$entry});
                   1828:         } else {
                   1829:             $domrolebuffer{$rudom}.=&escape($entry).
                   1830:                       '='.&escape($domainrolehash{$entry});
                   1831:         }
                   1832:         delete $domainrolehash{$entry};
                   1833:     }
                   1834:     foreach my $dom (keys(%domrolebuffer)) {
                   1835:         foreach my $tryserver (keys %libserv) {
                   1836:             if ($hostdom{$tryserver} eq $dom) {
                   1837:                 unless (&reply('domroleput:'.$dom.':'.
                   1838:                   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   1839:                     &logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   1840:                 }
                   1841:             }
                   1842:         }
                   1843:     }
1.186     www      1844:     $dumpcount++;
1.157     www      1845: }
                   1846: 
                   1847: sub courselog {
                   1848:     my $what=shift;
1.158     www      1849:     $what=time.':'.$what;
1.620     albertel 1850:     unless ($env{'request.course.id'}) { return ''; }
                   1851:     $coursedombuf{$env{'request.course.id'}}=
                   1852:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   1853:     $coursenumbuf{$env{'request.course.id'}}=
                   1854:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   1855:     $coursehombuf{$env{'request.course.id'}}=
                   1856:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   1857:     $coursedescrbuf{$env{'request.course.id'}}=
                   1858:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   1859:     $courseinstcodebuf{$env{'request.course.id'}}=
                   1860:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   1861:     $courseownerbuf{$env{'request.course.id'}}=
                   1862:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  1863:     $coursetypebuf{$env{'request.course.id'}}=
                   1864:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 1865:     if (defined $courselogs{$env{'request.course.id'}}) {
                   1866: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      1867:     } else {
1.620     albertel 1868: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      1869:     }
1.620     albertel 1870:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      1871: 	&flushcourselogs();
                   1872:     }
1.158     www      1873: }
                   1874: 
                   1875: sub courseacclog {
                   1876:     my $fnsymb=shift;
1.620     albertel 1877:     unless ($env{'request.course.id'}) { return ''; }
                   1878:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 1879:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      1880:         $what.=':POST';
1.583     matthew  1881:         # FIXME: Probably ought to escape things....
1.800     albertel 1882: 	foreach my $key (keys(%env)) {
                   1883:             if ($key=~/^form\.(.*)/) {
                   1884: 		$what.=':'.$1.'='.$env{$key};
1.158     www      1885:             }
1.191     harris41 1886:         }
1.583     matthew  1887:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   1888:         # FIXME: We should not be depending on a form parameter that someone
                   1889:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 1890:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  1891:             $what.= ':POST';
                   1892:             # FIXME: Probably ought to escape things....
                   1893:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   1894:                                  'crsdiscuss') {
1.620     albertel 1895:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  1896:             }
                   1897:         }
1.158     www      1898:     }
                   1899:     &courselog($what);
1.149     www      1900: }
                   1901: 
1.185     www      1902: sub countacc {
                   1903:     my $url=&declutter(shift);
1.458     matthew  1904:     return if (! defined($url) || $url eq '');
1.620     albertel 1905:     unless ($env{'request.course.id'}) { return ''; }
                   1906:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      1907:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  1908:     $accesshash{$key}++;
1.185     www      1909: }
1.349     www      1910: 
1.361     www      1911: sub linklog {
                   1912:     my ($from,$to)=@_;
                   1913:     $from=&declutter($from);
                   1914:     $to=&declutter($to);
                   1915:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   1916:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   1917: }
                   1918:   
1.349     www      1919: sub userrolelog {
                   1920:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  1921:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  1922:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  1923:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   1924:         ($trole=~/^ta/)) {
1.350     www      1925:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   1926:        $userrolehash
                   1927:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      1928:                     =$tend.':'.$tstart;
1.662     raeburn  1929:     }
                   1930:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   1931:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   1932:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   1933:         ($trole=~/^sc/)) {
                   1934:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   1935:        $domainrolehash
                   1936:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   1937:                     = $tend.':'.$tstart;
                   1938:     }
1.351     www      1939: }
                   1940: 
                   1941: sub get_course_adv_roles {
                   1942:     my $cid=shift;
1.620     albertel 1943:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      1944:     my %coursehash=&coursedescription($cid);
1.470     www      1945:     my %nothide=();
1.800     albertel 1946:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   1947: 	$nothide{join(':',split(/[\@\:]/,$user))}=1;
1.470     www      1948:     }
1.351     www      1949:     my %returnhash=();
                   1950:     my %dumphash=
                   1951:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   1952:     my $now=time;
1.800     albertel 1953:     foreach my $entry (keys %dumphash) {
                   1954: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      1955:         if (($tstart) && ($tstart<0)) { next; }
                   1956:         if (($tend) && ($tend<$now)) { next; }
                   1957:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 1958:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 1959: 	if ($username eq '' || $domain eq '') { next; }
1.470     www      1960: 	if ((&privileged($username,$domain)) && 
                   1961: 	    (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 1962: 	if ($role eq 'cr') { next; }
1.351     www      1963:         my $key=&plaintext($role);
                   1964:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
                   1965:         if ($returnhash{$key}) {
                   1966: 	    $returnhash{$key}.=','.$username.':'.$domain;
                   1967:         } else {
                   1968:             $returnhash{$key}=$username.':'.$domain;
                   1969:         }
1.400     www      1970:      }
                   1971:     return %returnhash;
                   1972: }
                   1973: 
                   1974: sub get_my_roles {
                   1975:     my ($uname,$udom)=@_;
1.620     albertel 1976:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   1977:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.400     www      1978:     my %dumphash=
                   1979:             &dump('nohist_userroles',$udom,$uname);
                   1980:     my %returnhash=();
                   1981:     my $now=time;
1.800     albertel 1982:     foreach my $entry (keys(%dumphash)) {
                   1983: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.400     www      1984:         if (($tstart) && ($tstart<0)) { next; }
                   1985:         if (($tend) && ($tend<$now)) { next; }
                   1986:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 1987:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.400     www      1988: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
1.373     www      1989:      }
                   1990:     return %returnhash;
1.399     www      1991: }
                   1992: 
                   1993: # ----------------------------------------------------- Frontpage Announcements
                   1994: #
                   1995: #
                   1996: 
                   1997: sub postannounce {
                   1998:     my ($server,$text)=@_;
                   1999:     unless (&allowed('psa',$hostdom{$server})) { return 'refused'; }
                   2000:     unless ($text=~/\w/) { $text=''; }
                   2001:     return &reply('setannounce:'.&escape($text),$server);
                   2002: }
                   2003: 
                   2004: sub getannounce {
1.448     albertel 2005: 
                   2006:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      2007: 	my $announcement='';
1.800     albertel 2008: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 2009: 	close($fh);
1.399     www      2010: 	if ($announcement=~/\w/) { 
                   2011: 	    return 
                   2012:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 2013:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      2014: 	} else {
                   2015: 	    return '';
                   2016: 	}
                   2017:     } else {
                   2018: 	return '';
                   2019:     }
1.351     www      2020: }
1.353     www      2021: 
                   2022: # ---------------------------------------------------------- Course ID routines
                   2023: # Deal with domain's nohist_courseid.db files
                   2024: #
                   2025: 
                   2026: sub courseidput {
                   2027:     my ($domain,$what,$coursehome)=@_;
                   2028:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   2029: }
                   2030: 
                   2031: sub courseiddump {
1.791     raeburn  2032:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok)=@_;
1.353     www      2033:     my %returnhash=();
1.355     www      2034:     unless ($domfilter) { $domfilter=''; }
1.353     www      2035:     foreach my $tryserver (keys %libserv) {
1.511     raeburn  2036:         if ( ($hostidflag == 1 && grep/^$tryserver$/,@{$hostidref}) || (!defined($hostidflag)) ) {
1.506     raeburn  2037: 	    if ((!$domfilter) || ($hostdom{$tryserver} eq $domfilter)) {
1.800     albertel 2038: 	        foreach my $line (
1.506     raeburn  2039:                  split(/\&/,&reply('courseiddump:'.$hostdom{$tryserver}.':'.
1.571     raeburn  2040: 			       $sincefilter.':'.&escape($descfilter).':'.
1.791     raeburn  2041:                                &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter).':'.&escape($typefilter).':'.&escape($regexp_ok),
1.354     www      2042:                                $tryserver))) {
1.800     albertel 2043: 		    my ($key,$value)=split(/\=/,$line,2);
1.506     raeburn  2044:                     if (($key) && ($value)) {
1.516     raeburn  2045: 		        $returnhash{&unescape($key)}=$value;
1.506     raeburn  2046:                     }
1.353     www      2047:                 }
                   2048:             }
                   2049:         }
                   2050:     }
                   2051:     return %returnhash;
                   2052: }
                   2053: 
1.658     raeburn  2054: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  2055: 
                   2056: sub dcmailput {
1.685     raeburn  2057:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  2058:     my $status = &Apache::lonnet::critical(
1.740     www      2059:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   2060:        &escape($message),$server);
1.662     raeburn  2061:     return $status;
                   2062: }
                   2063: 
1.658     raeburn  2064: sub dcmaildump {
                   2065:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  2066:     my %returnhash=();
                   2067:     if (exists($domain_primary{$dom})) {
                   2068:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   2069:                                                          &escape($enddate).':';
                   2070: 	my @esc_senders=map { &escape($_)} @$senders;
                   2071: 	$cmd.=&escape(join('&',@esc_senders));
1.800     albertel 2072: 	foreach my $line (split(/\&/,&reply($cmd,$domain_primary{$dom}))) {
                   2073:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  2074:             if (($key) && ($value)) {
                   2075:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  2076:             }
                   2077:         }
                   2078:     }
                   2079:     return %returnhash;
                   2080: }
1.662     raeburn  2081: # ---------------------------------------------------------- Domain roles
                   2082: 
                   2083: sub get_domain_roles {
                   2084:     my ($dom,$roles,$startdate,$enddate)=@_;
                   2085:     if (undef($startdate) || $startdate eq '') {
                   2086:         $startdate = '.';
                   2087:     }
                   2088:     if (undef($enddate) || $enddate eq '') {
                   2089:         $enddate = '.';
                   2090:     }
                   2091:     my $rolelist = join(':',@{$roles});
                   2092:     my %personnel = ();
                   2093:     foreach my $tryserver (keys(%libserv)) {
                   2094:         if ($hostdom{$tryserver} eq $dom) {
                   2095:             %{$personnel{$tryserver}}=();
1.800     albertel 2096:             foreach my $line (
1.662     raeburn  2097:                 split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   2098:                    &escape($startdate).':'.&escape($enddate).':'.
                   2099:                    &escape($rolelist), $tryserver))) {
1.800     albertel 2100:                 my ($key,$value) = split(/\=/,$line,2);
1.662     raeburn  2101:                 if (($key) && ($value)) {
                   2102:                     $personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   2103:                 }
                   2104:             }
                   2105:         }
                   2106:     }
                   2107:     return %personnel;
                   2108: }
1.658     raeburn  2109: 
1.149     www      2110: # ----------------------------------------------------------- Check out an item
                   2111: 
1.504     albertel 2112: sub get_first_access {
                   2113:     my ($type,$argsymb)=@_;
1.790     albertel 2114:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2115:     if ($argsymb) { $symb=$argsymb; }
                   2116:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2117:     if ($type eq 'map') {
                   2118: 	$res=&symbread($map);
                   2119:     } else {
                   2120: 	$res=$symb;
                   2121:     }
                   2122:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   2123:     return $times{"$courseid\0$res"};
1.504     albertel 2124: }
                   2125: 
                   2126: sub set_first_access {
                   2127:     my ($type)=@_;
1.790     albertel 2128:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2129:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2130:     if ($type eq 'map') {
                   2131: 	$res=&symbread($map);
                   2132:     } else {
                   2133: 	$res=$symb;
                   2134:     }
                   2135:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 2136:     if (!$firstaccess) {
1.588     albertel 2137: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 2138:     }
                   2139:     return 'already_set';
1.504     albertel 2140: }
                   2141: 
1.149     www      2142: sub checkout {
                   2143:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   2144:     my $now=time;
                   2145:     my $lonhost=$perlvar{'lonHostID'};
                   2146:     my $infostr=&escape(
1.234     www      2147:                  'CHECKOUTTOKEN&'.
1.149     www      2148:                  $tuname.'&'.
                   2149:                  $tudom.'&'.
                   2150:                  $tcrsid.'&'.
                   2151:                  $symb.'&'.
                   2152: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   2153:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      2154:     if ($token=~/^error\:/) { 
1.672     albertel 2155:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2156:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2157:                  "</font>");
                   2158:         return ''; 
                   2159:     }
                   2160: 
1.149     www      2161:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   2162:     $token=~tr/a-z/A-Z/;
                   2163: 
1.153     www      2164:     my %infohash=('resource.0.outtoken' => $token,
                   2165:                   'resource.0.checkouttime' => $now,
                   2166:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      2167: 
                   2168:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2169:        return '';
1.151     www      2170:     } else {
1.672     albertel 2171:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2172:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2173:                  "</font>");
1.149     www      2174:     }    
                   2175: 
                   2176:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2177:                          &escape('Checkout '.$infostr.' - '.
                   2178:                                                  $token)) ne 'ok') {
                   2179: 	return '';
1.151     www      2180:     } else {
1.672     albertel 2181:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2182:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2183:                  "</font>");
1.149     www      2184:     }
1.151     www      2185:     return $token;
1.149     www      2186: }
                   2187: 
                   2188: # ------------------------------------------------------------ Check in an item
                   2189: 
                   2190: sub checkin {
                   2191:     my $token=shift;
1.150     www      2192:     my $now=time;
                   2193:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   2194:     $lonhost=~tr/A-Z/a-z/;
1.595     albertel 2195:     my $dtoken=$ta.'_'.$hostname{$lonhost}.'_'.$tb;
1.150     www      2196:     $dtoken=~s/\W/\_/g;
1.234     www      2197:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      2198:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   2199: 
1.154     www      2200:     unless (($tuname) && ($tudom)) {
                   2201:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   2202:         return '';
                   2203:     }
                   2204:     
                   2205:     unless (&allowed('mgr',$tcrsid)) {
                   2206:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 2207:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      2208:         return '';
                   2209:     }
                   2210: 
1.153     www      2211:     my %infohash=('resource.0.intoken' => $token,
                   2212:                   'resource.0.checkintime' => $now,
                   2213:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      2214: 
                   2215:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2216:        return '';
                   2217:     }    
                   2218: 
                   2219:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2220:                          &escape('Checkin - '.$token)) ne 'ok') {
                   2221: 	return '';
                   2222:     }
                   2223: 
                   2224:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      2225: }
                   2226: 
                   2227: # --------------------------------------------- Set Expire Date for Spreadsheet
                   2228: 
                   2229: sub expirespread {
                   2230:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 2231:     my $cid=$env{'request.course.id'}; 
1.110     www      2232:     if ($cid) {
                   2233:        my $now=time;
                   2234:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 2235:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   2236:                             $env{'course.'.$cid.'.num'}.
1.110     www      2237: 	        	    ':nohist_expirationdates:'.
                   2238:                             &escape($key).'='.$now,
1.620     albertel 2239:                             $env{'course.'.$cid.'.home'})
1.110     www      2240:     }
                   2241:     return 'ok';
1.14      www      2242: }
                   2243: 
1.109     www      2244: # ----------------------------------------------------- Devalidate Spreadsheets
                   2245: 
                   2246: sub devalidate {
1.325     www      2247:     my ($symb,$uname,$udom)=@_;
1.620     albertel 2248:     my $cid=$env{'request.course.id'}; 
1.109     www      2249:     if ($cid) {
1.391     matthew  2250:         # delete the stored spreadsheets for
                   2251:         # - the student level sheet of this user in course's homespace
                   2252:         # - the assessment level sheet for this resource 
                   2253:         #   for this user in user's homespace
1.553     albertel 2254: 	# - current conditional state info
1.325     www      2255: 	my $key=$uname.':'.$udom.':';
1.109     www      2256:         my $status=
1.299     matthew  2257: 	    &del('nohist_calculatedsheets',
1.391     matthew  2258: 		 [$key.'studentcalc:'],
1.620     albertel 2259: 		 $env{'course.'.$cid.'.domain'},
                   2260: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 2261: 		.' '.
                   2262: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  2263: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      2264:         unless ($status eq 'ok ok') {
                   2265:            &logthis('Could not devalidate spreadsheet '.
1.325     www      2266:                     $uname.' at '.$udom.' for '.
1.109     www      2267: 		    $symb.': '.$status);
1.133     albertel 2268:         }
1.553     albertel 2269: 	&delenv('user.state.'.$cid);
1.109     www      2270:     }
                   2271: }
                   2272: 
1.265     albertel 2273: sub get_scalar {
                   2274:     my ($string,$end) = @_;
                   2275:     my $value;
                   2276:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   2277: 	$value = $1;
                   2278:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   2279: 	$value = $1;
                   2280:     }
                   2281:     return &unescape($value);
                   2282: }
                   2283: 
                   2284: sub array2str {
                   2285:   my (@array) = @_;
                   2286:   my $result=&arrayref2str(\@array);
                   2287:   $result=~s/^__ARRAY_REF__//;
                   2288:   $result=~s/__END_ARRAY_REF__$//;
                   2289:   return $result;
                   2290: }
                   2291: 
1.204     albertel 2292: sub arrayref2str {
                   2293:   my ($arrayref) = @_;
1.265     albertel 2294:   my $result='__ARRAY_REF__';
1.204     albertel 2295:   foreach my $elem (@$arrayref) {
1.265     albertel 2296:     if(ref($elem) eq 'ARRAY') {
                   2297:       $result.=&arrayref2str($elem).'&';
                   2298:     } elsif(ref($elem) eq 'HASH') {
                   2299:       $result.=&hashref2str($elem).'&';
                   2300:     } elsif(ref($elem)) {
                   2301:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 2302:     } else {
                   2303:       $result.=&escape($elem).'&';
                   2304:     }
                   2305:   }
                   2306:   $result=~s/\&$//;
1.265     albertel 2307:   $result .= '__END_ARRAY_REF__';
1.204     albertel 2308:   return $result;
                   2309: }
                   2310: 
1.168     albertel 2311: sub hash2str {
1.204     albertel 2312:   my (%hash) = @_;
                   2313:   my $result=&hashref2str(\%hash);
1.265     albertel 2314:   $result=~s/^__HASH_REF__//;
                   2315:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 2316:   return $result;
                   2317: }
                   2318: 
                   2319: sub hashref2str {
                   2320:   my ($hashref)=@_;
1.265     albertel 2321:   my $result='__HASH_REF__';
1.800     albertel 2322:   foreach my $key (sort(keys(%$hashref))) {
                   2323:     if (ref($key) eq 'ARRAY') {
                   2324:       $result.=&arrayref2str($key).'=';
                   2325:     } elsif (ref($key) eq 'HASH') {
                   2326:       $result.=&hashref2str($key).'=';
                   2327:     } elsif (ref($key)) {
1.265     albertel 2328:       $result.='=';
1.800     albertel 2329:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 2330:     } else {
1.800     albertel 2331: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 2332:     }
                   2333: 
1.800     albertel 2334:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   2335:       $result.=&arrayref2str($hashref->{$key}).'&';
                   2336:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   2337:       $result.=&hashref2str($hashref->{$key}).'&';
                   2338:     } elsif(ref($hashref->{$key})) {
1.265     albertel 2339:        $result.='&';
1.800     albertel 2340:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 2341:     } else {
1.800     albertel 2342:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 2343:     }
                   2344:   }
1.168     albertel 2345:   $result=~s/\&$//;
1.265     albertel 2346:   $result .= '__END_HASH_REF__';
1.168     albertel 2347:   return $result;
                   2348: }
                   2349: 
                   2350: sub str2hash {
1.265     albertel 2351:     my ($string)=@_;
                   2352:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   2353:     return %$hash;
                   2354: }
                   2355: 
                   2356: sub str2hashref {
1.168     albertel 2357:   my ($string) = @_;
1.265     albertel 2358: 
                   2359:   my %hash;
                   2360: 
                   2361:   if($string !~ /^__HASH_REF__/) {
                   2362:       if (! ($string eq '' || !defined($string))) {
                   2363: 	  $hash{'error'}='Not hash reference';
                   2364:       }
                   2365:       return (\%hash, $string);
                   2366:   }
                   2367: 
                   2368:   $string =~ s/^__HASH_REF__//;
                   2369: 
                   2370:   while($string !~ /^__END_HASH_REF__/) {
                   2371:       #key
                   2372:       my $key='';
                   2373:       if($string =~ /^__HASH_REF__/) {
                   2374:           ($key, $string)=&str2hashref($string);
                   2375:           if(defined($key->{'error'})) {
                   2376:               $hash{'error'}='Bad data';
                   2377:               return (\%hash, $string);
                   2378:           }
                   2379:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2380:           ($key, $string)=&str2arrayref($string);
                   2381:           if($key->[0] eq 'Array reference error') {
                   2382:               $hash{'error'}='Bad data';
                   2383:               return (\%hash, $string);
                   2384:           }
                   2385:       } else {
                   2386:           $string =~ s/^(.*?)=//;
1.267     albertel 2387: 	  $key=&unescape($1);
1.265     albertel 2388:       }
                   2389:       $string =~ s/^=//;
                   2390: 
                   2391:       #value
                   2392:       my $value='';
                   2393:       if($string =~ /^__HASH_REF__/) {
                   2394:           ($value, $string)=&str2hashref($string);
                   2395:           if(defined($value->{'error'})) {
                   2396:               $hash{'error'}='Bad data';
                   2397:               return (\%hash, $string);
                   2398:           }
                   2399:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2400:           ($value, $string)=&str2arrayref($string);
                   2401:           if($value->[0] eq 'Array reference error') {
                   2402:               $hash{'error'}='Bad data';
                   2403:               return (\%hash, $string);
                   2404:           }
                   2405:       } else {
                   2406: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   2407:       }
                   2408:       $string =~ s/^&//;
                   2409: 
                   2410:       $hash{$key}=$value;
1.204     albertel 2411:   }
1.265     albertel 2412: 
                   2413:   $string =~ s/^__END_HASH_REF__//;
                   2414: 
                   2415:   return (\%hash, $string);
1.204     albertel 2416: }
                   2417: 
                   2418: sub str2array {
1.265     albertel 2419:     my ($string)=@_;
                   2420:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   2421:     return @$array;
                   2422: }
                   2423: 
                   2424: sub str2arrayref {
1.204     albertel 2425:   my ($string) = @_;
1.265     albertel 2426:   my @array;
                   2427: 
                   2428:   if($string !~ /^__ARRAY_REF__/) {
                   2429:       if (! ($string eq '' || !defined($string))) {
                   2430: 	  $array[0]='Array reference error';
                   2431:       }
                   2432:       return (\@array, $string);
                   2433:   }
                   2434: 
                   2435:   $string =~ s/^__ARRAY_REF__//;
                   2436: 
                   2437:   while($string !~ /^__END_ARRAY_REF__/) {
                   2438:       my $value='';
                   2439:       if($string =~ /^__HASH_REF__/) {
                   2440:           ($value, $string)=&str2hashref($string);
                   2441:           if(defined($value->{'error'})) {
                   2442:               $array[0] ='Array reference error';
                   2443:               return (\@array, $string);
                   2444:           }
                   2445:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2446:           ($value, $string)=&str2arrayref($string);
                   2447:           if($value->[0] eq 'Array reference error') {
                   2448:               $array[0] ='Array reference error';
                   2449:               return (\@array, $string);
                   2450:           }
                   2451:       } else {
                   2452: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   2453:       }
                   2454:       $string =~ s/^&//;
                   2455: 
                   2456:       push(@array, $value);
1.191     harris41 2457:   }
1.265     albertel 2458: 
                   2459:   $string =~ s/^__END_ARRAY_REF__//;
                   2460: 
                   2461:   return (\@array, $string);
1.168     albertel 2462: }
                   2463: 
1.167     albertel 2464: # -------------------------------------------------------------------Temp Store
                   2465: 
1.168     albertel 2466: sub tmpreset {
                   2467:   my ($symb,$namespace,$domain,$stuname) = @_;
                   2468:   if (!$symb) {
                   2469:     $symb=&symbread();
1.620     albertel 2470:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2471:   }
                   2472:   $symb=escape($symb);
                   2473: 
1.620     albertel 2474:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 2475:   $namespace=~s/\//\_/g;
                   2476:   $namespace=~s/\W//g;
                   2477: 
1.620     albertel 2478:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2479:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2480:   if ($domain eq 'public' && $stuname eq 'public') {
                   2481:       $stuname=$ENV{'REMOTE_ADDR'};
                   2482:   }
1.168     albertel 2483:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2484:   my %hash;
                   2485:   if (tie(%hash,'GDBM_File',
                   2486: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2487: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2488:     foreach my $key (keys %hash) {
1.180     albertel 2489:       if ($key=~ /:$symb/) {
1.168     albertel 2490: 	delete($hash{$key});
                   2491:       }
                   2492:     }
                   2493:   }
                   2494: }
                   2495: 
1.167     albertel 2496: sub tmpstore {
1.168     albertel 2497:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2498: 
                   2499:   if (!$symb) {
                   2500:     $symb=&symbread();
1.620     albertel 2501:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2502:   }
                   2503:   $symb=escape($symb);
                   2504: 
                   2505:   if (!$namespace) {
                   2506:     # I don't think we would ever want to store this for a course.
                   2507:     # it seems this will only be used if we don't have a course.
1.620     albertel 2508:     #$namespace=$env{'request.course.id'};
1.168     albertel 2509:     #if (!$namespace) {
1.620     albertel 2510:       $namespace=$env{'request.state'};
1.168     albertel 2511:     #}
                   2512:   }
                   2513:   $namespace=~s/\//\_/g;
                   2514:   $namespace=~s/\W//g;
1.620     albertel 2515:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2516:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2517:   if ($domain eq 'public' && $stuname eq 'public') {
                   2518:       $stuname=$ENV{'REMOTE_ADDR'};
                   2519:   }
1.168     albertel 2520:   my $now=time;
                   2521:   my %hash;
                   2522:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2523:   if (tie(%hash,'GDBM_File',
                   2524: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2525: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2526:     $hash{"version:$symb"}++;
                   2527:     my $version=$hash{"version:$symb"};
                   2528:     my $allkeys=''; 
                   2529:     foreach my $key (keys(%$storehash)) {
                   2530:       $allkeys.=$key.':';
1.591     albertel 2531:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 2532:     }
                   2533:     $hash{"$version:$symb:timestamp"}=$now;
                   2534:     $allkeys.='timestamp';
                   2535:     $hash{"$version:keys:$symb"}=$allkeys;
                   2536:     if (untie(%hash)) {
                   2537:       return 'ok';
                   2538:     } else {
                   2539:       return "error:$!";
                   2540:     }
                   2541:   } else {
                   2542:     return "error:$!";
                   2543:   }
                   2544: }
1.167     albertel 2545: 
1.168     albertel 2546: # -----------------------------------------------------------------Temp Restore
1.167     albertel 2547: 
1.168     albertel 2548: sub tmprestore {
                   2549:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 2550: 
1.168     albertel 2551:   if (!$symb) {
                   2552:     $symb=&symbread();
1.620     albertel 2553:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2554:   }
                   2555:   $symb=escape($symb);
                   2556: 
1.620     albertel 2557:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 2558: 
1.620     albertel 2559:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2560:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2561:   if ($domain eq 'public' && $stuname eq 'public') {
                   2562:       $stuname=$ENV{'REMOTE_ADDR'};
                   2563:   }
1.168     albertel 2564:   my %returnhash;
                   2565:   $namespace=~s/\//\_/g;
                   2566:   $namespace=~s/\W//g;
                   2567:   my %hash;
                   2568:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2569:   if (tie(%hash,'GDBM_File',
                   2570: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2571: 	  &GDBM_READER(),0640)) {
1.168     albertel 2572:     my $version=$hash{"version:$symb"};
                   2573:     $returnhash{'version'}=$version;
                   2574:     my $scope;
                   2575:     for ($scope=1;$scope<=$version;$scope++) {
                   2576:       my $vkeys=$hash{"$scope:keys:$symb"};
                   2577:       my @keys=split(/:/,$vkeys);
                   2578:       my $key;
                   2579:       $returnhash{"$scope:keys"}=$vkeys;
                   2580:       foreach $key (@keys) {
1.591     albertel 2581: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   2582: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 2583:       }
                   2584:     }
1.168     albertel 2585:     if (!(untie(%hash))) {
                   2586:       return "error:$!";
                   2587:     }
                   2588:   } else {
                   2589:     return "error:$!";
                   2590:   }
                   2591:   return %returnhash;
1.167     albertel 2592: }
                   2593: 
1.9       www      2594: # ----------------------------------------------------------------------- Store
                   2595: 
                   2596: sub store {
1.124     www      2597:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2598:     my $home='';
                   2599: 
1.168     albertel 2600:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2601: 
1.213     www      2602:     $symb=&symbclean($symb);
1.122     albertel 2603:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2604: 
1.620     albertel 2605:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2606:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2607: 
                   2608:     &devalidate($symb,$stuname,$domain);
1.109     www      2609: 
                   2610:     $symb=escape($symb);
1.187     www      2611:     if (!$namespace) { 
1.620     albertel 2612:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2613:           return ''; 
                   2614:        } 
                   2615:     }
1.620     albertel 2616:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2617: 
                   2618:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2619:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   2620: 
1.12      www      2621:     my $namevalue='';
1.800     albertel 2622:     foreach my $key (keys(%$storehash)) {
                   2623:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 2624:     }
1.12      www      2625:     $namevalue=~s/\&$//;
1.187     www      2626:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      2627:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      2628: }
                   2629: 
1.47      www      2630: # -------------------------------------------------------------- Critical Store
                   2631: 
                   2632: sub cstore {
1.124     www      2633:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2634:     my $home='';
                   2635: 
1.168     albertel 2636:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2637: 
1.213     www      2638:     $symb=&symbclean($symb);
1.122     albertel 2639:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2640: 
1.620     albertel 2641:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2642:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2643: 
                   2644:     &devalidate($symb,$stuname,$domain);
1.109     www      2645: 
                   2646:     $symb=escape($symb);
1.187     www      2647:     if (!$namespace) { 
1.620     albertel 2648:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2649:           return ''; 
                   2650:        } 
                   2651:     }
1.620     albertel 2652:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2653: 
                   2654:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2655:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 2656: 
1.47      www      2657:     my $namevalue='';
1.800     albertel 2658:     foreach my $key (keys(%$storehash)) {
                   2659:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 2660:     }
1.47      www      2661:     $namevalue=~s/\&$//;
1.187     www      2662:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      2663:     return critical
                   2664:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      2665: }
                   2666: 
1.9       www      2667: # --------------------------------------------------------------------- Restore
                   2668: 
                   2669: sub restore {
1.124     www      2670:     my ($symb,$namespace,$domain,$stuname) = @_;
                   2671:     my $home='';
                   2672: 
1.168     albertel 2673:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2674: 
1.122     albertel 2675:     if (!$symb) {
                   2676:       unless ($symb=escape(&symbread())) { return ''; }
                   2677:     } else {
1.213     www      2678:       $symb=&escape(&symbclean($symb));
1.122     albertel 2679:     }
1.188     www      2680:     if (!$namespace) { 
1.620     albertel 2681:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      2682:           return ''; 
                   2683:        } 
                   2684:     }
1.620     albertel 2685:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2686:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   2687:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 2688:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   2689: 
1.12      www      2690:     my %returnhash=();
1.800     albertel 2691:     foreach my $line (split(/\&/,$answer)) {
                   2692: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 2693:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 2694:     }
1.75      www      2695:     my $version;
                   2696:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 2697:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   2698:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 2699:        }
1.75      www      2700:     }
1.13      www      2701:     return %returnhash;
1.34      www      2702: }
                   2703: 
                   2704: # ---------------------------------------------------------- Course Description
                   2705: 
                   2706: sub coursedescription {
1.731     albertel 2707:     my ($courseid,$args)=@_;
1.34      www      2708:     $courseid=~s/^\///;
1.49      www      2709:     $courseid=~s/\_/\//g;
1.34      www      2710:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 2711:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 2712:     my $normalid=$cdomain.'_'.$cnum;
                   2713:     # need to always cache even if we get errors otherwise we keep 
                   2714:     # trying and trying and trying to get the course description.
                   2715:     my %envhash=();
                   2716:     my %returnhash=();
1.731     albertel 2717:     
                   2718:     my $expiretime=600;
                   2719:     if ($env{'request.course.id'} eq $normalid) {
                   2720: 	$expiretime=120;
                   2721:     }
                   2722: 
                   2723:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   2724:     if (!$args->{'freshen_cache'}
                   2725: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   2726: 	foreach my $key (keys(%env)) {
                   2727: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   2728: 	    my ($setting) = $1;
                   2729: 	    $returnhash{$setting} = $env{$key};
                   2730: 	}
                   2731: 	return %returnhash;
                   2732:     }
                   2733: 
                   2734:     # get the data agin
                   2735:     if (!$args->{'one_time'}) {
                   2736: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   2737:     }
1.34      www      2738:     if ($chome ne 'no_host') {
1.302     albertel 2739:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 2740:        if (!exists($returnhash{'con_lost'})) {
                   2741:            $returnhash{'home'}= $chome;
                   2742: 	   $returnhash{'domain'} = $cdomain;
                   2743: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  2744:            if (!defined($returnhash{'type'})) {
                   2745:                $returnhash{'type'} = 'Course';
                   2746:            }
1.130     albertel 2747:            while (my ($name,$value) = each %returnhash) {
1.53      www      2748:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 2749:            }
1.270     www      2750:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      2751:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 2752: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      2753:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   2754:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   2755:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      2756:        }
                   2757:     }
1.731     albertel 2758:     if (!$args->{'one_time'}) {
                   2759: 	&appenv(%envhash);
                   2760:     }
1.302     albertel 2761:     return %returnhash;
1.461     www      2762: }
                   2763: 
                   2764: # -------------------------------------------------See if a user is privileged
                   2765: 
                   2766: sub privileged {
                   2767:     my ($username,$domain)=@_;
                   2768:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   2769: 			&homeserver($username,$domain));
                   2770:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   2771:     my $now=time;
                   2772:     if ($rolesdump ne '') {
1.800     albertel 2773:         foreach my $entry (split(/&/,$rolesdump)) {
                   2774: 	    if ($entry!~/^rolesdef_/) {
                   2775: 		my ($area,$role)=split(/=/,$entry);
1.461     www      2776: 		$area=~s/\_\w\w$//;
                   2777: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   2778: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   2779: 		    my $active=1;
                   2780: 		    if ($tend) {
                   2781: 			if ($tend<$now) { $active=0; }
                   2782: 		    }
                   2783: 		    if ($tstart) {
                   2784: 			if ($tstart>$now) { $active=0; }
                   2785: 		    }
                   2786: 		    if ($active) { return 1; }
                   2787: 		}
                   2788: 	    }
                   2789: 	}
                   2790:     }
                   2791:     return 0;
1.9       www      2792: }
1.1       albertel 2793: 
1.103     harris41 2794: # -------------------------------------------------------- Get user privileges
1.11      www      2795: 
                   2796: sub rolesinit {
                   2797:     my ($domain,$username,$authhost)=@_;
                   2798:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12      www      2799:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11      www      2800:     my %allroles=();
1.678     raeburn  2801:     my %allgroups=();   
1.11      www      2802:     my $now=time;
1.743     albertel 2803:     my %userroles = ('user.login.time' => $now);
1.678     raeburn  2804:     my $group_privs;
1.11      www      2805: 
                   2806:     if ($rolesdump ne '') {
1.800     albertel 2807:         foreach my $entry (split(/&/,$rolesdump)) {
                   2808: 	  if ($entry!~/^rolesdef_/) {
                   2809:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 2810: 	    $area=~s/\_\w\w$//;
1.678     raeburn  2811:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 2812: 	    if ($role=~/^cr/) { 
1.655     albertel 2813: 		if ($role=~m|^(cr/\w+/\w+/[a-zA-Z0-9]+)_(.*)$|) {
                   2814: 		    ($trole,my $trest)=($role=~m|^(cr/\w+/\w+/[a-zA-Z0-9]+)_(.*)$|);
                   2815: 		    ($tend,$tstart)=split('_',$trest);
                   2816: 		} else {
                   2817: 		    $trole=$role;
                   2818: 		}
1.678     raeburn  2819:             } elsif ($role =~ m|^gr/|) {
                   2820:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   2821:                 ($trole,$group_privs) = split(/\//,$trole);
                   2822:                 $group_privs = &unescape($group_privs);
1.587     albertel 2823: 	    } else {
                   2824: 		($trole,$tend,$tstart)=split(/_/,$role);
                   2825: 	    }
1.743     albertel 2826: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   2827: 					 $username);
                   2828: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  2829:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   2830:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      2831:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 2832: 		my $spec=$trole.'.'.$area;
                   2833: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   2834: 		if ($trole =~ /^cr\//) {
1.567     raeburn  2835:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  2836:                 } elsif ($trole eq 'gr') {
                   2837:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 2838: 		} else {
1.567     raeburn  2839:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 2840: 		}
1.12      www      2841:             }
1.662     raeburn  2842:           }
1.191     harris41 2843:         }
1.743     albertel 2844:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   2845:         $userroles{'user.adv'}    = $adv;
                   2846: 	$userroles{'user.author'} = $author;
1.620     albertel 2847:         $env{'user.adv'}=$adv;
1.11      www      2848:     }
1.743     albertel 2849:     return \%userroles;  
1.11      www      2850: }
                   2851: 
1.567     raeburn  2852: sub set_arearole {
                   2853:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   2854: # log the associated role with the area
                   2855:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 2856:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  2857: }
                   2858: 
                   2859: sub custom_roleprivs {
                   2860:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   2861:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   2862:     my $homsvr=homeserver($rauthor,$rdomain);
                   2863:     if ($hostname{$homsvr} ne '') {
                   2864:         my ($rdummy,$roledef)=
                   2865:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   2866:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   2867:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   2868:             if (defined($syspriv)) {
                   2869:                 $$allroles{'cm./'}.=':'.$syspriv;
                   2870:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   2871:             }
                   2872:             if ($tdomain ne '') {
                   2873:                 if (defined($dompriv)) {
                   2874:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   2875:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   2876:                 }
                   2877:                 if (($trest ne '') && (defined($coursepriv))) {
                   2878:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   2879:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   2880:                 }
                   2881:             }
                   2882:         }
                   2883:     }
                   2884: }
                   2885: 
1.678     raeburn  2886: sub group_roleprivs {
                   2887:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   2888:     my $access = 1;
                   2889:     my $now = time;
                   2890:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   2891:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   2892:     if ($access) {
                   2893:         my ($course,$group) = ($area =~ m|(/\w+/\w+)/([^/]+)$|);
                   2894:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   2895:     }
                   2896: }
1.567     raeburn  2897: 
                   2898: sub standard_roleprivs {
                   2899:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   2900:     if (defined($pr{$trole.':s'})) {
                   2901:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   2902:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   2903:     }
                   2904:     if ($tdomain ne '') {
                   2905:         if (defined($pr{$trole.':d'})) {
                   2906:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   2907:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   2908:         }
                   2909:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   2910:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   2911:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   2912:         }
                   2913:     }
                   2914: }
                   2915: 
                   2916: sub set_userprivs {
1.678     raeburn  2917:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  2918:     my $author=0;
                   2919:     my $adv=0;
1.678     raeburn  2920:     my %grouproles = ();
                   2921:     if (keys(%{$allgroups}) > 0) {
                   2922:         foreach my $role (keys %{$allroles}) {
1.681     raeburn  2923:             my ($trole,$area,$sec,$extendedarea);
1.771     raeburn  2924:             if ($role =~ m-^(\w+|cr/\w+/\w+/\w+)\.(/\w+/\w+)(/?\w*)-) {
1.678     raeburn  2925:                 $trole = $1;
                   2926:                 $area = $2;
1.681     raeburn  2927:                 $sec = $3;
                   2928:                 $extendedarea = $area.$sec;
                   2929:                 if (exists($$allgroups{$area})) {
                   2930:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   2931:                         my $spec = $trole.'.'.$extendedarea;
                   2932:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   2933:                                                 $$allgroups{$area}{$group};
1.678     raeburn  2934:                     }
                   2935:                 }
                   2936:             }
                   2937:         }
                   2938:     }
1.800     albertel 2939:     foreach my $group (keys(%grouproles)) {
                   2940:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  2941:     }
1.800     albertel 2942:     foreach my $role (keys(%{$allroles})) {
                   2943:         my %thesepriv;
                   2944:         if (($role=~/^au/) || ($role=~/^ca/)) { $author=1; }
                   2945:         foreach my $item (split(/:/,$$allroles{$role})) {
                   2946:             if ($item ne '') {
                   2947:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  2948:                 if ($restrictions eq '') {
                   2949:                     $thesepriv{$privilege}='F';
                   2950:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   2951:                     $thesepriv{$privilege}.=$restrictions;
                   2952:                 }
                   2953:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   2954:             }
                   2955:         }
                   2956:         my $thesestr='';
1.800     albertel 2957:         foreach my $priv (keys(%thesepriv)) {
                   2958: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   2959: 	}
                   2960:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  2961:     }
                   2962:     return ($author,$adv);
                   2963: }
                   2964: 
1.12      www      2965: # --------------------------------------------------------------- get interface
                   2966: 
                   2967: sub get {
1.131     albertel 2968:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      2969:    my $items='';
1.800     albertel 2970:    foreach my $item (@$storearr) {
                   2971:        $items.=&escape($item).'&';
1.191     harris41 2972:    }
1.12      www      2973:    $items=~s/\&$//;
1.620     albertel 2974:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   2975:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 2976:    my $uhome=&homeserver($uname,$udomain);
                   2977: 
1.133     albertel 2978:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      2979:    my @pairs=split(/\&/,$rep);
1.273     albertel 2980:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   2981:      return @pairs;
                   2982:    }
1.15      www      2983:    my %returnhash=();
1.42      www      2984:    my $i=0;
1.800     albertel 2985:    foreach my $item (@$storearr) {
                   2986:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      2987:       $i++;
1.191     harris41 2988:    }
1.15      www      2989:    return %returnhash;
1.27      www      2990: }
                   2991: 
                   2992: # --------------------------------------------------------------- del interface
                   2993: 
                   2994: sub del {
1.133     albertel 2995:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      2996:    my $items='';
1.800     albertel 2997:    foreach my $item (@$storearr) {
                   2998:        $items.=&escape($item).'&';
1.191     harris41 2999:    }
1.27      www      3000:    $items=~s/\&$//;
1.620     albertel 3001:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3002:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3003:    my $uhome=&homeserver($uname,$udomain);
                   3004: 
                   3005:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3006: }
                   3007: 
                   3008: # -------------------------------------------------------------- dump interface
                   3009: 
                   3010: sub dump {
1.755     albertel 3011:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   3012:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3013:     if (!$uname) { $uname=$env{'user.name'}; }
                   3014:     my $uhome=&homeserver($uname,$udomain);
                   3015:     if ($regexp) {
                   3016: 	$regexp=&escape($regexp);
                   3017:     } else {
                   3018: 	$regexp='.';
                   3019:     }
                   3020:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3021:     my @pairs=split(/\&/,$rep);
                   3022:     my %returnhash=();
                   3023:     foreach my $item (@pairs) {
                   3024: 	my ($key,$value)=split(/=/,$item,2);
                   3025: 	$key = &unescape($key);
                   3026: 	next if ($key =~ /^error: 2 /);
                   3027: 	$returnhash{$key}=&thaw_unescape($value);
                   3028:     }
                   3029:     return %returnhash;
1.407     www      3030: }
                   3031: 
1.717     albertel 3032: # --------------------------------------------------------- dumpstore interface
                   3033: 
                   3034: sub dumpstore {
                   3035:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   3036:    return &dump($namespace,$udomain,$uname,$regexp,$range);
                   3037: }
                   3038: 
1.407     www      3039: # -------------------------------------------------------------- keys interface
                   3040: 
                   3041: sub getkeys {
                   3042:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 3043:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3044:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      3045:    my $uhome=&homeserver($uname,$udomain);
                   3046:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   3047:    my @keyarray=();
1.800     albertel 3048:    foreach my $key (split(/\&/,$rep)) {
                   3049:       push(@keyarray,&unescape($key));
1.407     www      3050:    }
                   3051:    return @keyarray;
1.318     matthew  3052: }
                   3053: 
1.319     matthew  3054: # --------------------------------------------------------------- currentdump
                   3055: sub currentdump {
1.328     matthew  3056:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 3057:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   3058:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   3059:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  3060:    my $uhome = &homeserver($sname,$sdom);
                   3061:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  3062:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  3063:    #
1.318     matthew  3064:    my %returnhash=();
1.319     matthew  3065:    #
                   3066:    if ($rep eq "unknown_cmd") { 
                   3067:        # an old lond will not know currentdump
                   3068:        # Do a dump and make it look like a currentdump
1.326     matthew  3069:        my @tmp = &dump($courseid,$sdom,$sname,'.');
1.319     matthew  3070:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   3071:        my %hash = @tmp;
                   3072:        @tmp=();
1.424     matthew  3073:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  3074:    } else {
                   3075:        my @pairs=split(/\&/,$rep);
1.800     albertel 3076:        foreach my $pair (@pairs) {
                   3077:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  3078:            my ($symb,$param) = split(/:/,$key);
                   3079:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 3080:                                                         &thaw_unescape($value);
1.319     matthew  3081:        }
1.191     harris41 3082:    }
1.12      www      3083:    return %returnhash;
1.424     matthew  3084: }
                   3085: 
                   3086: sub convert_dump_to_currentdump{
                   3087:     my %hash = %{shift()};
                   3088:     my %returnhash;
                   3089:     # Code ripped from lond, essentially.  The only difference
                   3090:     # here is the unescaping done by lonnet::dump().  Conceivably
                   3091:     # we might run in to problems with parameter names =~ /^v\./
                   3092:     while (my ($key,$value) = each(%hash)) {
                   3093:         my ($v,$symb,$param) = split(/:/,$key);
                   3094:         next if ($v eq 'version' || $symb eq 'keys');
                   3095:         next if (exists($returnhash{$symb}) &&
                   3096:                  exists($returnhash{$symb}->{$param}) &&
                   3097:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   3098:         $returnhash{$symb}->{$param}=$value;
                   3099:         $returnhash{$symb}->{'v.'.$param}=$v;
                   3100:     }
                   3101:     #
                   3102:     # Remove all of the keys in the hashes which keep track of
                   3103:     # the version of the parameter.
                   3104:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   3105:         # use a foreach because we are going to delete from the hash.
                   3106:         foreach my $key (keys(%$param_hash)) {
                   3107:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   3108:         }
                   3109:     }
                   3110:     return \%returnhash;
1.12      www      3111: }
                   3112: 
1.627     albertel 3113: # ------------------------------------------------------ critical inc interface
                   3114: 
                   3115: sub cinc {
                   3116:     return &inc(@_,'critical');
                   3117: }
                   3118: 
1.449     matthew  3119: # --------------------------------------------------------------- inc interface
                   3120: 
                   3121: sub inc {
1.627     albertel 3122:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 3123:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3124:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  3125:     my $uhome=&homeserver($uname,$udomain);
                   3126:     my $items='';
                   3127:     if (! ref($store)) {
                   3128:         # got a single value, so use that instead
                   3129:         $items = &escape($store).'=&';
                   3130:     } elsif (ref($store) eq 'SCALAR') {
                   3131:         $items = &escape($$store).'=&';        
                   3132:     } elsif (ref($store) eq 'ARRAY') {
                   3133:         $items = join('=&',map {&escape($_);} @{$store});
                   3134:     } elsif (ref($store) eq 'HASH') {
                   3135:         while (my($key,$value) = each(%{$store})) {
                   3136:             $items.= &escape($key).'='.&escape($value).'&';
                   3137:         }
                   3138:     }
                   3139:     $items=~s/\&$//;
1.627     albertel 3140:     if ($critical) {
                   3141: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3142:     } else {
                   3143: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3144:     }
1.449     matthew  3145: }
                   3146: 
1.12      www      3147: # --------------------------------------------------------------- put interface
                   3148: 
                   3149: sub put {
1.134     albertel 3150:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3151:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3152:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3153:    my $uhome=&homeserver($uname,$udomain);
1.12      www      3154:    my $items='';
1.800     albertel 3155:    foreach my $item (keys(%$storehash)) {
                   3156:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3157:    }
1.12      www      3158:    $items=~s/\&$//;
1.134     albertel 3159:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      3160: }
                   3161: 
1.631     albertel 3162: # ------------------------------------------------------------ newput interface
                   3163: 
                   3164: sub newput {
                   3165:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   3166:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3167:    if (!$uname) { $uname=$env{'user.name'}; }
                   3168:    my $uhome=&homeserver($uname,$udomain);
                   3169:    my $items='';
                   3170:    foreach my $key (keys(%$storehash)) {
                   3171:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   3172:    }
                   3173:    $items=~s/\&$//;
                   3174:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   3175: }
                   3176: 
                   3177: # ---------------------------------------------------------  putstore interface
                   3178: 
1.524     raeburn  3179: sub putstore {
1.715     albertel 3180:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 3181:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3182:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  3183:    my $uhome=&homeserver($uname,$udomain);
                   3184:    my $items='';
1.715     albertel 3185:    foreach my $key (keys(%$storehash)) {
                   3186:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  3187:    }
1.715     albertel 3188:    $items=~s/\&$//;
1.716     albertel 3189:    my $esc_symb=&escape($symb);
                   3190:    my $esc_v=&escape($version);
1.715     albertel 3191:    my $reply =
1.716     albertel 3192:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 3193: 	      $uhome);
                   3194:    if ($reply eq 'unknown_cmd') {
1.716     albertel 3195:        # gfall back to way things use to be done
1.715     albertel 3196:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   3197: 			    $uname);
1.524     raeburn  3198:    }
1.715     albertel 3199:    return $reply;
                   3200: }
                   3201: 
                   3202: sub old_putstore {
1.716     albertel 3203:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   3204:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3205:     if (!$uname) { $uname=$env{'user.name'}; }
                   3206:     my $uhome=&homeserver($uname,$udomain);
                   3207:     my %newstorehash;
1.800     albertel 3208:     foreach my $item (keys(%$storehash)) {
                   3209: 	my $key = $version.':'.&escape($symb).':'.$item;
                   3210: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 3211:     }
                   3212:     my $items='';
                   3213:     my %allitems = ();
1.800     albertel 3214:     foreach my $item (keys(%newstorehash)) {
                   3215: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 3216: 	    my $key = $1.':keys:'.$2;
                   3217: 	    $allitems{$key} .= $3.':';
                   3218: 	}
1.800     albertel 3219: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 3220:     }
1.800     albertel 3221:     foreach my $item (keys(%allitems)) {
                   3222: 	$allitems{$item} =~ s/\:$//;
                   3223: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 3224:     }
                   3225:     $items=~s/\&$//;
                   3226:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  3227: }
                   3228: 
1.47      www      3229: # ------------------------------------------------------ critical put interface
                   3230: 
                   3231: sub cput {
1.134     albertel 3232:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3233:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3234:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3235:    my $uhome=&homeserver($uname,$udomain);
1.47      www      3236:    my $items='';
1.800     albertel 3237:    foreach my $item (keys(%$storehash)) {
                   3238:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3239:    }
1.47      www      3240:    $items=~s/\&$//;
1.134     albertel 3241:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3242: }
                   3243: 
                   3244: # -------------------------------------------------------------- eget interface
                   3245: 
                   3246: sub eget {
1.133     albertel 3247:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3248:    my $items='';
1.800     albertel 3249:    foreach my $item (@$storearr) {
                   3250:        $items.=&escape($item).'&';
1.191     harris41 3251:    }
1.12      www      3252:    $items=~s/\&$//;
1.620     albertel 3253:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3254:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3255:    my $uhome=&homeserver($uname,$udomain);
                   3256:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3257:    my @pairs=split(/\&/,$rep);
                   3258:    my %returnhash=();
1.42      www      3259:    my $i=0;
1.800     albertel 3260:    foreach my $item (@$storearr) {
                   3261:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3262:       $i++;
1.191     harris41 3263:    }
1.12      www      3264:    return %returnhash;
                   3265: }
                   3266: 
1.667     albertel 3267: # ------------------------------------------------------------ tmpput interface
                   3268: sub tmpput {
1.802     raeburn  3269:     my ($storehash,$server,$context)=@_;
1.667     albertel 3270:     my $items='';
1.800     albertel 3271:     foreach my $item (keys(%$storehash)) {
                   3272: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 3273:     }
                   3274:     $items=~s/\&$//;
1.802     raeburn  3275:     if (defined($context)) {
                   3276:         $items .= ':'.&escape($context);
                   3277:     }
1.667     albertel 3278:     return &reply("tmpput:$items",$server);
                   3279: }
                   3280: 
                   3281: # ------------------------------------------------------------ tmpget interface
                   3282: sub tmpget {
1.688     albertel 3283:     my ($token,$server)=@_;
                   3284:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3285:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 3286:     my %returnhash;
                   3287:     foreach my $item (split(/\&/,$rep)) {
                   3288: 	my ($key,$value)=split(/=/,$item);
                   3289: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   3290:     }
                   3291:     return %returnhash;
                   3292: }
                   3293: 
1.688     albertel 3294: # ------------------------------------------------------------ tmpget interface
                   3295: sub tmpdel {
                   3296:     my ($token,$server)=@_;
                   3297:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3298:     return &reply("tmpdel:$token",$server);
                   3299: }
                   3300: 
1.765     albertel 3301: # -------------------------------------------------- portfolio access checking
                   3302: 
                   3303: sub portfolio_access {
1.766     albertel 3304:     my ($requrl) = @_;
1.765     albertel 3305:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   3306:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
                   3307:     if ($result eq 'ok') {
1.766     albertel 3308:        return 'F';
1.765     albertel 3309:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 3310:        return 'A';
1.765     albertel 3311:     }
1.766     albertel 3312:     return '';
1.765     albertel 3313: }
                   3314: 
                   3315: sub get_portfolio_access {
1.767     albertel 3316:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   3317: 
                   3318:     if (!ref($access_hash)) {
                   3319: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   3320: 	my %access_controls = &get_access_controls($current_perms,$group,
                   3321: 						   $file_name);
                   3322: 	$access_hash = $access_controls{$file_name};
                   3323:     }
                   3324: 
1.765     albertel 3325:     my ($public,$guest,@domains,@users,@courses,@groups);
                   3326:     my $now = time;
                   3327:     if (ref($access_hash) eq 'HASH') {
                   3328:         foreach my $key (keys(%{$access_hash})) {
                   3329:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   3330:             if ($start > $now) {
                   3331:                 next;
                   3332:             }
                   3333:             if ($end && $end<$now) {
                   3334:                 next;
                   3335:             }
                   3336:             if ($scope eq 'public') {
                   3337:                 $public = $key;
                   3338:                 last;
                   3339:             } elsif ($scope eq 'guest') {
                   3340:                 $guest = $key;
                   3341:             } elsif ($scope eq 'domains') {
                   3342:                 push(@domains,$key);
                   3343:             } elsif ($scope eq 'users') {
                   3344:                 push(@users,$key);
                   3345:             } elsif ($scope eq 'course') {
                   3346:                 push(@courses,$key);
                   3347:             } elsif ($scope eq 'group') {
                   3348:                 push(@groups,$key);
                   3349:             }
                   3350:         }
                   3351:         if ($public) {
                   3352:             return 'ok';
                   3353:         }
                   3354:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3355:             if ($guest) {
                   3356:                 return $guest;
                   3357:             }
                   3358:         } else {
                   3359:             if (@domains > 0) {
                   3360:                 foreach my $domkey (@domains) {
                   3361:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   3362:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   3363:                             return 'ok';
                   3364:                         }
                   3365:                     }
                   3366:                 }
                   3367:             }
                   3368:             if (@users > 0) {
                   3369:                 foreach my $userkey (@users) {
                   3370:                     if (exists($access_hash->{$userkey}{'users'}{$env{'user.name'}.':'.$env{'user.domain'}})) {
                   3371:                         return 'ok';
                   3372:                     }
                   3373:                 }
                   3374:             }
                   3375:             my %roleshash;
                   3376:             my @courses_and_groups = @courses;
                   3377:             push(@courses_and_groups,@groups); 
                   3378:             if (@courses_and_groups > 0) {
                   3379:                 my (%allgroups,%allroles); 
                   3380:                 my ($start,$end,$role,$sec,$group);
                   3381:                 foreach my $envkey (%env) {
                   3382:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./([^/]+)/([^/]+)/?([^/]*)$-) {
                   3383:                         my $cid = $2.'_'.$3; 
                   3384:                         if ($1 eq 'gr') {
                   3385:                             $group = $4;
                   3386:                             $allgroups{$cid}{$group} = $env{$envkey};
                   3387:                         } else {
                   3388:                             if ($4 eq '') {
                   3389:                                 $sec = 'none';
                   3390:                             } else {
                   3391:                                 $sec = $4;
                   3392:                             }
                   3393:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3394:                         }
                   3395:                     } elsif ($envkey =~ m-^user\.role\./cr/(\w+/\w+/\w*)./([^/]+)/([^/]+)/?([^/]*)$-) {
                   3396:                         my $cid = $2.'_'.$3;
                   3397:                         if ($4 eq '') {
                   3398:                             $sec = 'none';
                   3399:                         } else {
                   3400:                             $sec = $4;
                   3401:                         }
                   3402:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3403:                     }
                   3404:                 }
                   3405:                 if (keys(%allroles) == 0) {
                   3406:                     return;
                   3407:                 }
                   3408:                 foreach my $key (@courses_and_groups) {
                   3409:                     my %content = %{$$access_hash{$key}};
                   3410:                     my $cnum = $content{'number'};
                   3411:                     my $cdom = $content{'domain'};
                   3412:                     my $cid = $cdom.'_'.$cnum;
                   3413:                     if (!exists($allroles{$cid})) {
                   3414:                         next;
                   3415:                     }    
                   3416:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   3417:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   3418:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   3419:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   3420:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   3421:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   3422:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   3423:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   3424:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   3425:                                         if (grep/^all$/,@sections) {
                   3426:                                             return 'ok';
                   3427:                                         } else {
                   3428:                                             if (grep/^$sec$/,@sections) {
                   3429:                                                 return 'ok';
                   3430:                                             }
                   3431:                                         }
                   3432:                                     }
                   3433:                                 }
                   3434:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   3435:                                     if (grep/^none$/,@groups) {
                   3436:                                         return 'ok';
                   3437:                                     }
                   3438:                                 } else {
                   3439:                                     if (grep/^all$/,@groups) {
                   3440:                                         return 'ok';
                   3441:                                     } 
                   3442:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   3443:                                         if (grep/^$group$/,@groups) {
                   3444:                                             return 'ok';
                   3445:                                         }
                   3446:                                     }
                   3447:                                 } 
                   3448:                             }
                   3449:                         }
                   3450:                     }
                   3451:                 }
                   3452:             }
                   3453:             if ($guest) {
                   3454:                 return $guest;
                   3455:             }
                   3456:         }
                   3457:     }
                   3458:     return;
                   3459: }
                   3460: 
                   3461: sub course_group_datechecker {
                   3462:     my ($dates,$now,$status) = @_;
                   3463:     my ($start,$end) = split(/\./,$dates);
                   3464:     if (!$start && !$end) {
                   3465:         return 'ok';
                   3466:     }
                   3467:     if (grep/^active$/,@{$status}) {
                   3468:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   3469:             return 'ok';
                   3470:         }
                   3471:     }
                   3472:     if (grep/^previous$/,@{$status}) {
                   3473:         if ($end > $now ) {
                   3474:             return 'ok';
                   3475:         }
                   3476:     }
                   3477:     if (grep/^future$/,@{$status}) {
                   3478:         if ($start > $now) {
                   3479:             return 'ok';
                   3480:         }
                   3481:     }
                   3482:     return; 
                   3483: }
                   3484: 
                   3485: sub parse_portfolio_url {
                   3486:     my ($url) = @_;
                   3487: 
                   3488:     my ($type,$udom,$unum,$group,$file_name);
                   3489:     
                   3490:     if ($url =~  m-^/*uploaded/([^/]+)/([^/]+)/portfolio(/.+)$-) {
                   3491: 	$type = 1;
                   3492:         $udom = $1;
                   3493:         $unum = $2;
                   3494:         $file_name = $3;
                   3495:     } elsif ($url =~ m-^/*uploaded/([^/]+)/([^/]+)/groups/([^/]+)/portfolio/(.+)$-) {
                   3496: 	$type = 2;
                   3497:         $udom = $1;
                   3498:         $unum = $2;
                   3499:         $group = $3;
                   3500:         $file_name = $3.'/'.$4;
                   3501:     }
                   3502:     if (wantarray) {
                   3503: 	return ($type,$udom,$unum,$file_name,$group);
                   3504:     }
                   3505:     return $type;
                   3506: }
                   3507: 
                   3508: sub is_portfolio_url {
                   3509:     my ($url) = @_;
                   3510:     return scalar(&parse_portfolio_url($url));
                   3511: }
                   3512: 
1.798     raeburn  3513: sub is_portfolio_file {
                   3514:     my ($file) = @_;
                   3515:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
                   3516:         return 1;
                   3517:     }
                   3518:     return;
                   3519: }
                   3520: 
                   3521: 
1.341     www      3522: # ---------------------------------------------- Custom access rule evaluation
                   3523: 
                   3524: sub customaccess {
                   3525:     my ($priv,$uri)=@_;
1.620     albertel 3526:     my ($urole,$urealm)=split(/\./,$env{'request.role'});
1.343     www      3527:     $urealm=~s/^\W//;
                   3528:     my ($udom,$ucrs,$usec)=split(/\//,$urealm);
1.341     www      3529:     my $access=0;
1.800     albertel 3530:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
                   3531: 	my ($effect,$realm,$role)=split(/\:/,$right);
1.343     www      3532:         if ($role) {
                   3533: 	   if ($role ne $urole) { next; }
                   3534:         }
1.800     albertel 3535:         foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   3536:             my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
1.343     www      3537:             if ($tdom) {
                   3538: 		if ($tdom ne $udom) { next; }
                   3539:             }
                   3540:             if ($tcrs) {
                   3541: 		if ($tcrs ne $ucrs) { next; }
                   3542:             }
                   3543:             if ($tsec) {
                   3544: 		if ($tsec ne $usec) { next; }
                   3545:             }
                   3546:             $access=($effect eq 'allow');
                   3547:             last;
1.342     www      3548:         }
1.402     bowersj2 3549: 	if ($realm eq '' && $role eq '') {
                   3550:             $access=($effect eq 'allow');
                   3551: 	}
1.341     www      3552:     }
                   3553:     return $access;
                   3554: }
                   3555: 
1.103     harris41 3556: # ------------------------------------------------- Check for a user privilege
1.12      www      3557: 
                   3558: sub allowed {
1.579     albertel 3559:     my ($priv,$uri,$symb)=@_;
1.705     albertel 3560:     my $ver_orguri=$uri;
1.439     www      3561:     $uri=&deversion($uri);
1.152     www      3562:     my $orguri=$uri;
1.52      www      3563:     $uri=&declutter($uri);
1.545     banghart 3564:     
1.620     albertel 3565:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      3566: # Free bre access to adm and meta resources
1.775     albertel 3567:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 3568: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   3569: 	&& ($priv eq 'bre')) {
1.14      www      3570: 	return 'F';
1.159     www      3571:     }
                   3572: 
1.545     banghart 3573: # Free bre access to user's own portfolio contents
1.714     raeburn  3574:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  3575:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  3576: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.545     banghart 3577:         return 'F';
                   3578:     }
                   3579: 
1.762     raeburn  3580: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  3581:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   3582:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   3583:         if (exists($env{'request.course.id'})) {
                   3584:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3585:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3586:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   3587:                 my $courseprivid=$env{'request.course.id'};
                   3588:                 $courseprivid=~s/\_/\//;
                   3589:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   3590:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   3591:                     return $1; 
1.762     raeburn  3592:                 } else {
                   3593:                     if ($env{'request.course.sec'}) {
                   3594:                         $courseprivid.='/'.$env{'request.course.sec'};
                   3595:                     }
                   3596:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   3597:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   3598:                         return $2;
                   3599:                     }
1.714     raeburn  3600:                 }
                   3601:             }
                   3602:         }
                   3603:     }
                   3604: 
1.159     www      3605: # Free bre to public access
                   3606: 
                   3607:     if ($priv eq 'bre') {
1.238     www      3608:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 3609: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      3610:            return 'F'; 
                   3611:         }
1.238     www      3612:         if ($copyright eq 'priv') {
                   3613:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3614: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      3615: 		return '';
                   3616:             }
                   3617:         }
                   3618:         if ($copyright eq 'domain') {
                   3619:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3620: 	    unless (($env{'user.domain'} eq $1) ||
                   3621:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      3622: 		return '';
                   3623:             }
1.262     matthew  3624:         }
1.620     albertel 3625:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  3626:             # Library role, so allow browsing of resources in this domain.
                   3627:             return 'F';
1.238     www      3628:         }
1.341     www      3629:         if ($copyright eq 'custom') {
                   3630: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   3631:         }
1.14      www      3632:     }
1.264     matthew  3633:     # Domain coordinator is trying to create a course
1.620     albertel 3634:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  3635:         # uri is the requested domain in this case.
                   3636:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  3637:         # a role of dc for the domain in question.
1.620     albertel 3638:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  3639:     }
1.29      www      3640: 
1.52      www      3641:     my $thisallowed='';
                   3642:     my $statecond=0;
                   3643:     my $courseprivid='';
                   3644: 
                   3645: # Course
                   3646: 
1.620     albertel 3647:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3648:        $thisallowed.=$1;
                   3649:     }
1.29      www      3650: 
1.52      www      3651: # Domain
                   3652: 
1.620     albertel 3653:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 3654:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3655:        $thisallowed.=$1;
                   3656:     }
1.52      www      3657: 
                   3658: # Course: uri itself is a course
1.66      www      3659:     my $courseuri=$uri;
                   3660:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      3661:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      3662: 
1.620     albertel 3663:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 3664:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3665:        $thisallowed.=$1;
                   3666:     }
1.29      www      3667: 
1.665     albertel 3668: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 3669: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 3670:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 3671: 	$thisallowed='';
1.671     raeburn  3672:         my ($match)=&is_on_map($uri);
                   3673:         if ($match) {
                   3674:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   3675:                   =~/\Q$priv\E\&([^\:]*)/) {
                   3676:                 $thisallowed.=$1;
                   3677:             }
                   3678:         } else {
1.705     albertel 3679:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  3680:             if ($refuri) {
                   3681:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  3682:                     $thisallowed='F';
1.671     raeburn  3683:                 } else {
                   3684:                     $refuri=&declutter($refuri);
                   3685:                     my ($match) = &is_on_map($refuri);
                   3686:                     if ($match) {
                   3687:                         $thisallowed='F';
                   3688:                     }
1.669     raeburn  3689:                 }
1.671     raeburn  3690:             }
                   3691:         }
1.314     www      3692:     }
1.492     albertel 3693: 
1.766     albertel 3694:     if ($priv eq 'bre'
                   3695: 	&& $thisallowed ne 'F' 
                   3696: 	&& $thisallowed ne '2'
                   3697: 	&& &is_portfolio_url($uri)) {
                   3698: 	$thisallowed = &portfolio_access($uri);
                   3699:     }
                   3700:     
1.52      www      3701: # Full access at system, domain or course-wide level? Exit.
1.29      www      3702: 
                   3703:     if ($thisallowed=~/F/) {
                   3704: 	return 'F';
                   3705:     }
                   3706: 
1.52      www      3707: # If this is generating or modifying users, exit with special codes
1.29      www      3708: 
1.643     www      3709:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   3710: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 3711: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      3712: # no author name given, so this just checks on the general right to make a co-author in this domain
                   3713: 	    unless ($auname) { return $thisallowed; }
                   3714: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 3715: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   3716: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   3717: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   3718: 	}
1.52      www      3719: 	return $thisallowed;
                   3720:     }
                   3721: #
1.103     harris41 3722: # Gathered so far: system, domain and course wide privileges
1.52      www      3723: #
                   3724: # Course: See if uri or referer is an individual resource that is part of 
                   3725: # the course
                   3726: 
1.620     albertel 3727:     if ($env{'request.course.id'}) {
1.232     www      3728: 
1.620     albertel 3729:        $courseprivid=$env{'request.course.id'};
                   3730:        if ($env{'request.course.sec'}) {
                   3731:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      3732:        }
                   3733:        $courseprivid=~s/\_/\//;
                   3734:        my $checkreferer=1;
1.232     www      3735:        my ($match,$cond)=&is_on_map($uri);
                   3736:        if ($match) {
                   3737:            $statecond=$cond;
1.620     albertel 3738:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 3739:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3740:                $thisallowed.=$1;
                   3741:                $checkreferer=0;
                   3742:            }
1.29      www      3743:        }
1.83      www      3744:        
1.148     www      3745:        if ($checkreferer) {
1.620     albertel 3746: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      3747:             unless ($refuri) {
1.800     albertel 3748:                 foreach my $key (keys(%env)) {
                   3749: 		    if ($key=~/^httpref\..*\*/) {
                   3750: 			my $pattern=$key;
1.156     www      3751:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      3752:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   3753:                         $pattern=~s/\//\\\//g;
1.152     www      3754:                         if ($orguri=~/$pattern/) {
1.800     albertel 3755: 			    $refuri=$env{$key};
1.148     www      3756:                         }
                   3757:                     }
1.191     harris41 3758:                 }
1.148     www      3759:             }
1.232     www      3760: 
1.148     www      3761:          if ($refuri) { 
1.152     www      3762: 	  $refuri=&declutter($refuri);
1.232     www      3763:           my ($match,$cond)=&is_on_map($refuri);
                   3764:             if ($match) {
                   3765:               my $refstatecond=$cond;
1.620     albertel 3766:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 3767:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3768:                   $thisallowed.=$1;
1.53      www      3769:                   $uri=$refuri;
                   3770:                   $statecond=$refstatecond;
1.52      www      3771:               }
                   3772:           }
1.148     www      3773:         }
1.29      www      3774:        }
1.52      www      3775:    }
1.29      www      3776: 
1.52      www      3777: #
1.103     harris41 3778: # Gathered now: all privileges that could apply, and condition number
1.52      www      3779: # 
                   3780: #
                   3781: # Full or no access?
                   3782: #
1.29      www      3783: 
1.52      www      3784:     if ($thisallowed=~/F/) {
                   3785: 	return 'F';
                   3786:     }
1.29      www      3787: 
1.52      www      3788:     unless ($thisallowed) {
                   3789:         return '';
                   3790:     }
1.29      www      3791: 
1.52      www      3792: # Restrictions exist, deal with them
                   3793: #
                   3794: #   C:according to course preferences
                   3795: #   R:according to resource settings
                   3796: #   L:unless locked
                   3797: #   X:according to user session state
                   3798: #
                   3799: 
                   3800: # Possibly locked functionality, check all courses
1.54      www      3801: # Locks might take effect only after 10 minutes cache expiration for other
                   3802: # courses, and 2 minutes for current course
1.52      www      3803: 
                   3804:     my $envkey;
                   3805:     if ($thisallowed=~/L/) {
1.620     albertel 3806:         foreach $envkey (keys %env) {
1.54      www      3807:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   3808:                my $courseid=$2;
                   3809:                my $roleid=$1.'.'.$2;
1.92      www      3810:                $courseid=~s/^\///;
1.54      www      3811:                my $expiretime=600;
1.620     albertel 3812:                if ($env{'request.role'} eq $roleid) {
1.54      www      3813: 		  $expiretime=120;
                   3814:                }
                   3815: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   3816:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 3817:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 3818: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      3819:                }
1.620     albertel 3820:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   3821:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   3822: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   3823:                        &log($env{'user.domain'},$env{'user.name'},
                   3824:                             $env{'user.home'},
1.57      www      3825:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      3826:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 3827:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      3828: 		       return '';
                   3829:                    }
                   3830:                }
1.620     albertel 3831:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   3832:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   3833: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   3834:                        &log($env{'user.domain'},$env{'user.name'},
                   3835:                             $env{'user.home'},
1.57      www      3836:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      3837:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 3838:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      3839: 		       return '';
                   3840:                    }
                   3841:                }
                   3842: 	   }
1.29      www      3843:        }
1.52      www      3844:     }
                   3845:    
                   3846: #
                   3847: # Rest of the restrictions depend on selected course
                   3848: #
                   3849: 
1.620     albertel 3850:     unless ($env{'request.course.id'}) {
1.766     albertel 3851: 	if ($thisallowed eq 'A') {
                   3852: 	    return 'A';
                   3853: 	} else {
                   3854: 	    return '1';
                   3855: 	}
1.52      www      3856:     }
1.29      www      3857: 
1.52      www      3858: #
                   3859: # Now user is definitely in a course
                   3860: #
1.53      www      3861: 
                   3862: 
                   3863: # Course preferences
                   3864: 
                   3865:    if ($thisallowed=~/C/) {
1.620     albertel 3866:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   3867:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   3868:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 3869: 	   =~/\Q$rolecode\E/) {
1.689     albertel 3870: 	   if ($priv ne 'pch') { 
                   3871: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   3872: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   3873: 			$env{'request.course.id'});
                   3874: 	   }
1.237     www      3875:            return '';
                   3876:        }
                   3877: 
1.620     albertel 3878:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 3879: 	   =~/\Q$unamedom\E/) {
1.689     albertel 3880: 	   if ($priv ne 'pch') { 
                   3881: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   3882: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   3883: 			$env{'request.course.id'});
                   3884: 	   }
1.54      www      3885:            return '';
                   3886:        }
1.53      www      3887:    }
                   3888: 
                   3889: # Resource preferences
                   3890: 
                   3891:    if ($thisallowed=~/R/) {
1.620     albertel 3892:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 3893:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 3894: 	   if ($priv ne 'pch') { 
                   3895: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   3896: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   3897: 	   }
                   3898: 	   return '';
1.54      www      3899:        }
1.53      www      3900:    }
1.30      www      3901: 
1.246     www      3902: # Restricted by state or randomout?
1.30      www      3903: 
1.52      www      3904:    if ($thisallowed=~/X/) {
1.620     albertel 3905:       if ($env{'acc.randomout'}) {
1.579     albertel 3906: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 3907:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      3908:             return ''; 
                   3909:          }
1.247     www      3910:       }
                   3911:       if (&condval($statecond)) {
1.52      www      3912: 	 return '2';
                   3913:       } else {
                   3914:          return '';
                   3915:       }
                   3916:    }
1.30      www      3917: 
1.766     albertel 3918:     if ($thisallowed eq 'A') {
                   3919: 	return 'A';
                   3920:     }
1.52      www      3921:    return 'F';
1.232     www      3922: }
                   3923: 
1.710     albertel 3924: sub split_uri_for_cond {
                   3925:     my $uri=&deversion(&declutter(shift));
                   3926:     my @uriparts=split(/\//,$uri);
                   3927:     my $filename=pop(@uriparts);
                   3928:     my $pathname=join('/',@uriparts);
                   3929:     return ($pathname,$filename);
                   3930: }
1.232     www      3931: # --------------------------------------------------- Is a resource on the map?
                   3932: 
                   3933: sub is_on_map {
1.710     albertel 3934:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 3935:     #Trying to find the conditional for the file
1.620     albertel 3936:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 3937: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      3938:     if ($match) {
1.289     bowersj2 3939: 	return (1,$1);
                   3940:     } else {
1.434     www      3941: 	return (0,0);
1.289     bowersj2 3942:     }
1.12      www      3943: }
                   3944: 
1.427     www      3945: # --------------------------------------------------------- Get symb from alias
                   3946: 
                   3947: sub get_symb_from_alias {
                   3948:     my $symb=shift;
                   3949:     my ($map,$resid,$url)=&decode_symb($symb);
                   3950: # Already is a symb
                   3951:     if ($url) { return $symb; }
                   3952: # Must be an alias
                   3953:     my $aliassymb='';
                   3954:     my %bighash;
1.620     albertel 3955:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      3956:                             &GDBM_READER(),0640)) {
                   3957:         my $rid=$bighash{'mapalias_'.$symb};
                   3958: 	if ($rid) {
                   3959: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 3960: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   3961: 				    $resid,$bighash{'src_'.$rid});
1.427     www      3962: 	}
                   3963:         untie %bighash;
                   3964:     }
                   3965:     return $aliassymb;
                   3966: }
                   3967: 
1.12      www      3968: # ----------------------------------------------------------------- Define Role
                   3969: 
                   3970: sub definerole {
                   3971:   if (allowed('mcr','/')) {
                   3972:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 3973:     foreach my $role (split(':',$sysrole)) {
                   3974: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 3975:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   3976:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   3977: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      3978:                return "refused:s:$crole&$cqual"; 
                   3979:             }
                   3980:         }
1.191     harris41 3981:     }
1.800     albertel 3982:     foreach my $role (split(':',$domrole)) {
                   3983: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 3984:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   3985:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   3986: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      3987:                return "refused:d:$crole&$cqual"; 
                   3988:             }
                   3989:         }
1.191     harris41 3990:     }
1.800     albertel 3991:     foreach my $role (split(':',$courole)) {
                   3992: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 3993:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   3994:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   3995: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      3996:                return "refused:c:$crole&$cqual"; 
                   3997:             }
                   3998:         }
1.191     harris41 3999:     }
1.620     albertel 4000:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   4001:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4002: 	        "rolesdef_$rolename=".
                   4003:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 4004:     return reply($command,$env{'user.home'});
1.12      www      4005:   } else {
                   4006:     return 'refused';
                   4007:   }
1.105     harris41 4008: }
                   4009: 
                   4010: # ---------------- Make a metadata query against the network of library servers
                   4011: 
                   4012: sub metadata_query {
1.244     matthew  4013:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 4014:     my %rhash;
1.244     matthew  4015:     my @server_list = (defined($server_array) ? @$server_array
                   4016:                                               : keys(%libserv) );
                   4017:     for my $server (@server_list) {
1.118     harris41 4018: 	unless ($custom or $customshow) {
                   4019: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   4020: 	    $rhash{$server}=$reply;
                   4021: 	}
                   4022: 	else {
                   4023: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   4024: 			     &escape($custom).':'.&escape($customshow),
                   4025: 			     $server);
                   4026: 	    $rhash{$server}=$reply;
                   4027: 	}
1.112     harris41 4028:     }
1.118     harris41 4029:     return \%rhash;
1.240     www      4030: }
                   4031: 
                   4032: # ----------------------------------------- Send log queries and wait for reply
                   4033: 
                   4034: sub log_query {
                   4035:     my ($uname,$udom,$query,%filters)=@_;
                   4036:     my $uhome=&homeserver($uname,$udom);
                   4037:     if ($uhome eq 'no_host') { return 'error: no_host'; }
                   4038:     my $uhost=$hostname{$uhome};
1.800     albertel 4039:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      4040:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   4041:                        $uhome);
1.479     albertel 4042:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      4043:     return get_query_reply($queryid);
                   4044: }
                   4045: 
1.508     raeburn  4046: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  4047: 
                   4048: sub fetch_enrollment_query {
1.511     raeburn  4049:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  4050:     my $homeserver;
1.547     raeburn  4051:     my $maxtries = 1;
1.508     raeburn  4052:     if ($context eq 'automated') {
                   4053:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  4054:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  4055:     } else {
                   4056:         $homeserver = &homeserver($cnum,$dom);
                   4057:     }
1.506     raeburn  4058:     my $host=$hostname{$homeserver};
                   4059:     my $cmd = '';
1.800     albertel 4060:     foreach my $affiliate (keys %{$affiliatesref}) {
                   4061:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  4062:     }
                   4063:     $cmd =~ s/%%$//;
                   4064:     $cmd = &escape($cmd);
                   4065:     my $query = 'fetchenrollment';
1.620     albertel 4066:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  4067:     unless ($queryid=~/^\Q$host\E\_/) { 
                   4068:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   4069:         return 'error: '.$queryid;
                   4070:     }
1.506     raeburn  4071:     my $reply = &get_query_reply($queryid);
1.547     raeburn  4072:     my $tries = 1;
                   4073:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4074:         $reply = &get_query_reply($queryid);
                   4075:         $tries ++;
                   4076:     }
1.526     raeburn  4077:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 4078:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  4079:     } else {
1.515     raeburn  4080:         my @responses = split/:/,$reply;
                   4081:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 4082:             foreach my $line (@responses) {
                   4083:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  4084:                 $$replyref{$key} = $value;
                   4085:             }
                   4086:         } else {
1.506     raeburn  4087:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 4088:             foreach my $line (@responses) {
                   4089:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  4090:                 $$replyref{$key} = $value;
                   4091:                 if ($value > 0) {
1.800     albertel 4092:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   4093:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  4094:                         my $destname = $pathname.'/'.$filename;
                   4095:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  4096:                         if ($xml_classlist =~ /^error/) {
                   4097:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   4098:                         } else {
1.506     raeburn  4099:                             if ( open(FILE,">$destname") ) {
                   4100:                                 print FILE &unescape($xml_classlist);
                   4101:                                 close(FILE);
1.526     raeburn  4102:                             } else {
                   4103:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  4104:                             }
                   4105:                         }
                   4106:                     }
                   4107:                 }
                   4108:             }
                   4109:         }
                   4110:         return 'ok';
                   4111:     }
                   4112:     return 'error';
                   4113: }
                   4114: 
1.242     www      4115: sub get_query_reply {
                   4116:     my $queryid=shift;
1.240     www      4117:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   4118:     my $reply='';
                   4119:     for (1..100) {
                   4120: 	sleep 2;
                   4121:         if (-e $replyfile.'.end') {
1.448     albertel 4122: 	    if (open(my $fh,$replyfile)) {
1.240     www      4123:                $reply.=<$fh>;
1.448     albertel 4124:                close($fh);
1.240     www      4125: 	   } else { return 'error: reply_file_error'; }
1.242     www      4126:            return &unescape($reply);
                   4127: 	}
1.240     www      4128:     }
1.242     www      4129:     return 'timeout:'.$queryid;
1.240     www      4130: }
                   4131: 
                   4132: sub courselog_query {
1.241     www      4133: #
                   4134: # possible filters:
                   4135: # url: url or symb
                   4136: # username
                   4137: # domain
                   4138: # action: view, submit, grade
                   4139: # start: timestamp
                   4140: # end: timestamp
                   4141: #
1.240     www      4142:     my (%filters)=@_;
1.620     albertel 4143:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      4144:     if ($filters{'url'}) {
                   4145: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   4146:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   4147:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   4148:     }
1.620     albertel 4149:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4150:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      4151:     return &log_query($cname,$cdom,'courselog',%filters);
                   4152: }
                   4153: 
                   4154: sub userlog_query {
                   4155:     my ($uname,$udom,%filters)=@_;
                   4156:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      4157: }
                   4158: 
1.506     raeburn  4159: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   4160: 
                   4161: sub auto_run {
1.508     raeburn  4162:     my ($cnum,$cdom) = @_;
                   4163:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4164:     my $response = &reply('autorun:'.$cdom,$homeserver);
1.506     raeburn  4165:     return $response;
                   4166: }
1.776     albertel 4167: 
1.506     raeburn  4168: sub auto_get_sections {
1.508     raeburn  4169:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   4170:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  4171:     my @secs = ();
1.511     raeburn  4172:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  4173:     unless ($response eq 'refused') {
                   4174:         @secs = split/:/,$response;
                   4175:     }
                   4176:     return @secs;
                   4177: }
1.776     albertel 4178: 
1.506     raeburn  4179: sub auto_new_course {
1.508     raeburn  4180:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   4181:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  4182:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  4183:     return $response;
                   4184: }
1.776     albertel 4185: 
1.506     raeburn  4186: sub auto_validate_courseID {
1.508     raeburn  4187:     my ($cnum,$cdom,$inst_course_id) = @_;
                   4188:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4189:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  4190:     return $response;
                   4191: }
1.776     albertel 4192: 
1.506     raeburn  4193: sub auto_create_password {
1.508     raeburn  4194:     my ($cnum,$cdom,$authparam) = @_;
                   4195:     my $homeserver = &homeserver($cnum,$cdom); 
1.506     raeburn  4196:     my $create_passwd = 0;
                   4197:     my $authchk = '';
1.511     raeburn  4198:     my $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
1.506     raeburn  4199:     if ($response eq 'refused') {
                   4200:         $authchk = 'refused';
                   4201:     } else {
                   4202:         ($authparam,$create_passwd,$authchk) = split/:/,$response;
                   4203:     }
                   4204:     return ($authparam,$create_passwd,$authchk);
                   4205: }
                   4206: 
1.706     raeburn  4207: sub auto_photo_permission {
                   4208:     my ($cnum,$cdom,$students) = @_;
                   4209:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 4210:     my ($outcome,$perm_reqd,$conditions) = 
                   4211: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 4212:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4213: 	return (undef,undef);
                   4214:     }
1.706     raeburn  4215:     return ($outcome,$perm_reqd,$conditions);
                   4216: }
                   4217: 
                   4218: sub auto_checkphotos {
                   4219:     my ($uname,$udom,$pid) = @_;
                   4220:     my $homeserver = &homeserver($uname,$udom);
                   4221:     my ($result,$resulttype);
                   4222:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 4223: 				   &escape($uname).':'.&escape($pid),
                   4224: 				   $homeserver));
1.709     albertel 4225:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4226: 	return (undef,undef);
                   4227:     }
1.706     raeburn  4228:     if ($outcome) {
                   4229:         ($result,$resulttype) = split(/:/,$outcome);
                   4230:     } 
                   4231:     return ($result,$resulttype);
                   4232: }
                   4233: 
                   4234: sub auto_photochoice {
                   4235:     my ($cnum,$cdom) = @_;
                   4236:     my $homeserver = &homeserver($cnum,$cdom);
                   4237:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 4238: 						       &escape($cdom),
                   4239: 						       $homeserver)));
1.709     albertel 4240:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4241: 	return (undef,undef);
                   4242:     }
1.706     raeburn  4243:     return ($update,$comment);
                   4244: }
                   4245: 
                   4246: sub auto_photoupdate {
                   4247:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   4248:     my $homeserver = &homeserver($cnum,$dom);
                   4249:     my $host=$hostname{$homeserver};
                   4250:     my $cmd = '';
                   4251:     my $maxtries = 1;
1.800     albertel 4252:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   4253:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  4254:     }
                   4255:     $cmd =~ s/%%$//;
                   4256:     $cmd = &escape($cmd);
                   4257:     my $query = 'institutionalphotos';
                   4258:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   4259:     unless ($queryid=~/^\Q$host\E\_/) {
                   4260:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   4261:         return 'error: '.$queryid;
                   4262:     }
                   4263:     my $reply = &get_query_reply($queryid);
                   4264:     my $tries = 1;
                   4265:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4266:         $reply = &get_query_reply($queryid);
                   4267:         $tries ++;
                   4268:     }
                   4269:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   4270:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   4271:     } else {
                   4272:         my @responses = split(/:/,$reply);
                   4273:         my $outcome = shift(@responses); 
                   4274:         foreach my $item (@responses) {
                   4275:             my ($key,$value) = split(/=/,$item);
                   4276:             $$photo{$key} = $value;
                   4277:         }
                   4278:         return $outcome;
                   4279:     }
                   4280:     return 'error';
                   4281: }
                   4282: 
1.521     raeburn  4283: sub auto_instcode_format {
1.793     albertel 4284:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   4285: 	$cat_order) = @_;
1.521     raeburn  4286:     my $courses = '';
1.772     raeburn  4287:     my @homeservers;
1.521     raeburn  4288:     if ($caller eq 'global') {
1.793     albertel 4289:         foreach my $tryserver (keys(%libserv)) {
1.584     raeburn  4290:             if ($hostdom{$tryserver} eq $codedom) {
1.793     albertel 4291:                 if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
1.772     raeburn  4292:                     push(@homeservers,$tryserver);
                   4293:                 }
1.584     raeburn  4294:             }
                   4295:         }
1.521     raeburn  4296:     } else {
1.772     raeburn  4297:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  4298:     }
1.793     albertel 4299:     foreach my $code (keys(%{$instcodes})) {
                   4300:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  4301:     }
                   4302:     chop($courses);
1.772     raeburn  4303:     my $ok_response = 0;
                   4304:     my $response;
                   4305:     while (@homeservers > 0 && $ok_response == 0) {
                   4306:         my $server = shift(@homeservers); 
                   4307:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   4308:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   4309:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.793     albertel 4310: 		split/:/,$response;
1.772     raeburn  4311:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   4312:             push(@{$codetitles},&str2array($codetitles_str));
                   4313:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   4314:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   4315:             $ok_response = 1;
                   4316:         }
                   4317:     }
                   4318:     if ($ok_response) {
1.521     raeburn  4319:         return 'ok';
1.772     raeburn  4320:     } else {
                   4321:         return $response;
1.521     raeburn  4322:     }
                   4323: }
                   4324: 
1.792     raeburn  4325: sub auto_instcode_defaults {
                   4326:     my ($domain,$returnhash,$code_order) = @_;
                   4327:     my @homeservers;
1.793     albertel 4328:     foreach my $tryserver (keys(%libserv)) {
1.792     raeburn  4329:         if ($hostdom{$tryserver} eq $domain) {
1.793     albertel 4330:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
1.792     raeburn  4331:                 push(@homeservers,$tryserver);
                   4332:             }
                   4333:         }
                   4334:     }
                   4335:     my $ok_response = 0;
                   4336:     my $response;
                   4337:     while (@homeservers > 0 && $ok_response == 0) {
                   4338:         my $server = shift(@homeservers);
                   4339:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
                   4340:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
1.793     albertel 4341:             foreach my $pair (split(/\&/,$response)) {
                   4342:                 my ($name,$value)=split(/\=/,$pair);
1.792     raeburn  4343:                 if ($name eq 'code_order') {
1.796     raeburn  4344:                     @{$code_order} = split(/\&/,&unescape($value));
1.792     raeburn  4345:                 } else {
1.796     raeburn  4346:                     $returnhash->{&unescape($name)}=&unescape($value);
1.792     raeburn  4347:                 }
                   4348:             }
1.804     raeburn  4349:             $ok_response = 1;
1.792     raeburn  4350:         }
                   4351:     }
                   4352:     if ($ok_response) {
                   4353:         return 'ok';
                   4354:     } else {
                   4355:         return $response;
                   4356:     }
                   4357: } 
                   4358: 
1.777     albertel 4359: sub auto_validate_class_sec {
1.773     raeburn  4360:     my ($cdom,$cnum,$owner,$inst_class) = @_;
                   4361:     my $homeserver = &homeserver($cnum,$cdom);
                   4362:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.774     banghart 4363:                         &escape($owner).':'.$cdom,$homeserver);
1.773     raeburn  4364:     return $response;
                   4365: }
                   4366: 
1.679     raeburn  4367: # ------------------------------------------------------- Course Group routines
                   4368: 
                   4369: sub get_coursegroups {
1.683     raeburn  4370:     my ($cdom,$cnum,$group) = @_;
                   4371:     return(&dump('coursegroups',$cdom,$cnum,$group));
1.679     raeburn  4372: }
                   4373: 
1.805     raeburn  4374: sub get_deleted_groups {
                   4375:     my ($cdom,$cnum,$group) = @_;
                   4376:     return(&dump('deleted_groups',$cdom,$cnum,$group));
                   4377: }
                   4378: 
1.679     raeburn  4379: sub modify_coursegroup {
                   4380:     my ($cdom,$cnum,$groupsettings) = @_;
                   4381:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   4382: }
                   4383: 
1.805     raeburn  4384: sub delete_coursegroup {
                   4385:     my ($cdom,$cnum,$group) = @_;
                   4386:     my %curr_group = &get_coursegroups($cdom,$cnum,$group);
                   4387:     if (my $tmp = &error(%curr_group)) {
                   4388:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   4389:         return ('read error',$tmp);
                   4390:     } else {
                   4391:         my %savedsettings = %curr_group; 
                   4392:         my $result = &put('deleted_groups',\%savedsettings,$cdom,$cnum);
                   4393:         my $deloutcome;
                   4394:         if ($result eq 'ok') {
                   4395:             $deloutcome = &del('coursegroups',[$group],$cdom,$cnum);
                   4396:         } else {
                   4397:             return ('write error',$result);
                   4398:         }
                   4399:         if ($deloutcome eq 'ok') {
                   4400:             return 'ok';
                   4401:         } else {
                   4402:             return ('delete error',$deloutcome);
                   4403:         }
                   4404:     }
                   4405: }
                   4406: 
1.679     raeburn  4407: sub modify_group_roles {
                   4408:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
                   4409:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   4410:     my $role = 'gr/'.&escape($userprivs);
                   4411:     my ($uname,$udom) = split(/:/,$user);
                   4412:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
1.684     raeburn  4413:     if ($result eq 'ok') {
                   4414:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   4415:     }
1.679     raeburn  4416:     return $result;
                   4417: }
                   4418: 
                   4419: sub modify_coursegroup_membership {
                   4420:     my ($cdom,$cnum,$membership) = @_;
                   4421:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   4422:     return $result;
                   4423: }
                   4424: 
1.682     raeburn  4425: sub get_active_groups {
                   4426:     my ($udom,$uname,$cdom,$cnum) = @_;
                   4427:     my $now = time;
                   4428:     my %groups = ();
                   4429:     foreach my $key (keys(%env)) {
                   4430:         if ($key =~ m-user\.role\.gr\./([^/]+)/([^/]+)/(\w+)$-) {
                   4431:             my ($start,$end) = split(/\./,$env{$key});
                   4432:             if (($end!=0) && ($end<$now)) { next; }
                   4433:             if (($start!=0) && ($start>$now)) { next; }
                   4434:             if ($1 eq $cdom && $2 eq $cnum) {
                   4435:                 $groups{$3} = $env{$key} ;
                   4436:             }
                   4437:         }
                   4438:     }
                   4439:     return %groups;
                   4440: }
                   4441: 
1.683     raeburn  4442: sub get_group_membership {
                   4443:     my ($cdom,$cnum,$group) = @_;
                   4444:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   4445: }
                   4446: 
                   4447: sub get_users_groups {
                   4448:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  4449:     my @usersgroups;
1.683     raeburn  4450:     my $cachetime=1800;
                   4451:     $courseid=~s/\_/\//g;
                   4452:     $courseid=~s/^(\w)/\/$1/;
                   4453: 
                   4454:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  4455:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   4456:     if (defined($cached)) {
1.734     albertel 4457:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  4458:     } else {  
                   4459:         $grouplist = '';
                   4460:         my %roleshash = &dump('roles',$udom,$uname,$courseid);
                   4461:         my ($tmp) = keys(%roleshash);
                   4462:         if ($tmp=~/^error:/) {
                   4463:             &logthis('Error retrieving roles: '.$tmp.' for '.$uname.':'.$udom);
                   4464:         } else {
                   4465:             my $access_end = $env{'course.'.$courseid.
                   4466:                                   '.default_enrollment_end_date'};
                   4467:             my $now = time;
1.734     albertel 4468:             foreach my $key (keys(%roleshash)) {
1.733     raeburn  4469:                 if ($key =~ /^\Q$courseid\E\/(\w+)\_gr$/) {
                   4470:                     my $group = $1;
                   4471:                     if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   4472:                         my $start = $2;
                   4473:                         my $end = $1;
                   4474:                         if ($start == -1) { next; } # deleted from group
                   4475:                         if (($start!=0) && ($start>$now)) { next; }
                   4476:                         if (($end!=0) && ($end<$now)) {
                   4477:                             if ($access_end && $access_end < $now) {
                   4478:                                 if ($access_end - $end < 86400) {
                   4479:                                     push(@usersgroups,$group);
                   4480:                                 }
                   4481:                             }
                   4482:                             next;
                   4483:                         }
                   4484:                         push(@usersgroups,$group);
                   4485:                     }
1.683     raeburn  4486:                 }
                   4487:             }
1.733     raeburn  4488:             @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   4489:             $grouplist = join(':',@usersgroups);
                   4490:             &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  4491:         }
                   4492:     }
1.733     raeburn  4493:     return @usersgroups;
1.683     raeburn  4494: }
                   4495: 
                   4496: sub devalidate_getgroups_cache {
                   4497:     my ($udom,$uname,$cdom,$cnum)=@_;
                   4498:     my $courseid = $cdom.'_'.$cnum;
                   4499:     $courseid=~s/\_/\//g;
                   4500:     $courseid=~s/^(\w)/\/$1/;
                   4501:     my $hashid="$udom:$uname:$courseid";
                   4502:     &devalidate_cache_new('getgroups',$hashid);
                   4503: }
                   4504: 
1.12      www      4505: # ------------------------------------------------------------------ Plain Text
                   4506: 
                   4507: sub plaintext {
1.742     raeburn  4508:     my ($short,$type,$cid) = @_;
1.758     albertel 4509:     if ($short =~ /^cr/) {
                   4510: 	return (split('/',$short))[-1];
                   4511:     }
1.742     raeburn  4512:     if (!defined($cid)) {
                   4513:         $cid = $env{'request.course.id'};
                   4514:     }
                   4515:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
                   4516:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
                   4517:                                           '.plaintext'});
                   4518:     }
                   4519:     my %rolenames = (
                   4520:                       Course => 'std',
                   4521:                       Group => 'alt1',
                   4522:                     );
                   4523:     if (defined($type) && 
                   4524:          defined($rolenames{$type}) && 
                   4525:          defined($prp{$short}{$rolenames{$type}})) {
                   4526:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   4527:     } else {
                   4528:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   4529:     }
1.12      www      4530: }
                   4531: 
                   4532: # ----------------------------------------------------------------- Assign Role
                   4533: 
                   4534: sub assignrole {
1.357     www      4535:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
1.21      www      4536:     my $mrole;
                   4537:     if ($role =~ /^cr\//) {
1.393     www      4538:         my $cwosec=$url;
                   4539:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
                   4540: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      4541:            &logthis('Refused custom assignrole: '.
                   4542:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4543: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4544:            return 'refused'; 
                   4545:         }
1.21      www      4546:         $mrole='cr';
1.678     raeburn  4547:     } elsif ($role =~ /^gr\//) {
                   4548:         my $cwogrp=$url;
                   4549:         $cwogrp=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
                   4550:         unless (&allowed('mdg',$cwogrp)) {
                   4551:             &logthis('Refused group assignrole: '.
                   4552:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   4553:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   4554:             return 'refused';
                   4555:         }
                   4556:         $mrole='gr';
1.21      www      4557:     } else {
1.82      www      4558:         my $cwosec=$url;
1.83      www      4559:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
1.373     www      4560:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
1.104     www      4561:            &logthis('Refused assignrole: '.
                   4562:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4563: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4564:            return 'refused'; 
                   4565:         }
1.21      www      4566:         $mrole=$role;
                   4567:     }
1.620     albertel 4568:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4569:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      4570:     if ($end) { $command.='_'.$end; }
1.21      www      4571:     if ($start) {
                   4572: 	if ($end) { 
1.81      www      4573:            $command.='_'.$start; 
1.21      www      4574:         } else {
1.81      www      4575:            $command.='_0_'.$start;
1.21      www      4576:         }
                   4577:     }
1.739     raeburn  4578:     my $origstart = $start;
                   4579:     my $origend = $end;
1.357     www      4580: # actually delete
                   4581:     if ($deleteflag) {
1.373     www      4582: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      4583: # modify command to delete the role
1.620     albertel 4584:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      4585:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 4586: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      4587: # set start and finish to negative values for userrolelog
                   4588:            $start=-1;
                   4589:            $end=-1;
                   4590:         }
                   4591:     }
                   4592: # send command
1.349     www      4593:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      4594: # log new user role if status is ok
1.349     www      4595:     if ($answer eq 'ok') {
1.663     raeburn  4596: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  4597: # for course roles, perform group memberships changes triggered by role change.
                   4598:         unless ($role =~ /^gr/) {
                   4599:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   4600:                                              $origstart);
                   4601:         }
1.349     www      4602:     }
                   4603:     return $answer;
1.169     harris41 4604: }
                   4605: 
                   4606: # -------------------------------------------------- Modify user authentication
1.197     www      4607: # Overrides without validation
                   4608: 
1.169     harris41 4609: sub modifyuserauth {
                   4610:     my ($udom,$uname,$umode,$upass)=@_;
                   4611:     my $uhome=&homeserver($uname,$udom);
1.197     www      4612:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   4613:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 4614:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4615:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 4616:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   4617: 		     &escape($upass),$uhome);
1.620     albertel 4618:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      4619:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   4620:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   4621:     &log($udom,,$uname,$uhome,
1.620     albertel 4622:         'Authentication changed by '.$env{'user.domain'}.', '.
                   4623:                                      $env{'user.name'}.', '.$umode.
1.197     www      4624:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 4625:     unless ($reply eq 'ok') {
1.197     www      4626:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 4627: 	return 'error: '.$reply;
                   4628:     }   
1.170     harris41 4629:     return 'ok';
1.80      www      4630: }
                   4631: 
1.81      www      4632: # --------------------------------------------------------------- Modify a user
1.80      www      4633: 
1.81      www      4634: sub modifyuser {
1.206     matthew  4635:     my ($udom,    $uname, $uid,
                   4636:         $umode,   $upass, $first,
                   4637:         $middle,  $last,  $gene,
1.387     www      4638:         $forceid, $desiredhome, $email)=@_;
1.198     www      4639:     $udom=~s/\W//g;
                   4640:     $uname=~s/\W//g;
1.81      www      4641:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4642:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  4643: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   4644:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   4645:                                      ' desiredhome not specified'). 
1.620     albertel 4646:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4647:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 4648:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      4649: # ----------------------------------------------------------------- Create User
1.406     albertel 4650:     if (($uhome eq 'no_host') && 
                   4651: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      4652:         my $unhome='';
1.209     matthew  4653:         if (defined($desiredhome) && $hostdom{$desiredhome} eq $udom) { 
                   4654:             $unhome = $desiredhome;
1.620     albertel 4655: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   4656: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  4657:         } else { # load balancing routine for determining $unhome
1.80      www      4658:             my $tryserver;
1.81      www      4659:             my $loadm=10000000;
1.80      www      4660:             foreach $tryserver (keys %libserv) {
                   4661: 	       if ($hostdom{$tryserver} eq $udom) {
                   4662:                   my $answer=reply('load',$tryserver);
                   4663:                   if (($answer=~/\d+/) && ($answer<$loadm)) {
                   4664: 		      $loadm=$answer;
                   4665:                       $unhome=$tryserver;
                   4666:                   }
                   4667: 	       }
                   4668: 	    }
                   4669:         }
                   4670:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  4671: 	    return 'error: unable to find a home server for '.$uname.
                   4672:                    ' in domain '.$udom;
1.80      www      4673:         }
                   4674:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   4675:                          &escape($upass),$unhome);
                   4676: 	unless ($reply eq 'ok') {
                   4677:             return 'error: '.$reply;
                   4678:         }   
1.230     stredwic 4679:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      4680:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  4681: 	    return 'error: unable verify users home machine.';
1.80      www      4682:         }
1.209     matthew  4683:     }   # End of creation of new user
1.80      www      4684: # ---------------------------------------------------------------------- Add ID
                   4685:     if ($uid) {
                   4686:        $uid=~tr/A-Z/a-z/;
                   4687:        my %uidhash=&idrget($udom,$uname);
1.196     www      4688:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   4689:          && (!$forceid)) {
1.80      www      4690: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  4691: 	      return 'error: user id "'.$uid.'" does not match '.
                   4692:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      4693:           }
                   4694:        } else {
                   4695: 	  &idput($udom,($uname => $uid));
                   4696:        }
                   4697:     }
                   4698: # -------------------------------------------------------------- Add names, etc
1.313     matthew  4699:     my @tmp=&get('environment',
1.134     albertel 4700: 		   ['firstname','middlename','lastname','generation'],
                   4701: 		   $udom,$uname);
1.313     matthew  4702:     my %names;
                   4703:     if ($tmp[0] =~ m/^error:.*/) { 
                   4704:         %names=(); 
                   4705:     } else {
                   4706:         %names = @tmp;
                   4707:     }
1.388     www      4708: #
                   4709: # Make sure to not trash student environment if instructor does not bother
                   4710: # to supply name and email information
                   4711: #
                   4712:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  4713:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      4714:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  4715:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      4716:     if ($email) {
                   4717:        $email=~s/[^\w\@\.\-\,]//gs;
                   4718:        if ($email=~/\@/) { $names{'notification'} = $email;
                   4719: 			   $names{'critnotification'} = $email;
                   4720: 			   $names{'permanentemail'} = $email; }
                   4721:     }
1.134     albertel 4722:     my $reply = &put('environment', \%names, $udom,$uname);
                   4723:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.680     www      4724:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.81      www      4725:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4726:              $umode.', '.$first.', '.$middle.', '.
                   4727: 	     $last.', '.$gene.' by '.
1.620     albertel 4728:              $env{'user.name'}.' at '.$env{'user.domain'});
1.134     albertel 4729:     return 'ok';
1.80      www      4730: }
                   4731: 
1.81      www      4732: # -------------------------------------------------------------- Modify student
1.80      www      4733: 
1.81      www      4734: sub modifystudent {
                   4735:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.515     raeburn  4736:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
1.455     albertel 4737:     if (!$cid) {
1.620     albertel 4738: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 4739: 	    return 'not_in_class';
                   4740: 	}
1.80      www      4741:     }
                   4742: # --------------------------------------------------------------- Make the user
1.81      www      4743:     my $reply=&modifyuser
1.209     matthew  4744: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      4745:          $desiredhome,$email);
1.80      www      4746:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  4747:     # This will cause &modify_student_enrollment to get the uid from the
                   4748:     # students environment
                   4749:     $uid = undef if (!$forceid);
1.455     albertel 4750:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.515     raeburn  4751: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
1.297     matthew  4752:     return $reply;
                   4753: }
                   4754: 
                   4755: sub modify_student_enrollment {
1.515     raeburn  4756:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
1.455     albertel 4757:     my ($cdom,$cnum,$chome);
                   4758:     if (!$cid) {
1.620     albertel 4759: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 4760: 	    return 'not_in_class';
                   4761: 	}
1.620     albertel 4762: 	$cdom=$env{'course.'.$cid.'.domain'};
                   4763: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 4764:     } else {
                   4765: 	($cdom,$cnum)=split(/_/,$cid);
                   4766:     }
1.620     albertel 4767:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 4768:     if (!$chome) {
1.457     raeburn  4769: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  4770:     }
1.455     albertel 4771:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  4772:     # Make sure the user exists
1.81      www      4773:     my $uhome=&homeserver($uname,$udom);
                   4774:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   4775: 	return 'error: no such user';
                   4776:     }
1.297     matthew  4777:     # Get student data if we were not given enough information
                   4778:     if (!defined($first)  || $first  eq '' || 
                   4779:         !defined($last)   || $last   eq '' || 
                   4780:         !defined($uid)    || $uid    eq '' || 
                   4781:         !defined($middle) || $middle eq '' || 
                   4782:         !defined($gene)   || $gene   eq '') {
1.294     matthew  4783:         # They did not supply us with enough data to enroll the student, so
                   4784:         # we need to pick up more information.
1.297     matthew  4785:         my %tmp = &get('environment',
1.294     matthew  4786:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  4787:                        ,$udom,$uname);
                   4788: 
1.800     albertel 4789:         #foreach my $key (keys(%tmp)) {
                   4790:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 4791:         #}
1.294     matthew  4792:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   4793:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   4794:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  4795:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  4796:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   4797:     }
1.556     albertel 4798:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 4799:     my $reply=cput('classlist',
                   4800: 		   {"$uname:$udom" => 
1.515     raeburn  4801: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 4802: 		   $cdom,$cnum);
1.81      www      4803:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   4804: 	return 'error: '.$reply;
1.652     albertel 4805:     } else {
                   4806: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      4807:     }
1.297     matthew  4808:     # Add student role to user
1.83      www      4809:     my $uurl='/'.$cid;
1.81      www      4810:     $uurl=~s/\_/\//g;
                   4811:     if ($usec) {
                   4812: 	$uurl.='/'.$usec;
                   4813:     }
                   4814:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21      www      4815: }
                   4816: 
1.556     albertel 4817: sub format_name {
                   4818:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   4819:     my $name;
                   4820:     if ($first ne 'lastname') {
                   4821: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   4822:     } else {
                   4823: 	if ($lastname=~/\S/) {
                   4824: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   4825: 	    $name=~s/\s+,/,/;
                   4826: 	} else {
                   4827: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   4828: 	}
                   4829:     }
                   4830:     $name=~s/^\s+//;
                   4831:     $name=~s/\s+$//;
                   4832:     $name=~s/\s+/ /g;
                   4833:     return $name;
                   4834: }
                   4835: 
1.84      www      4836: # ------------------------------------------------- Write to course preferences
                   4837: 
                   4838: sub writecoursepref {
                   4839:     my ($courseid,%prefs)=@_;
                   4840:     $courseid=~s/^\///;
                   4841:     $courseid=~s/\_/\//g;
                   4842:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   4843:     my $chome=homeserver($cnum,$cdomain);
                   4844:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   4845: 	return 'error: no such course';
                   4846:     }
                   4847:     my $cstring='';
1.800     albertel 4848:     foreach my $pref (keys(%prefs)) {
                   4849: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 4850:     }
1.84      www      4851:     $cstring=~s/\&$//;
                   4852:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   4853: }
                   4854: 
                   4855: # ---------------------------------------------------------- Make/modify course
                   4856: 
                   4857: sub createcourse {
1.741     raeburn  4858:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
                   4859:         $course_owner,$crstype)=@_;
1.84      www      4860:     $url=&declutter($url);
                   4861:     my $cid='';
1.264     matthew  4862:     unless (&allowed('ccc',$udom)) {
1.84      www      4863:         return 'refused';
                   4864:     }
                   4865: # ------------------------------------------------------------------- Create ID
1.674     www      4866:    my $uname=int(1+rand(9)).
                   4867:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   4868:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      4869:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   4870: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 4871:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      4872:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   4873:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   4874:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 4875:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      4876:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   4877:            return 'error: unable to generate unique course-ID';
                   4878:        } 
                   4879:    }
1.264     matthew  4880: # ------------------------------------------------ Check supplied server name
1.620     albertel 4881:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.264     matthew  4882:     if (! exists($libserv{$course_server})) {
                   4883:         return 'error:bad server name '.$course_server;
                   4884:     }
1.84      www      4885: # ------------------------------------------------------------- Make the course
                   4886:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  4887:                       $course_server);
1.84      www      4888:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 4889:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      4890:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   4891: 	return 'error: no such course';
                   4892:     }
1.271     www      4893: # ----------------------------------------------------------------- Course made
1.516     raeburn  4894: # log existence
                   4895:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
1.741     raeburn  4896:                  ':'.&escape($inst_code).':'.&escape($course_owner).':'.
                   4897:                   &escape($crstype),$uhome);
1.358     www      4898:     &flushcourselogs();
                   4899: # set toplevel url
1.271     www      4900:     my $topurl=$url;
                   4901:     unless ($nonstandard) {
                   4902: # ------------------------------------------ For standard courses, make top url
                   4903:         my $mapurl=&clutter($url);
1.278     www      4904:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 4905:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      4906: <map>
                   4907: <resource id="1" type="start"></resource>
                   4908: <resource id="2" src="$mapurl"></resource>
                   4909: <resource id="3" type="finish"></resource>
                   4910: <link index="1" from="1" to="2"></link>
                   4911: <link index="2" from="2" to="3"></link>
                   4912: </map>
                   4913: ENDINITMAP
                   4914:         $topurl=&declutter(
1.638     albertel 4915:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      4916:                           );
                   4917:     }
                   4918: # ----------------------------------------------------------- Write preferences
1.84      www      4919:     &writecoursepref($udom.'_'.$uname,
                   4920:                      ('description' => $description,
1.271     www      4921:                       'url'         => $topurl));
1.84      www      4922:     return '/'.$udom.'/'.$uname;
                   4923: }
                   4924: 
1.21      www      4925: # ---------------------------------------------------------- Assign Custom Role
                   4926: 
                   4927: sub assigncustomrole {
1.357     www      4928:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21      www      4929:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357     www      4930:                        $end,$start,$deleteflag);
1.21      www      4931: }
                   4932: 
                   4933: # ----------------------------------------------------------------- Revoke Role
                   4934: 
                   4935: sub revokerole {
1.357     www      4936:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21      www      4937:     my $now=time;
1.357     www      4938:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21      www      4939: }
                   4940: 
                   4941: # ---------------------------------------------------------- Revoke Custom Role
                   4942: 
                   4943: sub revokecustomrole {
1.357     www      4944:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21      www      4945:     my $now=time;
1.357     www      4946:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
                   4947:            $deleteflag);
1.17      www      4948: }
                   4949: 
1.533     banghart 4950: # ------------------------------------------------------------ Disk usage
1.535     albertel 4951: sub diskusage {
1.533     banghart 4952:     my ($udom,$uname,$directoryRoot)=@_;
                   4953:     $directoryRoot =~ s/\/$//;
1.535     albertel 4954:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
1.514     albertel 4955:     return $listing;
1.512     banghart 4956: }
                   4957: 
1.566     banghart 4958: sub is_locked {
                   4959:     my ($file_name, $domain, $user) = @_;
                   4960:     my @check;
                   4961:     my $is_locked;
                   4962:     push @check, $file_name;
1.613     albertel 4963:     my %locked = &get('file_permissions',\@check,
1.620     albertel 4964: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 4965:     my ($tmp)=keys(%locked);
                   4966:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  4967:     
1.566     banghart 4968:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  4969:         $is_locked = 'false';
                   4970:         foreach my $entry (@{$locked{$file_name}}) {
                   4971:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  4972:                $is_locked = 'true';
                   4973:                last;
1.745     raeburn  4974:            }
                   4975:        }
1.566     banghart 4976:     } else {
                   4977:         $is_locked = 'false';
                   4978:     }
                   4979: }
                   4980: 
1.759     albertel 4981: sub declutter_portfile {
                   4982:     my ($file) = @_;
                   4983:     &logthis("got $file");
                   4984:     $file =~ s-^(/portfolio/|portfolio/)-/-;
                   4985:     &logthis("ret $file");
                   4986:     return $file;
                   4987: }
                   4988: 
1.559     banghart 4989: # ------------------------------------------------------------- Mark as Read Only
                   4990: 
                   4991: sub mark_as_readonly {
                   4992:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 4993:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 4994:     my ($tmp)=keys(%current_permissions);
                   4995:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 4996:     foreach my $file (@{$files}) {
1.759     albertel 4997: 	$file = &declutter_portfile($file);
1.561     banghart 4998:         push(@{$current_permissions{$file}},$what);
1.559     banghart 4999:     }
1.613     albertel 5000:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5001:     return;
                   5002: }
                   5003: 
1.572     banghart 5004: # ------------------------------------------------------------Save Selected Files
                   5005: 
                   5006: sub save_selected_files {
                   5007:     my ($user, $path, @files) = @_;
                   5008:     my $filename = $user."savedfiles";
1.573     banghart 5009:     my @other_files = &files_not_in_path($user, $path);
1.574     banghart 5010:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 5011:     foreach my $file (@files) {
1.620     albertel 5012:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 5013:     }
                   5014:     foreach my $file (@other_files) {
1.574     banghart 5015:         print (OUT $file."\n");
1.572     banghart 5016:     }
1.574     banghart 5017:     close (OUT);
1.572     banghart 5018:     return 'ok';
                   5019: }
                   5020: 
1.574     banghart 5021: sub clear_selected_files {
                   5022:     my ($user) = @_;
                   5023:     my $filename = $user."savedfiles";
                   5024:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5025:     print (OUT undef);
                   5026:     close (OUT);
                   5027:     return ("ok");    
                   5028: }
                   5029: 
1.572     banghart 5030: sub files_in_path {
                   5031:     my ($user, $path) = @_;
                   5032:     my $filename = $user."savedfiles";
                   5033:     my %return_files;
1.574     banghart 5034:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 5035:     while (my $line_in = <IN>) {
1.574     banghart 5036:         chomp ($line_in);
                   5037:         my @paths_and_file = split (m!/!, $line_in);
                   5038:         my $file_part = pop (@paths_and_file);
                   5039:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 5040:         $path_part.='/';
                   5041:         my $path_and_file = $path_part.$file_part;
                   5042:         if ($path_part eq $path) {
                   5043:             $return_files{$file_part}= 'selected';
                   5044:         }
                   5045:     }
1.574     banghart 5046:     close (IN);
                   5047:     return (\%return_files);
1.572     banghart 5048: }
                   5049: 
                   5050: # called in portfolio select mode, to show files selected NOT in current directory
                   5051: sub files_not_in_path {
                   5052:     my ($user, $path) = @_;
                   5053:     my $filename = $user."savedfiles";
                   5054:     my @return_files;
                   5055:     my $path_part;
1.800     albertel 5056:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5057:     while (my $line = <IN>) {
1.572     banghart 5058:         #ok, I know it's clunky, but I want it to work
1.800     albertel 5059:         my @paths_and_file = split(m|/|, $line);
                   5060:         my $file_part = pop(@paths_and_file);
                   5061:         chomp($file_part);
                   5062:         my $path_part = join('/', @paths_and_file);
1.572     banghart 5063:         $path_part .= '/';
                   5064:         my $path_and_file = $path_part.$file_part;
                   5065:         if ($path_part ne $path) {
1.800     albertel 5066:             push(@return_files, ($path_and_file));
1.572     banghart 5067:         }
                   5068:     }
1.800     albertel 5069:     close(OUT);
1.574     banghart 5070:     return (@return_files);
1.572     banghart 5071: }
                   5072: 
1.745     raeburn  5073: #----------------------------------------------Get portfolio file permissions
1.629     banghart 5074: 
1.745     raeburn  5075: sub get_portfile_permissions {
                   5076:     my ($domain,$user) = @_;
1.613     albertel 5077:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5078:     my ($tmp)=keys(%current_permissions);
                   5079:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5080:     return \%current_permissions;
                   5081: }
                   5082: 
                   5083: #---------------------------------------------Get portfolio file access controls
                   5084: 
1.749     raeburn  5085: sub get_access_controls {
1.745     raeburn  5086:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 5087:     my %access;
                   5088:     my $real_file = $file;
                   5089:     $file =~ s/\.meta$//;
1.745     raeburn  5090:     if (defined($file)) {
1.749     raeburn  5091:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   5092:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 5093:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  5094:             }
                   5095:         }
1.745     raeburn  5096:     } else {
1.749     raeburn  5097:         foreach my $key (keys(%{$current_permissions})) {
                   5098:             if ($key =~ /\0accesscontrol$/) {
                   5099:                 if (defined($group)) {
                   5100:                     if ($key !~ m-^\Q$group\E/-) {
                   5101:                         next;
                   5102:                     }
                   5103:                 }
                   5104:                 my ($fullpath) = split(/\0/,$key);
                   5105:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   5106:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   5107:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   5108:                     }
                   5109:                 }
                   5110:             }
                   5111:         }
                   5112:     }
                   5113:     return %access;
                   5114: }
                   5115: 
                   5116: sub modify_access_controls {
                   5117:     my ($file_name,$changes,$domain,$user)=@_;
                   5118:     my ($outcome,$deloutcome);
                   5119:     my %store_permissions;
                   5120:     my %new_values;
                   5121:     my %new_control;
                   5122:     my %translation;
                   5123:     my @deletions = ();
                   5124:     my $now = time;
                   5125:     if (exists($$changes{'activate'})) {
                   5126:         if (ref($$changes{'activate'}) eq 'HASH') {
                   5127:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   5128:             my $numnew = scalar(@newitems);
                   5129:             for (my $i=0; $i<$numnew; $i++) {
                   5130:                 my $newkey = $newitems[$i];
                   5131:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  5132:                 if ($newkey =~ /^\d+:/) { 
                   5133:                     $newkey =~ s/^(\d+)/$newid/;
                   5134:                     $translation{$1} = $newid;
                   5135:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   5136:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   5137:                     $translation{$1} = $newid;
                   5138:                 }
1.749     raeburn  5139:                 $new_values{$file_name."\0".$newkey} = 
                   5140:                                           $$changes{'activate'}{$newitems[$i]};
                   5141:                 $new_control{$newkey} = $now;
                   5142:             }
                   5143:         }
                   5144:     }
                   5145:     my %todelete;
                   5146:     my %changed_items;
                   5147:     foreach my $action ('delete','update') {
                   5148:         if (exists($$changes{$action})) {
                   5149:             if (ref($$changes{$action}) eq 'HASH') {
                   5150:                 foreach my $key (keys(%{$$changes{$action}})) {
                   5151:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   5152:                     if ($action eq 'delete') { 
                   5153:                         $todelete{$itemnum} = 1;
                   5154:                     } else {
                   5155:                         $changed_items{$itemnum} = $key;
                   5156:                     }
                   5157:                 }
1.745     raeburn  5158:             }
                   5159:         }
1.749     raeburn  5160:     }
                   5161:     # get lock on access controls for file.
                   5162:     my $lockhash = {
                   5163:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   5164:                                                        ':'.$env{'user.domain'},
                   5165:                    }; 
                   5166:     my $tries = 0;
                   5167:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5168:    
                   5169:     while (($gotlock ne 'ok') && $tries <3) {
                   5170:         $tries ++;
                   5171:         sleep 1;
                   5172:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5173:     }
                   5174:     if ($gotlock eq 'ok') {
                   5175:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   5176:         my ($tmp)=keys(%curr_permissions);
                   5177:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   5178:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   5179:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   5180:             if (ref($curr_controls) eq 'HASH') {
                   5181:                 foreach my $control_item (keys(%{$curr_controls})) {
                   5182:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   5183:                     if (defined($todelete{$itemnum})) {
                   5184:                         push(@deletions,$file_name."\0".$control_item);
                   5185:                     } else {
                   5186:                         if (defined($changed_items{$itemnum})) {
                   5187:                             $new_control{$changed_items{$itemnum}} = $now;
                   5188:                             push(@deletions,$file_name."\0".$control_item);
                   5189:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   5190:                         } else {
                   5191:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   5192:                         }
                   5193:                     }
1.745     raeburn  5194:                 }
                   5195:             }
                   5196:         }
1.749     raeburn  5197:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   5198:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   5199:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   5200:         #  remove lock
                   5201:         my @del_lock = ($file_name."\0".'locked_access_records');
                   5202:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
                   5203:     } else {
                   5204:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  5205:     }
1.749     raeburn  5206:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  5207: }
                   5208: 
                   5209: #------------------------------------------------------Get Marked as Read Only
                   5210: 
                   5211: sub get_marked_as_readonly {
                   5212:     my ($domain,$user,$what,$group) = @_;
                   5213:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 5214:     my @readonly_files;
1.629     banghart 5215:     my $cmp1=$what;
                   5216:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  5217:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5218:         if (defined($group)) {
                   5219:             if ($file_name !~ m-^\Q$group\E/-) {
                   5220:                 next;
                   5221:             }
                   5222:         }
1.561     banghart 5223:         if (ref($value) eq "ARRAY"){
                   5224:             foreach my $stored_what (@{$value}) {
1.629     banghart 5225:                 my $cmp2=$stored_what;
1.759     albertel 5226:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  5227:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  5228:                 }
1.629     banghart 5229:                 if ($cmp1 eq $cmp2) {
1.561     banghart 5230:                     push(@readonly_files, $file_name);
1.745     raeburn  5231:                     last;
1.563     banghart 5232:                 } elsif (!defined($what)) {
                   5233:                     push(@readonly_files, $file_name);
1.745     raeburn  5234:                     last;
1.561     banghart 5235:                 }
                   5236:             }
1.745     raeburn  5237:         }
1.561     banghart 5238:     }
                   5239:     return @readonly_files;
                   5240: }
1.577     banghart 5241: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 5242: 
1.577     banghart 5243: sub get_marked_as_readonly_hash {
1.745     raeburn  5244:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 5245:     my %readonly_files;
1.745     raeburn  5246:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5247:         if (defined($group)) {
                   5248:             if ($file_name !~ m-^\Q$group\E/-) {
                   5249:                 next;
                   5250:             }
                   5251:         }
1.577     banghart 5252:         if (ref($value) eq "ARRAY"){
                   5253:             foreach my $stored_what (@{$value}) {
1.745     raeburn  5254:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 5255:                     foreach my $lock_descriptor(@{$stored_what}) {
                   5256:                         if ($lock_descriptor eq 'graded') {
                   5257:                             $readonly_files{$file_name} = 'graded';
                   5258:                         } elsif ($lock_descriptor eq 'handback') {
                   5259:                             $readonly_files{$file_name} = 'handback';
                   5260:                         } else {
                   5261:                             if (!exists($readonly_files{$file_name})) {
                   5262:                                 $readonly_files{$file_name} = 'locked';
                   5263:                             }
                   5264:                         }
1.745     raeburn  5265:                     }
1.750     banghart 5266:                 } 
1.577     banghart 5267:             }
                   5268:         } 
                   5269:     }
                   5270:     return %readonly_files;
                   5271: }
1.559     banghart 5272: # ------------------------------------------------------------ Unmark as Read Only
                   5273: 
                   5274: sub unmark_as_readonly {
1.629     banghart 5275:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   5276:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  5277:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 5278:     $file_name = &declutter_portfile($file_name);
1.634     albertel 5279:     my $symb_crs = $what;
                   5280:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  5281:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 5282:     my ($tmp)=keys(%current_permissions);
                   5283:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5284:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 5285:     foreach my $file (@readonly_files) {
1.759     albertel 5286: 	my $clean_file = &declutter_portfile($file);
                   5287: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 5288: 	my $current_locks = $current_permissions{$file};
1.563     banghart 5289:         my @new_locks;
                   5290:         my @del_keys;
                   5291:         if (ref($current_locks) eq "ARRAY"){
                   5292:             foreach my $locker (@{$current_locks}) {
1.632     albertel 5293:                 my $compare=$locker;
1.749     raeburn  5294:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  5295:                     $compare=join('',@{$locker});
1.746     raeburn  5296:                     if ($compare ne $symb_crs) {
                   5297:                         push(@new_locks, $locker);
                   5298:                     }
1.563     banghart 5299:                 }
                   5300:             }
1.650     albertel 5301:             if (scalar(@new_locks) > 0) {
1.563     banghart 5302:                 $current_permissions{$file} = \@new_locks;
                   5303:             } else {
                   5304:                 push(@del_keys, $file);
1.613     albertel 5305:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 5306:                 delete($current_permissions{$file});
1.563     banghart 5307:             }
                   5308:         }
1.561     banghart 5309:     }
1.613     albertel 5310:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5311:     return;
                   5312: }
1.512     banghart 5313: 
1.17      www      5314: # ------------------------------------------------------------ Directory lister
                   5315: 
                   5316: sub dirlist {
1.253     stredwic 5317:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
                   5318: 
1.18      www      5319:     $uri=~s/^\///;
                   5320:     $uri=~s/\/$//;
1.253     stredwic 5321:     my ($udom, $uname);
                   5322:     (undef,$udom,$uname)=split(/\//,$uri);
                   5323:     if(defined($userdomain)) {
                   5324:         $udom = $userdomain;
                   5325:     }
                   5326:     if(defined($username)) {
                   5327:         $uname = $username;
                   5328:     }
                   5329: 
                   5330:     my $dirRoot = $perlvar{'lonDocRoot'};
                   5331:     if(defined($alternateDirectoryRoot)) {
                   5332:         $dirRoot = $alternateDirectoryRoot;
                   5333:         $dirRoot =~ s/\/$//;
1.751     banghart 5334:     }
1.253     stredwic 5335: 
                   5336:     if($udom) {
                   5337:         if($uname) {
1.800     albertel 5338:             my $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   5339: 				 &homeserver($uname,$udom));
1.605     matthew  5340:             my @listing_results;
                   5341:             if ($listing eq 'unknown_cmd') {
1.800     albertel 5342:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   5343: 				  &homeserver($uname,$udom));
1.605     matthew  5344:                 @listing_results = split(/:/,$listing);
                   5345:             } else {
                   5346:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   5347:             }
                   5348:             return @listing_results;
1.253     stredwic 5349:         } elsif(!defined($alternateDirectoryRoot)) {
1.800     albertel 5350:             my %allusers;
                   5351:             foreach my $tryserver (keys(%libserv)) {
1.253     stredwic 5352:                 if($hostdom{$tryserver} eq $udom) {
1.800     albertel 5353:                     my $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   5354: 					 $udom, $tryserver);
1.605     matthew  5355:                     my @listing_results;
                   5356:                     if ($listing eq 'unknown_cmd') {
1.800     albertel 5357:                         $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   5358: 					  $udom, $tryserver);
1.605     matthew  5359:                         @listing_results = split(/:/,$listing);
                   5360:                     } else {
                   5361:                         @listing_results =
                   5362:                             map { &unescape($_); } split(/:/,$listing);
                   5363:                     }
                   5364:                     if ($listing_results[0] ne 'no_such_dir' && 
                   5365:                         $listing_results[0] ne 'empty'       &&
                   5366:                         $listing_results[0] ne 'con_lost') {
1.800     albertel 5367:                         foreach my $line (@listing_results) {
                   5368:                             my ($entry) = split(/&/,$line,2);
                   5369:                             $allusers{$entry} = 1;
1.253     stredwic 5370:                         }
                   5371:                     }
1.191     harris41 5372:                 }
1.253     stredwic 5373:             }
                   5374:             my $alluserstr='';
1.800     albertel 5375:             foreach my $user (sort(keys(%allusers))) {
                   5376:                 $alluserstr.=$user.'&user:';
1.253     stredwic 5377:             }
                   5378:             $alluserstr=~s/:$//;
                   5379:             return split(/:/,$alluserstr);
                   5380:         } else {
1.800     albertel 5381:             return ('missing user name');
1.253     stredwic 5382:         }
                   5383:     } elsif(!defined($alternateDirectoryRoot)) {
                   5384:         my $tryserver;
                   5385:         my %alldom=();
1.800     albertel 5386:         foreach $tryserver (keys(%libserv)) {
1.253     stredwic 5387:             $alldom{$hostdom{$tryserver}}=1;
                   5388:         }
                   5389:         my $alldomstr='';
1.800     albertel 5390:         foreach my $domain (sort(keys(%alldom))) {
                   5391:             $alldomstr.=$perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain:';
1.253     stredwic 5392:         }
                   5393:         $alldomstr=~s/:$//;
                   5394:         return split(/:/,$alldomstr);       
                   5395:     } else {
1.800     albertel 5396:         return ('missing domain');
1.275     stredwic 5397:     }
                   5398: }
                   5399: 
                   5400: # --------------------------------------------- GetFileTimestamp
                   5401: # This function utilizes dirlist and returns the date stamp for
                   5402: # when it was last modified.  It will also return an error of -1
                   5403: # if an error occurs
                   5404: 
1.410     matthew  5405: ##
                   5406: ## FIXME: This subroutine assumes its caller knows something about the
                   5407: ## directory structure of the home server for the student ($root).
                   5408: ## Not a good assumption to make.  Since this is for looking up files
                   5409: ## in user directories, the full path should be constructed by lond, not
                   5410: ## whatever machine we request data from.
                   5411: ##
1.275     stredwic 5412: sub GetFileTimestamp {
                   5413:     my ($studentDomain,$studentName,$filename,$root)=@_;
                   5414:     $studentDomain=~s/\W//g;
                   5415:     $studentName=~s/\W//g;
                   5416:     my $subdir=$studentName.'__';
                   5417:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   5418:     my $proname="$studentDomain/$subdir/$studentName";
                   5419:     $proname .= '/'.$filename;
1.375     matthew  5420:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
                   5421:                                               $studentName, $root);
1.275     stredwic 5422:     my @stats = split('&', $fileStat);
                   5423:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  5424:         # @stats contains first the filename, then the stat output
                   5425:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 5426:     } else {
                   5427:         return -1;
1.253     stredwic 5428:     }
1.26      www      5429: }
                   5430: 
1.712     albertel 5431: sub stat_file {
                   5432:     my ($uri) = @_;
1.787     albertel 5433:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 5434: 
1.712     albertel 5435:     my ($udom,$uname,$file,$dir);
                   5436:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   5437: 	($udom,$uname,$file) =
                   5438: 	    ($uri =~ m-/(?:uploaded|editupload)/?([^/]*)/?([^/]*)/?(.*)-);
                   5439: 	$file = 'userfiles/'.$file;
1.740     www      5440: 	$dir = &propath($udom,$uname);
1.712     albertel 5441:     }
                   5442:     if ($uri =~ m-^/res/-) {
                   5443: 	($udom,$uname) = 
                   5444: 	    ($uri =~ m-/(?:res)/?([^/]*)/?([^/]*)/-);
                   5445: 	$file = $uri;
                   5446:     }
                   5447: 
                   5448:     if (!$udom || !$uname || !$file) {
                   5449: 	# unable to handle the uri
                   5450: 	return ();
                   5451:     }
                   5452: 
                   5453:     my ($result) = &dirlist($file,$udom,$uname,$dir);
                   5454:     my @stats = split('&', $result);
1.721     banghart 5455:     
1.712     albertel 5456:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   5457: 	shift(@stats); #filename is first
                   5458: 	return @stats;
                   5459:     }
                   5460:     return ();
                   5461: }
                   5462: 
1.26      www      5463: # -------------------------------------------------------- Value of a Condition
                   5464: 
1.713     albertel 5465: # gets the value of a specific preevaluated condition
                   5466: #    stored in the string  $env{user.state.<cid>}
                   5467: # or looks up a condition reference in the bighash and if if hasn't
                   5468: # already been evaluated recurses into docondval to get the value of
                   5469: # the condition, then memoizing it to 
                   5470: #   $env{user.state.<cid>.<condition>}
1.40      www      5471: sub directcondval {
                   5472:     my $number=shift;
1.620     albertel 5473:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 5474: 	&Apache::lonuserstate::evalstate();
                   5475:     }
1.713     albertel 5476:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   5477: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   5478:     } elsif ($number =~ /^_/) {
                   5479: 	my $sub_condition;
                   5480: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   5481: 		&GDBM_READER(),0640)) {
                   5482: 	    $sub_condition=$bighash{'conditions'.$number};
                   5483: 	    untie(%bighash);
                   5484: 	}
                   5485: 	my $value = &docondval($sub_condition);
                   5486: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
                   5487: 	return $value;
                   5488:     }
1.620     albertel 5489:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   5490:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      5491:     } else {
                   5492:        return 2;
                   5493:     }
                   5494: }
                   5495: 
1.713     albertel 5496: # get the collection of conditions for this resource
1.26      www      5497: sub condval {
                   5498:     my $condidx=shift;
1.54      www      5499:     my $allpathcond='';
1.713     albertel 5500:     foreach my $cond (split(/\|/,$condidx)) {
                   5501: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   5502: 	    $allpathcond.=
                   5503: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   5504: 	}
1.191     harris41 5505:     }
1.54      www      5506:     $allpathcond=~s/\|$//;
1.713     albertel 5507:     return &docondval($allpathcond);
                   5508: }
                   5509: 
                   5510: #evaluates an expression of conditions
                   5511: sub docondval {
                   5512:     my ($allpathcond) = @_;
                   5513:     my $result=0;
                   5514:     if ($env{'request.course.id'}
                   5515: 	&& defined($allpathcond)) {
                   5516: 	my $operand='|';
                   5517: 	my @stack;
                   5518: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   5519: 	    if ($chunk eq '(') {
                   5520: 		push @stack,($operand,$result);
                   5521: 	    } elsif ($chunk eq ')') {
                   5522: 		my $before=pop @stack;
                   5523: 		if (pop @stack eq '&') {
                   5524: 		    $result=$result>$before?$before:$result;
                   5525: 		} else {
                   5526: 		    $result=$result>$before?$result:$before;
                   5527: 		}
                   5528: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   5529: 		$operand=$chunk;
                   5530: 	    } else {
                   5531: 		my $new=directcondval($chunk);
                   5532: 		if ($operand eq '&') {
                   5533: 		    $result=$result>$new?$new:$result;
                   5534: 		} else {
                   5535: 		    $result=$result>$new?$result:$new;
                   5536: 		}
                   5537: 	    }
                   5538: 	}
1.26      www      5539:     }
                   5540:     return $result;
1.421     albertel 5541: }
                   5542: 
                   5543: # ---------------------------------------------------- Devalidate courseresdata
                   5544: 
                   5545: sub devalidatecourseresdata {
                   5546:     my ($coursenum,$coursedomain)=@_;
                   5547:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 5548:     &devalidate_cache_new('courseres',$hashid);
1.28      www      5549: }
                   5550: 
1.763     www      5551: 
1.200     www      5552: # --------------------------------------------------- Course Resourcedata Query
                   5553: 
1.624     albertel 5554: sub get_courseresdata {
                   5555:     my ($coursenum,$coursedomain)=@_;
1.200     www      5556:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   5557:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 5558:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 5559:     my %dumpreply;
1.417     albertel 5560:     unless (defined($cached)) {
1.624     albertel 5561: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 5562: 	$result=\%dumpreply;
1.251     albertel 5563: 	my ($tmp) = keys(%dumpreply);
                   5564: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 5565: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 5566: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   5567: 	    return $tmp;
1.416     albertel 5568: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 5569: 	    $result=undef;
1.599     albertel 5570: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 5571: 	}
                   5572:     }
1.624     albertel 5573:     return $result;
                   5574: }
                   5575: 
1.633     albertel 5576: sub devalidateuserresdata {
                   5577:     my ($uname,$udom)=@_;
                   5578:     my $hashid="$udom:$uname";
                   5579:     &devalidate_cache_new('userres',$hashid);
                   5580: }
                   5581: 
1.624     albertel 5582: sub get_userresdata {
                   5583:     my ($uname,$udom)=@_;
                   5584:     #most student don\'t have any data set, check if there is some data
                   5585:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   5586: 
                   5587:     my $hashid="$udom:$uname";
                   5588:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   5589:     if (!defined($cached)) {
                   5590: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   5591: 	$result=\%resourcedata;
                   5592: 	&do_cache_new('userres',$hashid,$result,600);
                   5593:     }
                   5594:     my ($tmp)=keys(%$result);
                   5595:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   5596: 	return $result;
                   5597:     }
                   5598:     #error 2 occurs when the .db doesn't exist
                   5599:     if ($tmp!~/error: 2 /) {
1.672     albertel 5600: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 5601: 		 " Trying to get resource data for ".
                   5602: 		 $uname." at ".$udom.": ".
                   5603: 		 $tmp."</font>");
                   5604:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 5605: 	#&EXT_cache_set($udom,$uname);
                   5606: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 5607: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 5608:     }
                   5609:     return $tmp;
                   5610: }
                   5611: 
                   5612: sub resdata {
                   5613:     my ($name,$domain,$type,@which)=@_;
                   5614:     my $result;
                   5615:     if ($type eq 'course') {
                   5616: 	$result=&get_courseresdata($name,$domain);
                   5617:     } elsif ($type eq 'user') {
                   5618: 	$result=&get_userresdata($name,$domain);
                   5619:     }
                   5620:     if (!ref($result)) { return $result; }    
1.251     albertel 5621:     foreach my $item (@which) {
1.417     albertel 5622: 	if (defined($result->{$item})) {
                   5623: 	    return $result->{$item};
1.251     albertel 5624: 	}
1.250     albertel 5625:     }
1.291     albertel 5626:     return undef;
1.200     www      5627: }
                   5628: 
1.379     matthew  5629: #
                   5630: # EXT resource caching routines
                   5631: #
                   5632: 
                   5633: sub clear_EXT_cache_status {
1.383     albertel 5634:     &delenv('cache.EXT.');
1.379     matthew  5635: }
                   5636: 
                   5637: sub EXT_cache_status {
                   5638:     my ($target_domain,$target_user) = @_;
1.383     albertel 5639:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 5640:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  5641:         # We know already the user has no data
                   5642:         return 1;
                   5643:     } else {
                   5644:         return 0;
                   5645:     }
                   5646: }
                   5647: 
                   5648: sub EXT_cache_set {
                   5649:     my ($target_domain,$target_user) = @_;
1.383     albertel 5650:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.633     albertel 5651:     #&appenv($cachename => time);
1.379     matthew  5652: }
                   5653: 
1.28      www      5654: # --------------------------------------------------------- Value of a Variable
1.58      www      5655: sub EXT {
1.715     albertel 5656: 
1.395     albertel 5657:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      5658:     unless ($varname) { return ''; }
1.218     albertel 5659:     #get real user name/domain, courseid and symb
                   5660:     my $courseid;
1.359     albertel 5661:     my $publicuser;
1.427     www      5662:     if ($symbparm) {
                   5663: 	$symbparm=&get_symb_from_alias($symbparm);
                   5664:     }
1.218     albertel 5665:     if (!($uname && $udom)) {
1.790     albertel 5666:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 5667:       if (!$symbparm) {	$symbparm=$cursymb; }
                   5668:     } else {
1.620     albertel 5669: 	$courseid=$env{'request.course.id'};
1.218     albertel 5670:     }
1.48      www      5671:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   5672:     my $rest;
1.320     albertel 5673:     if (defined($therest[0])) {
1.48      www      5674:        $rest=join('.',@therest);
                   5675:     } else {
                   5676:        $rest='';
                   5677:     }
1.320     albertel 5678: 
1.57      www      5679:     my $qualifierrest=$qualifier;
                   5680:     if ($rest) { $qualifierrest.='.'.$rest; }
                   5681:     my $spacequalifierrest=$space;
                   5682:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      5683:     if ($realm eq 'user') {
1.48      www      5684: # --------------------------------------------------------------- user.resource
                   5685: 	if ($space eq 'resource') {
1.651     albertel 5686: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   5687: 		  || defined($Apache::lonhomework::parsing_a_task))
                   5688: 		 &&
1.744     albertel 5689: 		 ($symbparm eq &symbread()) ) {	
                   5690: 		# if we are in the middle of processing the resource the
                   5691: 		# get the value we are planning on committing
                   5692:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   5693:                     return $Apache::lonhomework::results{$qualifierrest};
                   5694:                 } else {
                   5695:                     return $Apache::lonhomework::history{$qualifierrest};
                   5696:                 }
1.335     albertel 5697: 	    } else {
1.359     albertel 5698: 		my %restored;
1.620     albertel 5699: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 5700: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   5701: 		} else {
                   5702: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   5703: 		}
1.335     albertel 5704: 		return $restored{$qualifierrest};
                   5705: 	    }
1.48      www      5706: # ----------------------------------------------------------------- user.access
                   5707:         } elsif ($space eq 'access') {
1.218     albertel 5708: 	    # FIXME - not supporting calls for a specific user
1.48      www      5709:             return &allowed($qualifier,$rest);
                   5710: # ------------------------------------------ user.preferences, user.environment
                   5711:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 5712: 	    if (($uname eq $env{'user.name'}) &&
                   5713: 		($udom eq $env{'user.domain'})) {
                   5714: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 5715: 	    } else {
1.359     albertel 5716: 		my %returnhash;
                   5717: 		if (!$publicuser) {
                   5718: 		    %returnhash=&userenvironment($udom,$uname,
                   5719: 						 $qualifierrest);
                   5720: 		}
1.218     albertel 5721: 		return $returnhash{$qualifierrest};
                   5722: 	    }
1.48      www      5723: # ----------------------------------------------------------------- user.course
                   5724:         } elsif ($space eq 'course') {
1.218     albertel 5725: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 5726:             return $env{join('.',('request.course',$qualifier))};
1.48      www      5727: # ------------------------------------------------------------------- user.role
                   5728:         } elsif ($space eq 'role') {
1.218     albertel 5729: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 5730:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      5731:             if ($qualifier eq 'value') {
                   5732: 		return $role;
                   5733:             } elsif ($qualifier eq 'extent') {
                   5734:                 return $where;
                   5735:             }
                   5736: # ----------------------------------------------------------------- user.domain
                   5737:         } elsif ($space eq 'domain') {
1.218     albertel 5738:             return $udom;
1.48      www      5739: # ------------------------------------------------------------------- user.name
                   5740:         } elsif ($space eq 'name') {
1.218     albertel 5741:             return $uname;
1.48      www      5742: # ---------------------------------------------------- Any other user namespace
1.29      www      5743:         } else {
1.359     albertel 5744: 	    my %reply;
                   5745: 	    if (!$publicuser) {
                   5746: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   5747: 	    }
                   5748: 	    return $reply{$qualifierrest};
1.48      www      5749:         }
1.236     www      5750:     } elsif ($realm eq 'query') {
                   5751: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 5752:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   5753: 						[$spacequalifierrest]);
1.620     albertel 5754: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      5755:    } elsif ($realm eq 'request') {
1.48      www      5756: # ------------------------------------------------------------- request.browser
                   5757:         if ($space eq 'browser') {
1.430     www      5758: 	    if ($qualifier eq 'textremote') {
1.676     albertel 5759: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      5760: 		    return 1;
                   5761: 		} else {
                   5762: 		    return 0;
                   5763: 		}
                   5764: 	    } else {
1.620     albertel 5765: 		return $env{'browser.'.$qualifier};
1.430     www      5766: 	    }
1.57      www      5767: # ------------------------------------------------------------ request.filename
                   5768:         } else {
1.620     albertel 5769:             return $env{'request.'.$spacequalifierrest};
1.29      www      5770:         }
1.28      www      5771:     } elsif ($realm eq 'course') {
1.48      www      5772: # ---------------------------------------------------------- course.description
1.620     albertel 5773:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      5774:     } elsif ($realm eq 'resource') {
1.165     www      5775: 
1.620     albertel 5776: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 5777: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   5778: 	}
1.693     albertel 5779: 
                   5780: 	if ($space eq 'title') {
                   5781: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   5782: 	    return &gettitle($symbparm);
                   5783: 	}
                   5784: 	
                   5785: 	if ($space eq 'map') {
                   5786: 	    my ($map) = &decode_symb($symbparm);
                   5787: 	    return &symbread($map);
                   5788: 	}
                   5789: 
                   5790: 	my ($section, $group, @groups);
1.593     albertel 5791: 	my ($courselevelm,$courselevel);
1.539     albertel 5792: 	if ($symbparm && defined($courseid) && 
1.620     albertel 5793: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      5794: 
1.218     albertel 5795: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      5796: 
1.60      www      5797: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 5798: 	    my $symbp=$symbparm;
1.735     albertel 5799: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 5800: 
                   5801: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   5802: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   5803: 
1.620     albertel 5804: 	    if (($env{'user.name'} eq $uname) &&
                   5805: 		($env{'user.domain'} eq $udom)) {
                   5806: 		$section=$env{'request.course.sec'};
1.733     raeburn  5807:                 @groups = split(/:/,$env{'request.course.groups'});  
                   5808:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 5809: 	    } else {
1.539     albertel 5810: 		if (! defined($usection)) {
1.551     albertel 5811: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 5812: 		} else {
                   5813: 		    $section = $usection;
                   5814: 		}
1.733     raeburn  5815:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 5816: 	    }
                   5817: 
                   5818: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   5819: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   5820: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   5821: 
1.593     albertel 5822: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 5823: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 5824: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      5825: 
1.60      www      5826: # ----------------------------------------------------------- first, check user
1.624     albertel 5827: 
                   5828: 	    my $userreply=&resdata($uname,$udom,'user',
                   5829: 				       ($courselevelr,$courselevelm,
                   5830: 					$courselevel));
                   5831: 	    if (defined($userreply)) { return $userreply; }
1.95      www      5832: 
1.594     albertel 5833: # ------------------------------------------------ second, check some of course
1.684     raeburn  5834:             my $coursereply;
1.691     raeburn  5835:             if (@groups > 0) {
                   5836:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   5837:                                        $mapparm,$spacequalifierrest);
1.684     raeburn  5838:                 if (defined($coursereply)) { return $coursereply; }
                   5839:             }
1.96      www      5840: 
1.684     raeburn  5841: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.624     albertel 5842: 				     $env{'course.'.$courseid.'.domain'},
                   5843: 				     'course',
                   5844: 				     ($seclevelr,$seclevelm,$seclevel,
                   5845: 				      $courselevelr));
1.287     albertel 5846: 	    if (defined($coursereply)) { return $coursereply; }
1.200     www      5847: 
1.60      www      5848: # ------------------------------------------------------ third, check map parms
1.218     albertel 5849: 	    my %parmhash=();
                   5850: 	    my $thisparm='';
                   5851: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 5852: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 5853: 		    &GDBM_READER(),0640)) {
1.218     albertel 5854: 		$thisparm=$parmhash{$symbparm};
                   5855: 		untie(%parmhash);
                   5856: 	    }
                   5857: 	    if ($thisparm) { return $thisparm; }
                   5858: 	}
1.594     albertel 5859: # ------------------------------------------ fourth, look in resource metadata
1.71      www      5860: 
1.218     albertel 5861: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 5862: 	my $filename;
                   5863: 	if (!$symbparm) { $symbparm=&symbread(); }
                   5864: 	if ($symbparm) {
1.409     www      5865: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 5866: 	} else {
1.620     albertel 5867: 	    $filename=$env{'request.filename'};
1.282     albertel 5868: 	}
                   5869: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.288     albertel 5870: 	if (defined($metadata)) { return $metadata; }
1.282     albertel 5871: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.288     albertel 5872: 	if (defined($metadata)) { return $metadata; }
1.142     www      5873: 
1.594     albertel 5874: # ---------------------------------------------- fourth, look in rest pf course
1.593     albertel 5875: 	if ($symbparm && defined($courseid) && 
1.620     albertel 5876: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 5877: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   5878: 				     $env{'course.'.$courseid.'.domain'},
                   5879: 				     'course',
                   5880: 				     ($courselevelm,$courselevel));
1.593     albertel 5881: 	    if (defined($coursereply)) { return $coursereply; }
                   5882: 	}
1.145     www      5883: # ------------------------------------------------------------------ Cascade up
1.218     albertel 5884: 	unless ($space eq '0') {
1.336     albertel 5885: 	    my @parts=split(/_/,$space);
                   5886: 	    my $id=pop(@parts);
                   5887: 	    my $part=join('_',@parts);
                   5888: 	    if ($part eq '') { $part='0'; }
                   5889: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 5890: 				 $symbparm,$udom,$uname,$section,1);
1.337     albertel 5891: 	    if (defined($partgeneral)) { return $partgeneral; }
1.218     albertel 5892: 	}
1.395     albertel 5893: 	if ($recurse) { return undef; }
                   5894: 	my $pack_def=&packages_tab_default($filename,$varname);
                   5895: 	if (defined($pack_def)) { return $pack_def; }
1.71      www      5896: 
1.48      www      5897: # ---------------------------------------------------- Any other user namespace
                   5898:     } elsif ($realm eq 'environment') {
                   5899: # ----------------------------------------------------------------- environment
1.620     albertel 5900: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   5901: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 5902: 	} else {
1.770     albertel 5903: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   5904: 		return '';
                   5905: 	    }
1.219     albertel 5906: 	    my %returnhash=&userenvironment($udom,$uname,
                   5907: 					    $spacequalifierrest);
                   5908: 	    return $returnhash{$spacequalifierrest};
                   5909: 	}
1.28      www      5910:     } elsif ($realm eq 'system') {
1.48      www      5911: # ----------------------------------------------------------------- system.time
                   5912: 	if ($space eq 'time') {
                   5913: 	    return time;
                   5914:         }
1.696     albertel 5915:     } elsif ($realm eq 'server') {
                   5916: # ----------------------------------------------------------------- system.time
                   5917: 	if ($space eq 'name') {
                   5918: 	    return $ENV{'SERVER_NAME'};
                   5919:         }
1.28      www      5920:     }
1.48      www      5921:     return '';
1.61      www      5922: }
                   5923: 
1.691     raeburn  5924: sub check_group_parms {
                   5925:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   5926:     my @groupitems = ();
                   5927:     my $resultitem;
                   5928:     my @levels = ($symbparm,$mapparm,$what);
                   5929:     foreach my $group (@{$groups}) {
                   5930:         foreach my $level (@levels) {
                   5931:              my $item = $courseid.'.['.$group.'].'.$level;
                   5932:              push(@groupitems,$item);
                   5933:         }
                   5934:     }
                   5935:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   5936:                             $env{'course.'.$courseid.'.domain'},
                   5937:                                      'course',@groupitems);
                   5938:     return $coursereply;
                   5939: }
                   5940: 
                   5941: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  5942:     my ($courseid,@groups) = @_;
                   5943:     @groups = sort(@groups);
1.691     raeburn  5944:     return @groups;
                   5945: }
                   5946: 
1.395     albertel 5947: sub packages_tab_default {
                   5948:     my ($uri,$varname)=@_;
                   5949:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 5950: 
                   5951:     my (@extension,@specifics,$do_default);
                   5952:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 5953: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 5954: 	if ($pack_type eq 'default') {
                   5955: 	    $do_default=1;
                   5956: 	} elsif ($pack_type eq 'extension') {
                   5957: 	    push(@extension,[$package,$pack_type,$pack_part]);
                   5958: 	} else {
                   5959: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   5960: 	}
                   5961:     }
                   5962:     # first look for a package that matches the requested part id
                   5963:     foreach my $package (@specifics) {
                   5964: 	my (undef,$pack_type,$pack_part)=@{$package};
                   5965: 	next if ($pack_part ne $part);
                   5966: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   5967: 	    return $packagetab{"$pack_type&$name&default"};
                   5968: 	}
                   5969:     }
                   5970:     # look for any possible matching non extension_ package
                   5971:     foreach my $package (@specifics) {
                   5972: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 5973: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   5974: 	    return $packagetab{"$pack_type&$name&default"};
                   5975: 	}
1.585     albertel 5976: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 5977: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   5978: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 5979: 	}
                   5980:     }
1.738     albertel 5981:     # look for any posible extension_ match
                   5982:     foreach my $package (@extension) {
                   5983: 	my ($package,$pack_type)=@{$package};
                   5984: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   5985: 	    return $packagetab{"$pack_type&$name&default"};
                   5986: 	}
                   5987: 	if (defined($packagetab{$package."&$name&default"})) {
                   5988: 	    return $packagetab{$package."&$name&default"};
                   5989: 	}
                   5990:     }
                   5991:     # look for a global default setting
                   5992:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   5993: 	return $packagetab{"default&$name&default"};
                   5994:     }
1.395     albertel 5995:     return undef;
                   5996: }
                   5997: 
1.334     albertel 5998: sub add_prefix_and_part {
                   5999:     my ($prefix,$part)=@_;
                   6000:     my $keyroot;
                   6001:     if (defined($prefix) && $prefix !~ /^__/) {
                   6002: 	# prefix that has a part already
                   6003: 	$keyroot=$prefix;
                   6004:     } elsif (defined($prefix)) {
                   6005: 	# prefix that is missing a part
                   6006: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   6007:     } else {
                   6008: 	# no prefix at all
                   6009: 	if (defined($part)) { $keyroot='_'.$part; }
                   6010:     }
                   6011:     return $keyroot;
                   6012: }
                   6013: 
1.71      www      6014: # ---------------------------------------------------------------- Get metadata
                   6015: 
1.599     albertel 6016: my %metaentry;
1.71      www      6017: sub metadata {
1.176     www      6018:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      6019:     $uri=&declutter($uri);
1.288     albertel 6020:     # if it is a non metadata possible uri return quickly
1.529     albertel 6021:     if (($uri eq '') || 
                   6022: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 6023: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.423     albertel 6024:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
1.489     albertel 6025: 	($uri =~ m|home/[^/]+/public_html/|)) {
1.468     albertel 6026: 	return undef;
1.288     albertel 6027:     }
1.73      www      6028:     my $filename=$uri;
                   6029:     $uri=~s/\.meta$//;
1.172     www      6030: #
                   6031: # Is the metadata already cached?
1.177     www      6032: # Look at timestamp of caching
1.172     www      6033: # Everything is cached by the main uri, libraries are never directly cached
                   6034: #
1.428     albertel 6035:     if (!defined($liburi)) {
1.599     albertel 6036: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 6037: 	if (defined($cached)) { return $result->{':'.$what}; }
                   6038:     }
                   6039:     {
1.172     www      6040: #
                   6041: # Is this a recursive call for a library?
                   6042: #
1.599     albertel 6043: #	if (! exists($metacache{$uri})) {
                   6044: #	    $metacache{$uri}={};
                   6045: #	}
1.171     www      6046:         if ($liburi) {
                   6047: 	    $liburi=&declutter($liburi);
                   6048:             $filename=$liburi;
1.401     bowersj2 6049:         } else {
1.599     albertel 6050: 	    &devalidate_cache_new('meta',$uri);
                   6051: 	    undef(%metaentry);
1.401     bowersj2 6052: 	}
1.140     www      6053:         my %metathesekeys=();
1.73      www      6054:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 6055: 	my $metastring;
1.768     albertel 6056: 	if ($uri !~ m -^(editupload)/-) {
1.543     albertel 6057: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 6058: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 6059: 	    $metastring=&getfile($file);
1.489     albertel 6060: 	}
1.208     albertel 6061:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      6062:         my $token;
1.140     www      6063:         undef %metathesekeys;
1.71      www      6064:         while ($token=$parser->get_token) {
1.339     albertel 6065: 	    if ($token->[0] eq 'S') {
                   6066: 		if (defined($token->[2]->{'package'})) {
1.172     www      6067: #
                   6068: # This is a package - get package info
                   6069: #
1.339     albertel 6070: 		    my $package=$token->[2]->{'package'};
                   6071: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6072: 		    if (defined($token->[2]->{'id'})) { 
                   6073: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   6074: 		    }
1.599     albertel 6075: 		    if ($metaentry{':packages'}) {
                   6076: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 6077: 		    } else {
1.599     albertel 6078: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 6079: 		    }
1.736     albertel 6080: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 6081: 			my $part=$keyroot;
                   6082: 			$part=~s/^\_//;
1.736     albertel 6083: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   6084: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   6085: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 6086: 			    # ignore package.tab specified default values
                   6087:                             # here &package_tab_default() will fetch those
                   6088: 			    if ($subp eq 'default') { next; }
1.736     albertel 6089: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 6090: 			    my $unikey;
                   6091: 			    if ($pack =~ /_0$/) {
                   6092: 				$unikey='parameter_0_'.$name;
                   6093: 				$part=0;
                   6094: 			    } else {
                   6095: 				$unikey='parameter'.$keyroot.'_'.$name;
                   6096: 			    }
1.339     albertel 6097: 			    if ($subp eq 'display') {
                   6098: 				$value.=' [Part: '.$part.']';
                   6099: 			    }
1.599     albertel 6100: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 6101: 			    $metathesekeys{$unikey}=1;
1.599     albertel 6102: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6103: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 6104: 			    }
1.599     albertel 6105: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   6106: 				$metaentry{':'.$unikey}=
                   6107: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 6108: 			    }
1.339     albertel 6109: 			}
                   6110: 		    }
                   6111: 		} else {
1.172     www      6112: #
                   6113: # This is not a package - some other kind of start tag
1.339     albertel 6114: #
                   6115: 		    my $entry=$token->[1];
                   6116: 		    my $unikey;
                   6117: 		    if ($entry eq 'import') {
                   6118: 			$unikey='';
                   6119: 		    } else {
                   6120: 			$unikey=$entry;
                   6121: 		    }
                   6122: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6123: 
                   6124: 		    if (defined($token->[2]->{'id'})) { 
                   6125: 			$unikey.='_'.$token->[2]->{'id'}; 
                   6126: 		    }
1.175     www      6127: 
1.339     albertel 6128: 		    if ($entry eq 'import') {
1.175     www      6129: #
                   6130: # Importing a library here
1.339     albertel 6131: #
                   6132: 			if ($depthcount<20) {
                   6133: 			    my $location=$parser->get_text('/import');
                   6134: 			    my $dir=$filename;
                   6135: 			    $dir=~s|[^/]*$||;
                   6136: 			    $location=&filelocation($dir,$location);
1.736     albertel 6137: 			    my $metadata = 
                   6138: 				&metadata($uri,'keys', $location,$unikey,
                   6139: 					  $depthcount+1);
                   6140: 			    foreach my $meta (split(',',$metadata)) {
                   6141: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   6142: 				$metathesekeys{$meta}=1;
1.339     albertel 6143: 			    }
                   6144: 			}
                   6145: 		    } else { 
                   6146: 			
                   6147: 			if (defined($token->[2]->{'name'})) { 
                   6148: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   6149: 			}
                   6150: 			$metathesekeys{$unikey}=1;
1.736     albertel 6151: 			foreach my $param (@{$token->[3]}) {
                   6152: 			    $metaentry{':'.$unikey.'.'.$param} =
                   6153: 				$token->[2]->{$param};
1.339     albertel 6154: 			}
                   6155: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 6156: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 6157: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   6158: 		 # only ws inside the tag, and not in default, so use default
                   6159: 		 # as value
1.599     albertel 6160: 			    $metaentry{':'.$unikey}=$default;
1.339     albertel 6161: 			} else {
1.321     albertel 6162: 		  # either something interesting inside the tag or default
                   6163:                   # uninteresting
1.599     albertel 6164: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 6165: 			}
1.172     www      6166: # end of not-a-package not-a-library import
1.339     albertel 6167: 		    }
1.172     www      6168: # end of not-a-package start tag
1.339     albertel 6169: 		}
1.172     www      6170: # the next is the end of "start tag"
1.339     albertel 6171: 	    }
                   6172: 	}
1.483     albertel 6173: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.737     albertel 6174: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 6175: 	    #no specific packages #how's our extension
                   6176: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 6177: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 6178: 					 \%metathesekeys);
                   6179: 	}
1.599     albertel 6180: 	if (!exists($metaentry{':packages'})) {
1.737     albertel 6181: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 6182: 		#no specific packages well let's get default then
                   6183: 		if ($key!~/^default&/) { next; }
1.488     albertel 6184: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 6185: 					     \%metathesekeys);
                   6186: 	    }
                   6187: 	}
1.338     www      6188: # are there custom rights to evaluate
1.599     albertel 6189: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 6190: 
1.338     www      6191:     #
                   6192:     # Importing a rights file here
1.339     albertel 6193:     #
                   6194: 	    unless ($depthcount) {
1.599     albertel 6195: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 6196: 		my $dir=$filename;
                   6197: 		$dir=~s|[^/]*$||;
                   6198: 		$location=&filelocation($dir,$location);
1.736     albertel 6199: 		my $rights_metadata =
                   6200: 		    &metadata($uri,'keys',$location,'_rights',
                   6201: 			      $depthcount+1);
                   6202: 		foreach my $rights (split(',',$rights_metadata)) {
                   6203: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   6204: 		    $metathesekeys{$rights}=1;
1.339     albertel 6205: 		}
                   6206: 	    }
                   6207: 	}
1.737     albertel 6208: 	# uniqifiy package listing
                   6209: 	my %seen;
                   6210: 	my @uniq_packages =
                   6211: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   6212: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   6213: 
                   6214: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 6215: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   6216: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.699     albertel 6217: 	&do_cache_new('meta',$uri,\%metaentry,60*60);
1.177     www      6218: # this is the end of "was not already recently cached
1.71      www      6219:     }
1.599     albertel 6220:     return $metaentry{':'.$what};
1.261     albertel 6221: }
                   6222: 
1.488     albertel 6223: sub metadata_create_package_def {
1.483     albertel 6224:     my ($uri,$key,$package,$metathesekeys)=@_;
                   6225:     my ($pack,$name,$subp)=split(/\&/,$key);
                   6226:     if ($subp eq 'default') { next; }
                   6227:     
1.599     albertel 6228:     if (defined($metaentry{':packages'})) {
                   6229: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 6230:     } else {
1.599     albertel 6231: 	$metaentry{':packages'}=$package;
1.483     albertel 6232:     }
                   6233:     my $value=$packagetab{$key};
                   6234:     my $unikey;
                   6235:     $unikey='parameter_0_'.$name;
1.599     albertel 6236:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 6237:     $$metathesekeys{$unikey}=1;
1.599     albertel 6238:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6239: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 6240:     }
1.599     albertel 6241:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   6242: 	$metaentry{':'.$unikey}=
                   6243: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 6244:     }
                   6245: }
                   6246: 
1.261     albertel 6247: sub metadata_generate_part0 {
                   6248:     my ($metadata,$metacache,$uri) = @_;
                   6249:     my %allnames;
1.737     albertel 6250:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 6251: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 6252: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   6253: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 6254: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 6255: 	    $allnames{$name}=$part;
                   6256: 	  }
                   6257: 	}
                   6258:     }
                   6259:     foreach my $name (keys(%allnames)) {
                   6260:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 6261:       my $key=":parameter_0_$name";
1.261     albertel 6262:       $$metacache{"$key.part"}='0';
                   6263:       $$metacache{"$key.name"}=$name;
1.428     albertel 6264:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 6265: 					   $allnames{$name}.'_'.$name.
                   6266: 					   '.type'};
1.428     albertel 6267:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 6268: 			     '.display'};
1.644     www      6269:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 6270:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 6271:       $$metacache{"$key.display"}=$olddis;
                   6272:     }
1.71      www      6273: }
                   6274: 
1.764     albertel 6275: # ------------------------------------------------------ Devalidate title cache
                   6276: 
                   6277: sub devalidate_title_cache {
                   6278:     my ($url)=@_;
                   6279:     if (!$env{'request.course.id'}) { return; }
                   6280:     my $symb=&symbread($url);
                   6281:     if (!$symb) { return; }
                   6282:     my $key=$env{'request.course.id'}."\0".$symb;
                   6283:     &devalidate_cache_new('title',$key);
                   6284: }
                   6285: 
1.301     www      6286: # ------------------------------------------------- Get the title of a resource
                   6287: 
                   6288: sub gettitle {
                   6289:     my $urlsymb=shift;
                   6290:     my $symb=&symbread($urlsymb);
1.534     albertel 6291:     if ($symb) {
1.620     albertel 6292: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 6293: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 6294: 	if (defined($cached)) { 
                   6295: 	    return $result;
                   6296: 	}
1.534     albertel 6297: 	my ($map,$resid,$url)=&decode_symb($symb);
                   6298: 	my $title='';
                   6299: 	my %bighash;
1.620     albertel 6300: 	if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.534     albertel 6301: 		&GDBM_READER(),0640)) {
                   6302: 	    my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   6303: 	    $title=$bighash{'title_'.$mapid.'.'.$resid};
                   6304: 	    untie %bighash;
                   6305: 	}
                   6306: 	$title=~s/\&colon\;/\:/gs;
                   6307: 	if ($title) {
1.599     albertel 6308: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 6309: 	}
                   6310: 	$urlsymb=$url;
                   6311:     }
                   6312:     my $title=&metadata($urlsymb,'title');
                   6313:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   6314:     return $title;
1.301     www      6315: }
1.613     albertel 6316: 
1.614     albertel 6317: sub get_slot {
                   6318:     my ($which,$cnum,$cdom)=@_;
                   6319:     if (!$cnum || !$cdom) {
1.790     albertel 6320: 	(undef,my $courseid)=&whichuser();
1.620     albertel 6321: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   6322: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 6323:     }
1.703     albertel 6324:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   6325:     my %slotinfo;
                   6326:     if (exists($remembered{$key})) {
                   6327: 	$slotinfo{$which} = $remembered{$key};
                   6328:     } else {
                   6329: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   6330: 	&Apache::lonhomework::showhash(%slotinfo);
                   6331: 	my ($tmp)=keys(%slotinfo);
                   6332: 	if ($tmp=~/^error:/) { return (); }
                   6333: 	$remembered{$key} = $slotinfo{$which};
                   6334:     }
1.616     albertel 6335:     if (ref($slotinfo{$which}) eq 'HASH') {
                   6336: 	return %{$slotinfo{$which}};
                   6337:     }
                   6338:     return $slotinfo{$which};
1.614     albertel 6339: }
1.31      www      6340: # ------------------------------------------------- Update symbolic store links
                   6341: 
                   6342: sub symblist {
                   6343:     my ($mapname,%newhash)=@_;
1.438     www      6344:     $mapname=&deversion(&declutter($mapname));
1.31      www      6345:     my %hash;
1.620     albertel 6346:     if (($env{'request.course.fn'}) && (%newhash)) {
                   6347:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6348:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 6349: 	    foreach my $url (keys %newhash) {
                   6350: 		next if ($url eq 'last_known'
                   6351: 			 && $env{'form.no_update_last_known'});
                   6352: 		$hash{declutter($url)}=&encode_symb($mapname,
                   6353: 						    $newhash{$url}->[1],
                   6354: 						    $newhash{$url}->[0]);
1.191     harris41 6355:             }
1.31      www      6356:             if (untie(%hash)) {
                   6357: 		return 'ok';
                   6358:             }
                   6359:         }
                   6360:     }
                   6361:     return 'error';
1.212     www      6362: }
                   6363: 
                   6364: # --------------------------------------------------------------- Verify a symb
                   6365: 
                   6366: sub symbverify {
1.510     www      6367:     my ($symb,$thisurl)=@_;
                   6368:     my $thisfn=$thisurl;
1.439     www      6369:     $thisfn=&declutter($thisfn);
1.215     www      6370: # direct jump to resource in page or to a sequence - will construct own symbs
                   6371:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   6372: # check URL part
1.409     www      6373:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      6374: 
1.431     www      6375:     unless ($url eq $thisfn) { return 0; }
1.213     www      6376: 
1.216     www      6377:     $symb=&symbclean($symb);
1.510     www      6378:     $thisurl=&deversion($thisurl);
1.439     www      6379:     $thisfn=&deversion($thisfn);
1.213     www      6380: 
                   6381:     my %bighash;
                   6382:     my $okay=0;
1.431     www      6383: 
1.620     albertel 6384:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6385:                             &GDBM_READER(),0640)) {
1.510     www      6386:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      6387:         unless ($ids) { 
1.510     www      6388:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      6389:         }
                   6390:         if ($ids) {
                   6391: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 6392: 	    foreach my $id (split(/\,/,$ids)) {
                   6393: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      6394:                if (
                   6395:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   6396:    eq $symb) { 
1.620     albertel 6397: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 6398: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 6399: 		       $okay=1; 
                   6400: 		   }
                   6401: 	       }
1.216     www      6402: 	   }
                   6403:         }
1.213     www      6404: 	untie(%bighash);
                   6405:     }
                   6406:     return $okay;
1.31      www      6407: }
                   6408: 
1.210     www      6409: # --------------------------------------------------------------- Clean-up symb
                   6410: 
                   6411: sub symbclean {
                   6412:     my $symb=shift;
1.568     albertel 6413:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      6414: # remove version from map
                   6415:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      6416: 
1.210     www      6417: # remove version from URL
                   6418:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      6419: 
1.507     www      6420: # remove wrapper
                   6421: 
1.510     www      6422:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 6423:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      6424:     return $symb;
1.409     www      6425: }
                   6426: 
                   6427: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 6428: 
                   6429: sub encode_symb {
                   6430:     my ($map,$resid,$url)=@_;
                   6431:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   6432: }
1.409     www      6433: 
                   6434: sub decode_symb {
1.568     albertel 6435:     my $symb=shift;
                   6436:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   6437:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      6438:     return (&fixversion($map),$resid,&fixversion($url));
                   6439: }
                   6440: 
                   6441: sub fixversion {
                   6442:     my $fn=shift;
1.609     banghart 6443:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      6444:     my %bighash;
                   6445:     my $uri=&clutter($fn);
1.620     albertel 6446:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      6447: # is this cached?
1.599     albertel 6448:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      6449:     if (defined($cached)) { return $result; }
                   6450: # unfortunately not cached, or expired
1.620     albertel 6451:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      6452: 	    &GDBM_READER(),0640)) {
                   6453:  	if ($bighash{'version_'.$uri}) {
                   6454:  	    my $version=$bighash{'version_'.$uri};
1.444     www      6455:  	    unless (($version eq 'mostrecent') || 
                   6456: 		    ($version==&getversion($uri))) {
1.440     www      6457:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   6458:  	    }
                   6459:  	}
                   6460:  	untie %bighash;
1.413     www      6461:     }
1.599     albertel 6462:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      6463: }
                   6464: 
                   6465: sub deversion {
                   6466:     my $url=shift;
                   6467:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   6468:     return $url;
1.210     www      6469: }
                   6470: 
1.31      www      6471: # ------------------------------------------------------ Return symb list entry
                   6472: 
                   6473: sub symbread {
1.249     www      6474:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 6475:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 6476:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      6477: # no filename provided? try from environment
1.44      www      6478:     unless ($thisfn) {
1.620     albertel 6479:         if ($env{'request.symb'}) {
                   6480: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 6481: 	}
1.620     albertel 6482: 	$thisfn=$env{'request.filename'};
1.44      www      6483:     }
1.569     albertel 6484:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      6485: # is that filename actually a symb? Verify, clean, and return
                   6486:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 6487: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 6488: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 6489: 	}
1.242     www      6490:     }
1.44      www      6491:     $thisfn=declutter($thisfn);
1.31      www      6492:     my %hash;
1.37      www      6493:     my %bighash;
                   6494:     my $syval='';
1.620     albertel 6495:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  6496:         my $targetfn = $thisfn;
1.609     banghart 6497:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  6498:             $targetfn = 'adm/wrapper/'.$thisfn;
                   6499:         }
1.687     albertel 6500: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   6501: 	    $targetfn=$1;
                   6502: 	}
1.620     albertel 6503:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6504:                       &GDBM_READER(),0640)) {
1.481     raeburn  6505: 	    $syval=$hash{$targetfn};
1.37      www      6506:             untie(%hash);
                   6507:         }
                   6508: # ---------------------------------------------------------- There was an entry
                   6509:         if ($syval) {
1.601     albertel 6510: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 6511: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.601     albertel 6512: 		    #&appenv('request.ambiguous' => $thisfn);
1.620     albertel 6513: 		    #return $env{$cache_str}='';
1.601     albertel 6514: 		#}    
                   6515: 		#$syval.=$1;
                   6516: 	    #}
1.37      www      6517:         } else {
                   6518: # ------------------------------------------------------- Was not in symb table
1.620     albertel 6519:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6520:                             &GDBM_READER(),0640)) {
1.37      www      6521: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      6522:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      6523:               unless ($ids) { 
                   6524:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      6525:               }
                   6526:               unless ($ids) {
                   6527: # alias?
                   6528: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      6529:               }
1.37      www      6530:               if ($ids) {
                   6531: # ------------------------------------------------------------------- Has ID(s)
                   6532:                  my @possibilities=split(/\,/,$ids);
1.39      www      6533:                  if ($#possibilities==0) {
                   6534: # ----------------------------------------------- There is only one possibility
1.37      www      6535: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 6536: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6537: 						    $resid,$thisfn);
1.249     www      6538:                  } elsif (!$donotrecurse) {
1.39      www      6539: # ------------------------------------------ There is more than one possibility
                   6540:                      my $realpossible=0;
1.800     albertel 6541:                      foreach my $id (@possibilities) {
                   6542: 			 my $file=$bighash{'src_'.$id};
1.39      www      6543:                          if (&allowed('bre',$file)) {
1.800     albertel 6544:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      6545:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   6546: 				$realpossible++;
1.626     albertel 6547:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6548: 						    $resid,$thisfn);
1.39      www      6549:                             }
                   6550: 			 }
1.191     harris41 6551:                      }
1.39      www      6552: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      6553:                  } else {
                   6554:                      $syval='';
1.37      www      6555:                  }
                   6556: 	      }
                   6557:               untie(%bighash)
1.481     raeburn  6558:            }
1.31      www      6559:         }
1.62      www      6560:         if ($syval) {
1.620     albertel 6561: 	    return $env{$cache_str}=$syval;
1.62      www      6562:         }
1.31      www      6563:     }
1.44      www      6564:     &appenv('request.ambiguous' => $thisfn);
1.620     albertel 6565:     return $env{$cache_str}='';
1.31      www      6566: }
                   6567: 
                   6568: # ---------------------------------------------------------- Return random seed
                   6569: 
1.32      www      6570: sub numval {
                   6571:     my $txt=shift;
                   6572:     $txt=~tr/A-J/0-9/;
                   6573:     $txt=~tr/a-j/0-9/;
                   6574:     $txt=~tr/K-T/0-9/;
                   6575:     $txt=~tr/k-t/0-9/;
                   6576:     $txt=~tr/U-Z/0-5/;
                   6577:     $txt=~tr/u-z/0-5/;
                   6578:     $txt=~s/\D//g;
1.564     albertel 6579:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      6580:     return int($txt);
1.368     albertel 6581: }
                   6582: 
1.484     albertel 6583: sub numval2 {
                   6584:     my $txt=shift;
                   6585:     $txt=~tr/A-J/0-9/;
                   6586:     $txt=~tr/a-j/0-9/;
                   6587:     $txt=~tr/K-T/0-9/;
                   6588:     $txt=~tr/k-t/0-9/;
                   6589:     $txt=~tr/U-Z/0-5/;
                   6590:     $txt=~tr/u-z/0-5/;
                   6591:     $txt=~s/\D//g;
                   6592:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   6593:     my $total;
                   6594:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 6595:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 6596:     return int($total);
                   6597: }
                   6598: 
1.575     albertel 6599: sub numval3 {
                   6600:     use integer;
                   6601:     my $txt=shift;
                   6602:     $txt=~tr/A-J/0-9/;
                   6603:     $txt=~tr/a-j/0-9/;
                   6604:     $txt=~tr/K-T/0-9/;
                   6605:     $txt=~tr/k-t/0-9/;
                   6606:     $txt=~tr/U-Z/0-5/;
                   6607:     $txt=~tr/u-z/0-5/;
                   6608:     $txt=~s/\D//g;
                   6609:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   6610:     my $total;
                   6611:     foreach my $val (@txts) { $total+=$val; }
                   6612:     if ($_64bit) { $total=(($total<<32)>>32); }
                   6613:     return $total;
                   6614: }
                   6615: 
1.675     albertel 6616: sub digest {
                   6617:     my ($data)=@_;
                   6618:     my $digest=&Digest::MD5::md5($data);
                   6619:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   6620:     my ($e,$f);
                   6621:     {
                   6622:         use integer;
                   6623:         $e=($a+$b);
                   6624:         $f=($c+$d);
                   6625:         if ($_64bit) {
                   6626:             $e=(($e<<32)>>32);
                   6627:             $f=(($f<<32)>>32);
                   6628:         }
                   6629:     }
                   6630:     if (wantarray) {
                   6631: 	return ($e,$f);
                   6632:     } else {
                   6633: 	my $g;
                   6634: 	{
                   6635: 	    use integer;
                   6636: 	    $g=($e+$f);
                   6637: 	    if ($_64bit) {
                   6638: 		$g=(($g<<32)>>32);
                   6639: 	    }
                   6640: 	}
                   6641: 	return $g;
                   6642:     }
                   6643: }
                   6644: 
1.368     albertel 6645: sub latest_rnd_algorithm_id {
1.675     albertel 6646:     return '64bit5';
1.366     albertel 6647: }
1.32      www      6648: 
1.503     albertel 6649: sub get_rand_alg {
                   6650:     my ($courseid)=@_;
1.790     albertel 6651:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 6652:     if ($courseid) {
1.620     albertel 6653: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 6654:     }
                   6655:     return &latest_rnd_algorithm_id();
                   6656: }
                   6657: 
1.562     albertel 6658: sub validCODE {
                   6659:     my ($CODE)=@_;
                   6660:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   6661:     return 0;
                   6662: }
                   6663: 
1.491     albertel 6664: sub getCODE {
1.620     albertel 6665:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 6666:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   6667: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   6668: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 6669: 	return $Apache::lonhomework::history{'resource.CODE'};
                   6670:     }
                   6671:     return undef;
                   6672: }
                   6673: 
1.31      www      6674: sub rndseed {
1.155     albertel 6675:     my ($symb,$courseid,$domain,$username)=@_;
1.366     albertel 6676: 
1.790     albertel 6677:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.155     albertel 6678:     if (!$symb) {
1.366     albertel 6679: 	unless ($symb=$wsymb) { return time; }
                   6680:     }
                   6681:     if (!$courseid) { $courseid=$wcourseid; }
                   6682:     if (!$domain) { $domain=$wdomain; }
                   6683:     if (!$username) { $username=$wusername }
1.503     albertel 6684:     my $which=&get_rand_alg();
1.803     albertel 6685: 
1.491     albertel 6686:     if (defined(&getCODE())) {
1.675     albertel 6687: 	if ($which eq '64bit5') {
                   6688: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   6689: 	} elsif ($which eq '64bit4') {
1.575     albertel 6690: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   6691: 	} else {
                   6692: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   6693: 	}
1.675     albertel 6694:     } elsif ($which eq '64bit5') {
                   6695: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 6696:     } elsif ($which eq '64bit4') {
                   6697: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 6698:     } elsif ($which eq '64bit3') {
                   6699: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 6700:     } elsif ($which eq '64bit2') {
                   6701: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 6702:     } elsif ($which eq '64bit') {
                   6703: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   6704:     }
                   6705:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   6706: }
                   6707: 
                   6708: sub rndseed_32bit {
                   6709:     my ($symb,$courseid,$domain,$username)=@_;
                   6710:     {
                   6711: 	use integer;
                   6712: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   6713: 	my $symbseed=numval($symb) << 22;
                   6714: 	my $namechck=unpack("%32C*",$username) << 17;
                   6715: 	my $nameseed=numval($username) << 12;
                   6716: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   6717: 	my $courseseed=unpack("%32C*",$courseid);
                   6718: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 6719: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6720: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 6721: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 6722: 	return $num;
                   6723:     }
                   6724: }
                   6725: 
                   6726: sub rndseed_64bit {
                   6727:     my ($symb,$courseid,$domain,$username)=@_;
                   6728:     {
                   6729: 	use integer;
                   6730: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   6731: 	my $symbseed=numval($symb) << 10;
                   6732: 	my $namechck=unpack("%32S*",$username);
                   6733: 	
                   6734: 	my $nameseed=numval($username) << 21;
                   6735: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   6736: 	my $courseseed=unpack("%32S*",$courseid);
                   6737: 	
                   6738: 	my $num1=$symbchck+$symbseed+$namechck;
                   6739: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6740: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6741: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 6742: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 6743: 	return "$num1,$num2";
1.155     albertel 6744:     }
1.366     albertel 6745: }
                   6746: 
1.443     albertel 6747: sub rndseed_64bit2 {
                   6748:     my ($symb,$courseid,$domain,$username)=@_;
                   6749:     {
                   6750: 	use integer;
                   6751: 	# strings need to be an even # of cahracters long, it it is odd the
                   6752:         # last characters gets thrown away
                   6753: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6754: 	my $symbseed=numval($symb) << 10;
                   6755: 	my $namechck=unpack("%32S*",$username.' ');
                   6756: 	
                   6757: 	my $nameseed=numval($username) << 21;
1.501     albertel 6758: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6759: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6760: 	
                   6761: 	my $num1=$symbchck+$symbseed+$namechck;
                   6762: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6763: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6764: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 6765: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 6766: 	return "$num1,$num2";
                   6767:     }
                   6768: }
                   6769: 
                   6770: sub rndseed_64bit3 {
                   6771:     my ($symb,$courseid,$domain,$username)=@_;
                   6772:     {
                   6773: 	use integer;
                   6774: 	# strings need to be an even # of cahracters long, it it is odd the
                   6775:         # last characters gets thrown away
                   6776: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6777: 	my $symbseed=numval2($symb) << 10;
                   6778: 	my $namechck=unpack("%32S*",$username.' ');
                   6779: 	
                   6780: 	my $nameseed=numval2($username) << 21;
1.443     albertel 6781: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6782: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6783: 	
                   6784: 	my $num1=$symbchck+$symbseed+$namechck;
                   6785: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6786: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6787: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 6788: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6789: 	
1.503     albertel 6790: 	return "$num1:$num2";
1.443     albertel 6791:     }
                   6792: }
                   6793: 
1.575     albertel 6794: sub rndseed_64bit4 {
                   6795:     my ($symb,$courseid,$domain,$username)=@_;
                   6796:     {
                   6797: 	use integer;
                   6798: 	# strings need to be an even # of cahracters long, it it is odd the
                   6799:         # last characters gets thrown away
                   6800: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6801: 	my $symbseed=numval3($symb) << 10;
                   6802: 	my $namechck=unpack("%32S*",$username.' ');
                   6803: 	
                   6804: 	my $nameseed=numval3($username) << 21;
                   6805: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6806: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6807: 	
                   6808: 	my $num1=$symbchck+$symbseed+$namechck;
                   6809: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6810: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6811: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 6812: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6813: 	
                   6814: 	return "$num1:$num2";
                   6815:     }
                   6816: }
                   6817: 
1.675     albertel 6818: sub rndseed_64bit5 {
                   6819:     my ($symb,$courseid,$domain,$username)=@_;
                   6820:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   6821:     return "$num1:$num2";
                   6822: }
                   6823: 
1.366     albertel 6824: sub rndseed_CODE_64bit {
                   6825:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 6826:     {
1.366     albertel 6827: 	use integer;
1.443     albertel 6828: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 6829: 	my $symbseed=numval2($symb);
1.491     albertel 6830: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   6831: 	my $CODEseed=numval(&getCODE());
1.443     albertel 6832: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 6833: 	my $num1=$symbseed+$CODEchck;
                   6834: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 6835: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   6836: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 6837: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   6838: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 6839: 	return "$num1:$num2";
1.366     albertel 6840:     }
                   6841: }
                   6842: 
1.575     albertel 6843: sub rndseed_CODE_64bit4 {
                   6844:     my ($symb,$courseid,$domain,$username)=@_;
                   6845:     {
                   6846: 	use integer;
                   6847: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   6848: 	my $symbseed=numval3($symb);
                   6849: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   6850: 	my $CODEseed=numval3(&getCODE());
                   6851: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6852: 	my $num1=$symbseed+$CODEchck;
                   6853: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 6854: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   6855: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 6856: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   6857: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   6858: 	return "$num1:$num2";
                   6859:     }
                   6860: }
                   6861: 
1.675     albertel 6862: sub rndseed_CODE_64bit5 {
                   6863:     my ($symb,$courseid,$domain,$username)=@_;
                   6864:     my $code = &getCODE();
                   6865:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   6866:     return "$num1:$num2";
                   6867: }
                   6868: 
1.366     albertel 6869: sub setup_random_from_rndseed {
                   6870:     my ($rndseed)=@_;
1.503     albertel 6871:     if ($rndseed =~/([,:])/) {
                   6872: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 6873: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   6874:     } else {
                   6875: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 6876:     }
1.36      albertel 6877: }
                   6878: 
1.474     albertel 6879: sub latest_receipt_algorithm_id {
                   6880:     return 'receipt2';
                   6881: }
                   6882: 
1.480     www      6883: sub recunique {
                   6884:     my $fucourseid=shift;
                   6885:     my $unique;
1.620     albertel 6886:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   6887: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      6888:     } else {
                   6889: 	$unique=$perlvar{'lonReceipt'};
                   6890:     }
                   6891:     return unpack("%32C*",$unique);
                   6892: }
                   6893: 
                   6894: sub recprefix {
                   6895:     my $fucourseid=shift;
                   6896:     my $prefix;
1.620     albertel 6897:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   6898: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      6899:     } else {
                   6900: 	$prefix=$perlvar{'lonHostID'};
                   6901:     }
                   6902:     return unpack("%32C*",$prefix);
                   6903: }
                   6904: 
1.76      www      6905: sub ireceipt {
1.474     albertel 6906:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.76      www      6907:     my $cuname=unpack("%32C*",$funame);
                   6908:     my $cudom=unpack("%32C*",$fudom);
                   6909:     my $cucourseid=unpack("%32C*",$fucourseid);
                   6910:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      6911:     my $cunique=&recunique($fucourseid);
1.474     albertel 6912:     my $cpart=unpack("%32S*",$part);
1.480     www      6913:     my $return =&recprefix($fucourseid).'-';
1.620     albertel 6914:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   6915: 	$env{'request.state'} eq 'construct') {
1.790     albertel 6916: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 6917: 			       
                   6918: 	$return.= ($cunique%$cuname+
                   6919: 		   $cunique%$cudom+
                   6920: 		   $cusymb%$cuname+
                   6921: 		   $cusymb%$cudom+
                   6922: 		   $cucourseid%$cuname+
                   6923: 		   $cucourseid%$cudom+
                   6924: 		   $cpart%$cuname+
                   6925: 		   $cpart%$cudom);
                   6926:     } else {
                   6927: 	$return.= ($cunique%$cuname+
                   6928: 		   $cunique%$cudom+
                   6929: 		   $cusymb%$cuname+
                   6930: 		   $cusymb%$cudom+
                   6931: 		   $cucourseid%$cuname+
                   6932: 		   $cucourseid%$cudom);
                   6933:     }
                   6934:     return $return;
1.76      www      6935: }
                   6936: 
                   6937: sub receipt {
1.474     albertel 6938:     my ($part)=@_;
1.790     albertel 6939:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 6940:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      6941: }
1.260     ng       6942: 
1.790     albertel 6943: sub whichuser {
                   6944:     my ($passedsymb)=@_;
                   6945:     my ($symb,$courseid,$domain,$name,$publicuser);
                   6946:     if (defined($env{'form.grade_symb'})) {
                   6947: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   6948: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   6949: 	if (!$allowed &&
                   6950: 	    exists($env{'request.course.sec'}) &&
                   6951: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   6952: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   6953: 			      '/'.$env{'request.course.sec'});
                   6954: 	}
                   6955: 	if ($allowed) {
                   6956: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   6957: 	    $courseid=$tmp_courseid;
                   6958: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   6959: 	    ($name)=&get_env_multiple('form.grade_username');
                   6960: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   6961: 	}
                   6962:     }
                   6963:     if (!$passedsymb) {
                   6964: 	$symb=&symbread();
                   6965:     } else {
                   6966: 	$symb=$passedsymb;
                   6967:     }
                   6968:     $courseid=$env{'request.course.id'};
                   6969:     $domain=$env{'user.domain'};
                   6970:     $name=$env{'user.name'};
                   6971:     if ($name eq 'public' && $domain eq 'public') {
                   6972: 	if (!defined($env{'form.username'})) {
                   6973: 	    $env{'form.username'}.=time.rand(10000000);
                   6974: 	}
                   6975: 	$name.=$env{'form.username'};
                   6976:     }
                   6977:     return ($symb,$courseid,$domain,$name,$publicuser);
                   6978: 
                   6979: }
                   6980: 
1.36      albertel 6981: # ------------------------------------------------------------ Serves up a file
1.472     albertel 6982: # returns either the contents of the file or 
                   6983: # -1 if the file doesn't exist
1.481     raeburn  6984: #
                   6985: # if the target is a file that was uploaded via DOCS, 
                   6986: # a check will be made to see if a current copy exists on the local server,
                   6987: # if it does this will be served, otherwise a copy will be retrieved from
                   6988: # the home server for the course and stored in /home/httpd/html/userfiles on
                   6989: # the local server.   
1.472     albertel 6990: 
1.36      albertel 6991: sub getfile {
1.538     albertel 6992:     my ($file) = @_;
1.609     banghart 6993:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 6994:     &repcopy($file);
                   6995:     return &readfile($file);
                   6996: }
                   6997: 
                   6998: sub repcopy_userfile {
                   6999:     my ($file)=@_;
1.609     banghart 7000:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 7001:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 7002:     my ($cdom,$cnum,$filename) = 
                   7003: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+([^/]+)/+([^/]+)/+(.*)|);
                   7004:     my ($info,$rtncode);
                   7005:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   7006:     if (-e "$file") {
                   7007: 	my @fileinfo = stat($file);
                   7008: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 7009: 	if ($lwpresp ne 'ok') {
                   7010: 	    if ($rtncode eq '404') {
1.538     albertel 7011: 		unlink($file);
1.482     albertel 7012: 	    }
1.517     albertel 7013: 	    #my $ua=new LWP::UserAgent;
1.538     albertel 7014: 	    #my $request=new HTTP::Request('GET',&tokenwrapper($uri));
1.517     albertel 7015: 	    #my $response=$ua->request($request);
                   7016: 	    #if ($response->is_success()) {
                   7017: 	#	return $response->content;
                   7018: 	#    } else {
                   7019: 	#	return -1;
                   7020: 	#    }
1.482     albertel 7021: 	    return -1;
                   7022: 	}
                   7023: 	if ($info < $fileinfo[9]) {
1.607     raeburn  7024: 	    return 'ok';
1.482     albertel 7025: 	}
                   7026: 	$info = '';
1.538     albertel 7027: 	$lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 7028: 	if ($lwpresp ne 'ok') {
                   7029: 	    return -1;
                   7030: 	}
                   7031:     } else {
1.538     albertel 7032: 	my $lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 7033: 	if ($lwpresp ne 'ok') {
1.517     albertel 7034: 	    my $ua=new LWP::UserAgent;
1.538     albertel 7035: 	    my $request=new HTTP::Request('GET',&tokenwrapper($uri));
1.517     albertel 7036: 	    my $response=$ua->request($request);
                   7037: 	    if ($response->is_success()) {
1.538     albertel 7038: 		$info=$response->content;
1.517     albertel 7039: 	    } else {
                   7040: 		return -1;
                   7041: 	    }
1.482     albertel 7042: 	}
                   7043: 	my @parts = ($cdom,$cnum); 
                   7044: 	if ($filename =~ m|^(.+)/[^/]+$|) {
                   7045: 	    push @parts, split(/\//,$1);
1.518     albertel 7046: 	}
1.538     albertel 7047: 	my $path = $perlvar{'lonDocRoot'}.'/userfiles';
1.482     albertel 7048: 	foreach my $part (@parts) {
                   7049: 	    $path .= '/'.$part;
                   7050: 	    if (!-e $path) {
                   7051: 		mkdir($path,0770);
                   7052: 	    }
                   7053: 	}
                   7054:     }
1.538     albertel 7055:     open(FILE,">$file");
1.482     albertel 7056:     print FILE $info;
                   7057:     close(FILE);
1.607     raeburn  7058:     return 'ok';
1.481     raeburn  7059: }
                   7060: 
1.517     albertel 7061: sub tokenwrapper {
                   7062:     my $uri=shift;
1.552     albertel 7063:     $uri=~s|^http\://([^/]+)||;
                   7064:     $uri=~s|^/||;
1.620     albertel 7065:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 7066:     my $token=$1;
1.552     albertel 7067:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   7068:     if ($udom && $uname && $file) {
                   7069: 	$file=~s|(\?\.*)*$||;
1.620     albertel 7070:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
1.552     albertel 7071:         return 'http://'.$hostname{ &homeserver($uname,$udom)}.'/'.$uri.
1.517     albertel 7072:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   7073:                                '&tokenissued='.$perlvar{'lonHostID'};
                   7074:     } else {
                   7075:         return '/adm/notfound.html';
                   7076:     }
                   7077: }
                   7078: 
1.481     raeburn  7079: sub getuploaded {
                   7080:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   7081:     $uri=~s/^\///;
                   7082:     $uri = 'http://'.$hostname{ &homeserver($cnum,$cdom)}.'/raw/'.$uri;
                   7083:     my $ua=new LWP::UserAgent;
                   7084:     my $request=new HTTP::Request($reqtype,$uri);
                   7085:     my $response=$ua->request($request);
                   7086:     $$rtncode = $response->code;
1.482     albertel 7087:     if (! $response->is_success()) {
                   7088: 	return 'failed';
                   7089:     }      
                   7090:     if ($reqtype eq 'HEAD') {
1.486     www      7091: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 7092:     } elsif ($reqtype eq 'GET') {
                   7093: 	$$info = $response->content;
1.472     albertel 7094:     }
1.482     albertel 7095:     return 'ok';
1.36      albertel 7096: }
                   7097: 
1.481     raeburn  7098: sub readfile {
                   7099:     my $file = shift;
                   7100:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   7101:     my $fh;
                   7102:     open($fh,"<$file");
                   7103:     my $a='';
1.800     albertel 7104:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  7105:     return $a;
                   7106: }
                   7107: 
1.36      albertel 7108: sub filelocation {
1.590     banghart 7109:     my ($dir,$file) = @_;
                   7110:     my $location;
                   7111:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 7112: 
                   7113:     if ($file =~ m-^/adm/-) {
                   7114: 	$file=~s-^/adm/wrapper/-/-;
                   7115: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   7116:     }
1.590     banghart 7117:     if ($file=~m:^/~:) { # is a contruction space reference
                   7118:         $location = $file;
                   7119:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.649     albertel 7120:     } elsif ($file=~m:^/home/[^/]*/public_html/:) {
                   7121: 	# is a correct contruction space reference
                   7122:         $location = $file;
1.609     banghart 7123:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 7124:         my ($udom,$uname,$filename)=
1.609     banghart 7125:   	    ($file=~m -^/+(?:uploaded|editupload)/+([^/]+)/+([^/]+)/+(.*)$-);
1.590     banghart 7126:         my $home=&homeserver($uname,$udom);
                   7127:         my $is_me=0;
                   7128:         my @ids=&current_machine_ids();
                   7129:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   7130:         if ($is_me) {
1.740     www      7131:   	    $location=&propath($udom,$uname).
1.590     banghart 7132:   	      '/userfiles/'.$filename;
                   7133:         } else {
                   7134:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   7135:   	      $udom.'/'.$uname.'/'.$filename;
                   7136:         }
                   7137:     } else {
                   7138:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   7139:         $file=~s:^/res/:/:;
                   7140:         if ( !( $file =~ m:^/:) ) {
                   7141:             $location = $dir. '/'.$file;
                   7142:         } else {
                   7143:             $location = '/home/httpd/html/res'.$file;
                   7144:         }
1.59      albertel 7145:     }
1.590     banghart 7146:     $location=~s://+:/:g; # remove duplicate /
                   7147:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
                   7148:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   7149:     return $location;
1.46      www      7150: }
1.36      albertel 7151: 
1.46      www      7152: sub hreflocation {
                   7153:     my ($dir,$file)=@_;
1.460     albertel 7154:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666     albertel 7155: 	$file=filelocation($dir,$file);
1.700     albertel 7156:     } elsif ($file=~m-^/adm/-) {
                   7157: 	$file=~s-^/adm/wrapper/-/-;
                   7158: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 7159:     }
                   7160:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   7161: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   7162:     } elsif ($file=~m-/home/(\w+)/public_html/-) {
1.462     albertel 7163: 	$file=~s-^/home/(\w+)/public_html/-/~$1/-;
1.666     albertel 7164:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
                   7165: 	$file=~s-^/home/httpd/lonUsers/([^/]*)/./././([^/]*)/userfiles/
                   7166: 	    -/uploaded/$1/$2/-x;
1.46      www      7167:     }
1.462     albertel 7168:     return $file;
1.465     albertel 7169: }
                   7170: 
                   7171: sub current_machine_domains {
                   7172:     my $hostname=$hostname{$perlvar{'lonHostID'}};
                   7173:     my @domains;
                   7174:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  7175: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 7176: 	if ($hostname eq $name) {
                   7177: 	    push(@domains,$hostdom{$id});
                   7178: 	}
                   7179:     }
                   7180:     return @domains;
                   7181: }
                   7182: 
                   7183: sub current_machine_ids {
                   7184:     my $hostname=$hostname{$perlvar{'lonHostID'}};
                   7185:     my @ids;
                   7186:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  7187: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 7188: 	if ($hostname eq $name) {
                   7189: 	    push(@ids,$id);
                   7190: 	}
                   7191:     }
                   7192:     return @ids;
1.31      www      7193: }
                   7194: 
                   7195: # ------------------------------------------------------------- Declutters URLs
                   7196: 
                   7197: sub declutter {
                   7198:     my $thisfn=shift;
1.569     albertel 7199:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 7200:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      7201:     $thisfn=~s/^\///;
1.697     albertel 7202:     $thisfn=~s|^adm/wrapper/||;
                   7203:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      7204:     $thisfn=~s/^res\///;
1.235     www      7205:     $thisfn=~s/\?.+$//;
1.268     www      7206:     return $thisfn;
                   7207: }
                   7208: 
                   7209: # ------------------------------------------------------------- Clutter up URLs
                   7210: 
                   7211: sub clutter {
                   7212:     my $thisfn='/'.&declutter(shift);
1.609     banghart 7213:     unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) { 
1.270     www      7214:        $thisfn='/res'.$thisfn; 
                   7215:     }
1.694     albertel 7216:     if ($thisfn !~m|/adm|) {
1.695     albertel 7217: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 7218: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 7219: 	} else {
                   7220: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   7221: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 7222: 	    if ($embstyle eq 'ssi'
                   7223: 		|| ($embstyle eq 'hdn')
                   7224: 		|| ($embstyle eq 'rat')
                   7225: 		|| ($embstyle eq 'prv')
                   7226: 		|| ($embstyle eq 'ign')) {
                   7227: 		#do nothing with these
                   7228: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 7229: 		|| ($embstyle eq 'emb')
                   7230: 		|| ($embstyle eq 'wrp')) {
                   7231: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 7232: 	    } elsif ($embstyle eq 'unk'
                   7233: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 7234: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 7235: 	    } else {
1.718     www      7236: #		&logthis("Got a blank emb style");
1.695     albertel 7237: 	    }
1.694     albertel 7238: 	}
                   7239:     }
1.31      www      7240:     return $thisfn;
1.12      www      7241: }
                   7242: 
1.787     albertel 7243: sub clutter_with_no_wrapper {
                   7244:     my $uri = &clutter(shift);
                   7245:     if ($uri =~ m-^/adm/-) {
                   7246: 	$uri =~ s-^/adm/wrapper/-/-;
                   7247: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   7248:     }
                   7249:     return $uri;
                   7250: }
                   7251: 
1.557     albertel 7252: sub freeze_escape {
                   7253:     my ($value)=@_;
                   7254:     if (ref($value)) {
                   7255: 	$value=&nfreeze($value);
                   7256: 	return '__FROZEN__'.&escape($value);
                   7257:     }
                   7258:     return &escape($value);
                   7259: }
                   7260: 
1.11      www      7261: 
1.557     albertel 7262: sub thaw_unescape {
                   7263:     my ($value)=@_;
                   7264:     if ($value =~ /^__FROZEN__/) {
                   7265: 	substr($value,0,10,undef);
                   7266: 	$value=&unescape($value);
                   7267: 	return &thaw($value);
                   7268:     }
                   7269:     return &unescape($value);
                   7270: }
                   7271: 
1.436     albertel 7272: sub correct_line_ends {
                   7273:     my ($result)=@_;
                   7274:     $$result =~s/\r\n/\n/mg;
                   7275:     $$result =~s/\r/\n/mg;
1.415     albertel 7276: }
1.1       albertel 7277: # ================================================================ Main Program
                   7278: 
1.184     www      7279: sub goodbye {
1.204     albertel 7280:    &logthis("Starting Shut down");
1.443     albertel 7281: #not converted to using infrastruture and probably shouldn't be
1.599     albertel 7282:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&freeze(\%badServerCache))));
1.443     albertel 7283: #converted
1.599     albertel 7284: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
                   7285:    &logthis(sprintf("%-20s is %s",'%homecache',length(&freeze(\%homecache))));
                   7286: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&freeze(\%titlecache))));
                   7287: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&freeze(\%courseresdatacache))));
1.425     albertel 7288: #1.1 only
1.599     albertel 7289: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&freeze(\%userresdatacache))));
                   7290: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&freeze(\%getsectioncache))));
                   7291: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&freeze(\%courseresversioncache))));
                   7292: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&freeze(\%resversioncache))));
                   7293:    &logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
                   7294:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   7295:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      7296:    &flushcourselogs();
                   7297:    &logthis("Shutting down");
                   7298: }
                   7299: 
1.179     www      7300: BEGIN {
1.228     harris41 7301: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
1.195     www      7302:     unless ($readit) {
1.217     harris41 7303: {
1.781     raeburn  7304:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   7305:     %perlvar = (%perlvar,%{$configvars});
1.227     harris41 7306: }
1.1       albertel 7307: 
1.327     albertel 7308: # ------------------------------------------------------------ Read domain file
                   7309: {
                   7310:     %domaindescription = ();
                   7311:     %domain_auth_def = ();
                   7312:     %domain_auth_arg_def = ();
1.448     albertel 7313:     my $fh;
                   7314:     if (open($fh,"<".$Apache::lonnet::perlvar{'lonTabDir'}.'/domain.tab')) {
1.800     albertel 7315: 	while (my $line = <$fh>) {
                   7316:            next if ($line =~ /^(\#|\s*$)/);
1.390     matthew  7317: #           next if /^\#/;
1.801     foxr     7318:            chomp $line;
1.403     www      7319:            my ($domain, $domain_description, $def_auth, $def_auth_arg,
1.800     albertel 7320: 	       $def_lang, $city, $longi, $lati, $primary) = split(/:/,$line,9);
1.403     www      7321: 	   $domain_auth_def{$domain}=$def_auth;
1.327     albertel 7322:            $domain_auth_arg_def{$domain}=$def_auth_arg;
1.403     www      7323: 	   $domaindescription{$domain}=$domain_description;
                   7324: 	   $domain_lang_def{$domain}=$def_lang;
                   7325: 	   $domain_city{$domain}=$city;
                   7326: 	   $domain_longi{$domain}=$longi;
                   7327: 	   $domain_lati{$domain}=$lati;
1.685     raeburn  7328:            $domain_primary{$domain}=$primary;
1.403     www      7329: 
1.448     albertel 7330:  #         &logthis("Domain.tab: $domain, $domain_auth_def{$domain}, $domain_auth_arg_def{$domain},$domaindescription{$domain}");
1.327     albertel 7331: #          &logthis("Domain.tab: $domain ".$domaindescription{$domain} );
1.448     albertel 7332: 	}
1.327     albertel 7333:     }
1.448     albertel 7334:     close ($fh);
1.327     albertel 7335: }
                   7336: 
                   7337: 
1.1       albertel 7338: # ------------------------------------------------------------- Read hosts file
                   7339: {
1.448     albertel 7340:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
1.1       albertel 7341: 
                   7342:     while (my $configline=<$config>) {
1.303     matthew  7343:        next if ($configline =~ /^(\#|\s*$)/);
1.154     www      7344:        chomp($configline);
1.595     albertel 7345:        my ($id,$domain,$role,$name)=split(/:/,$configline);
1.597     albertel 7346:        $name=~s/\s//g;
1.595     albertel 7347:        if ($id && $domain && $role && $name) {
1.252     albertel 7348: 	 $hostname{$id}=$name;
                   7349: 	 $hostdom{$id}=$domain;
                   7350: 	 if ($role eq 'library') { $libserv{$id}=$name; }
1.245     www      7351:        }
1.1       albertel 7352:     }
1.448     albertel 7353:     close($config);
1.619     albertel 7354:     # FIXME: dev server don't want this, production servers _do_ want this
1.654     albertel 7355:     #&get_iphost();
1.1       albertel 7356: }
                   7357: 
1.598     albertel 7358: sub get_iphost {
                   7359:     if (%iphost) { return %iphost; }
1.653     albertel 7360:     my %name_to_ip;
1.598     albertel 7361:     foreach my $id (keys(%hostname)) {
                   7362: 	my $name=$hostname{$id};
1.653     albertel 7363: 	my $ip;
                   7364: 	if (!exists($name_to_ip{$name})) {
                   7365: 	    $ip = gethostbyname($name);
                   7366: 	    if (!$ip || length($ip) ne 4) {
                   7367: 		&logthis("Skipping host $id name $name no IP found\n");
                   7368: 		next;
                   7369: 	    }
                   7370: 	    $ip=inet_ntoa($ip);
                   7371: 	    $name_to_ip{$name} = $ip;
                   7372: 	} else {
                   7373: 	    $ip = $name_to_ip{$name};
1.598     albertel 7374: 	}
                   7375: 	push(@{$iphost{$ip}},$id);
                   7376:     }
                   7377:     return %iphost;
                   7378: }
                   7379: 
1.1       albertel 7380: # ------------------------------------------------------ Read spare server file
                   7381: {
1.448     albertel 7382:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 7383: 
                   7384:     while (my $configline=<$config>) {
                   7385:        chomp($configline);
1.284     matthew  7386:        if ($configline) {
1.784     albertel 7387: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 7388: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 7389: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 7390:        }
                   7391:     }
1.448     albertel 7392:     close($config);
1.1       albertel 7393: }
1.11      www      7394: # ------------------------------------------------------------ Read permissions
                   7395: {
1.448     albertel 7396:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      7397: 
                   7398:     while (my $configline=<$config>) {
1.448     albertel 7399: 	chomp($configline);
                   7400: 	if ($configline) {
                   7401: 	    my ($role,$perm)=split(/ /,$configline);
                   7402: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   7403: 	}
1.11      www      7404:     }
1.448     albertel 7405:     close($config);
1.11      www      7406: }
                   7407: 
                   7408: # -------------------------------------------- Read plain texts for permissions
                   7409: {
1.448     albertel 7410:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      7411: 
                   7412:     while (my $configline=<$config>) {
1.448     albertel 7413: 	chomp($configline);
                   7414: 	if ($configline) {
1.742     raeburn  7415: 	    my ($short,@plain)=split(/:/,$configline);
                   7416:             %{$prp{$short}} = ();
                   7417: 	    if (@plain > 0) {
                   7418:                 $prp{$short}{'std'} = $plain[0];
                   7419:                 for (my $i=1; $i<@plain; $i++) {
                   7420:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   7421:                 }
                   7422:             }
1.448     albertel 7423: 	}
1.135     www      7424:     }
1.448     albertel 7425:     close($config);
1.135     www      7426: }
                   7427: 
                   7428: # ---------------------------------------------------------- Read package table
                   7429: {
1.448     albertel 7430:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      7431: 
                   7432:     while (my $configline=<$config>) {
1.483     albertel 7433: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 7434: 	chomp($configline);
                   7435: 	my ($short,$plain)=split(/:/,$configline);
                   7436: 	my ($pack,$name)=split(/\&/,$short);
                   7437: 	if ($plain ne '') {
                   7438: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   7439: 	    $packagetab{$short}=$plain; 
                   7440: 	}
1.11      www      7441:     }
1.448     albertel 7442:     close($config);
1.329     matthew  7443: }
                   7444: 
                   7445: # ------------- set up temporary directory
                   7446: {
                   7447:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   7448: 
1.11      www      7449: }
                   7450: 
1.794     albertel 7451: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   7452: 				'compress_threshold'=> 20_000,
                   7453:  			        });
1.185     www      7454: 
1.281     www      7455: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      7456: $dumpcount=0;
1.22      www      7457: 
1.163     harris41 7458: &logtouch();
1.672     albertel 7459: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      7460: $readit=1;
1.564     albertel 7461:     {
                   7462: 	use integer;
                   7463: 	my $test=(2**32)+1;
1.568     albertel 7464: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 7465: 	&logthis(" Detected 64bit platform ($_64bit)");
                   7466:     }
1.195     www      7467: }
1.1       albertel 7468: }
1.179     www      7469: 
1.1       albertel 7470: 1;
1.191     harris41 7471: __END__
                   7472: 
1.243     albertel 7473: =pod
                   7474: 
1.191     harris41 7475: =head1 NAME
                   7476: 
1.243     albertel 7477: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 7478: 
                   7479: =head1 SYNOPSIS
                   7480: 
1.243     albertel 7481: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 7482: 
                   7483:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   7484: 
1.243     albertel 7485: Common parameters:
                   7486: 
                   7487: =over 4
                   7488: 
                   7489: =item *
                   7490: 
                   7491: $uname : an internal username (if $cname expecting a course Id specifically)
                   7492: 
                   7493: =item *
                   7494: 
                   7495: $udom : a domain (if $cdom expecting a course's domain specifically)
                   7496: 
                   7497: =item *
                   7498: 
                   7499: $symb : a resource instance identifier
                   7500: 
                   7501: =item *
                   7502: 
                   7503: $namespace : the name of a .db file that contains the data needed or
                   7504: being set.
                   7505: 
                   7506: =back
                   7507: 
1.394     bowersj2 7508: =head1 OVERVIEW
1.191     harris41 7509: 
1.394     bowersj2 7510: lonnet provides subroutines which interact with the
                   7511: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   7512: about classes, users, and resources.
1.243     albertel 7513: 
                   7514: For many of these objects you can also use this to store data about
                   7515: them or modify them in various ways.
1.191     harris41 7516: 
1.394     bowersj2 7517: =head2 Symbs
1.191     harris41 7518: 
1.394     bowersj2 7519: To identify a specific instance of a resource, LON-CAPA uses symbols
                   7520: or "symbs"X<symb>. These identifiers are built from the URL of the
                   7521: map, the resource number of the resource in the map, and the URL of
                   7522: the resource itself. The latter is somewhat redundant, but might help
                   7523: if maps change.
                   7524: 
                   7525: An example is
                   7526: 
                   7527:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   7528: 
                   7529: The respective map entry is
                   7530: 
                   7531:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   7532:   title="Problem 2">
                   7533:  </resource>
                   7534: 
                   7535: Symbs are used by the random number generator, as well as to store and
                   7536: restore data specific to a certain instance of for example a problem.
                   7537: 
                   7538: =head2 Storing And Retrieving Data
                   7539: 
                   7540: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   7541: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   7542: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   7543: is is the non-critical message twin of cstore. These functions are for
                   7544: handlers to store a perl hash to a user's permanent data space in an
                   7545: easy manner, and to retrieve it again on another call. It is expected
                   7546: that a handler would use this once at the beginning to retrieve data,
                   7547: and then again once at the end to send only the new data back.
                   7548: 
                   7549: The data is stored in the user's data directory on the user's
                   7550: homeserver under the ID of the course.
                   7551: 
                   7552: The hash that is returned by restore will have all of the previous
                   7553: value for all of the elements of the hash.
                   7554: 
                   7555: Example:
                   7556: 
                   7557:  #creating a hash
                   7558:  my %hash;
                   7559:  $hash{'foo'}='bar';
                   7560: 
                   7561:  #storing it
                   7562:  &Apache::lonnet::cstore(\%hash);
                   7563: 
                   7564:  #changing a value
                   7565:  $hash{'foo'}='notbar';
                   7566: 
                   7567:  #adding a new value
                   7568:  $hash{'bar'}='foo';
                   7569:  &Apache::lonnet::cstore(\%hash);
                   7570: 
                   7571:  #retrieving the hash
                   7572:  my %history=&Apache::lonnet::restore();
                   7573: 
                   7574:  #print the hash
                   7575:  foreach my $key (sort(keys(%history))) {
                   7576:    print("\%history{$key} = $history{$key}");
                   7577:  }
                   7578: 
                   7579: Will print out:
1.191     harris41 7580: 
1.394     bowersj2 7581:  %history{1:foo} = bar
                   7582:  %history{1:keys} = foo:timestamp
                   7583:  %history{1:timestamp} = 990455579
                   7584:  %history{2:bar} = foo
                   7585:  %history{2:foo} = notbar
                   7586:  %history{2:keys} = foo:bar:timestamp
                   7587:  %history{2:timestamp} = 990455580
                   7588:  %history{bar} = foo
                   7589:  %history{foo} = notbar
                   7590:  %history{timestamp} = 990455580
                   7591:  %history{version} = 2
                   7592: 
                   7593: Note that the special hash entries C<keys>, C<version> and
                   7594: C<timestamp> were added to the hash. C<version> will be equal to the
                   7595: total number of versions of the data that have been stored. The
                   7596: C<timestamp> attribute will be the UNIX time the hash was
                   7597: stored. C<keys> is available in every historical section to list which
                   7598: keys were added or changed at a specific historical revision of a
                   7599: hash.
                   7600: 
                   7601: B<Warning>: do not store the hash that restore returns directly. This
                   7602: will cause a mess since it will restore the historical keys as if the
                   7603: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 7604: 
1.394     bowersj2 7605: Calling convention:
1.191     harris41 7606: 
1.394     bowersj2 7607:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   7608:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 7609: 
1.394     bowersj2 7610: For more detailed information, see lonnet specific documentation.
1.191     harris41 7611: 
1.394     bowersj2 7612: =head1 RETURN MESSAGES
1.191     harris41 7613: 
1.394     bowersj2 7614: =over 4
1.191     harris41 7615: 
1.394     bowersj2 7616: =item * B<con_lost>: unable to contact remote host
1.191     harris41 7617: 
1.394     bowersj2 7618: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   7619: when the connection is brought back up
1.191     harris41 7620: 
1.394     bowersj2 7621: =item * B<con_failed>: unable to contact remote host and unable to save message
                   7622: for later delivery
1.191     harris41 7623: 
1.394     bowersj2 7624: =item * B<error:>: an error a occured, a description of the error follows the :
1.191     harris41 7625: 
1.394     bowersj2 7626: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 7627: that was requested
1.191     harris41 7628: 
1.243     albertel 7629: =back
1.191     harris41 7630: 
1.243     albertel 7631: =head1 PUBLIC SUBROUTINES
1.191     harris41 7632: 
1.243     albertel 7633: =head2 Session Environment Functions
1.191     harris41 7634: 
1.243     albertel 7635: =over 4
1.191     harris41 7636: 
1.394     bowersj2 7637: =item * 
                   7638: X<appenv()>
                   7639: B<appenv(%hash)>: the value of %hash is written to
                   7640: the user envirnoment file, and will be restored for each access this
1.620     albertel 7641: user makes during this session, also modifies the %env for the current
1.394     bowersj2 7642: process
1.191     harris41 7643: 
                   7644: =item *
1.394     bowersj2 7645: X<delenv()>
                   7646: B<delenv($regexp)>: removes all items from the session
                   7647: environment file that matches the regular expression in $regexp. The
1.620     albertel 7648: values are also delted from the current processes %env.
1.191     harris41 7649: 
1.795     albertel 7650: =item * get_env_multiple($name) 
                   7651: 
                   7652: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   7653: values may be defined and end up as an array ref.
                   7654: 
                   7655: returns an array of values
                   7656: 
1.243     albertel 7657: =back
                   7658: 
                   7659: =head2 User Information
1.191     harris41 7660: 
1.243     albertel 7661: =over 4
1.191     harris41 7662: 
                   7663: =item *
1.394     bowersj2 7664: X<queryauthenticate()>
                   7665: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 7666: authentication scheme
                   7667: 
                   7668: =item *
1.394     bowersj2 7669: X<authenticate()>
                   7670: B<authenticate($uname,$upass,$udom)>: try to
                   7671: authenticate user from domain's lib servers (first use the current
                   7672: one). C<$upass> should be the users password.
1.191     harris41 7673: 
                   7674: =item *
1.394     bowersj2 7675: X<homeserver()>
                   7676: B<homeserver($uname,$udom)>: find the server which has
                   7677: the user's directory and files (there must be only one), this caches
                   7678: the answer, and also caches if there is a borken connection.
1.191     harris41 7679: 
                   7680: =item *
1.394     bowersj2 7681: X<idget()>
                   7682: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   7683: (IDs are a unique resource in a domain, there must be only 1 ID per
                   7684: username, and only 1 username per ID in a specific domain) (returns
                   7685: hash: id=>name,id=>name)
1.191     harris41 7686: 
                   7687: =item *
1.394     bowersj2 7688: X<idrget()>
                   7689: B<idrget($udom,@unames)>: find the IDs behind a list of
                   7690: usernames (returns hash: name=>id,name=>id)
1.191     harris41 7691: 
                   7692: =item *
1.394     bowersj2 7693: X<idput()>
                   7694: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 7695: 
                   7696: =item *
1.394     bowersj2 7697: X<rolesinit()>
                   7698: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 7699: 
                   7700: =item *
1.551     albertel 7701: X<getsection()>
                   7702: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 7703: course $cname, return section name/number or '' for "not in course"
                   7704: and '-1' for "no section"
                   7705: 
                   7706: =item *
1.394     bowersj2 7707: X<userenvironment()>
                   7708: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 7709: passed in @what from the requested user's environment, returns a hash
                   7710: 
                   7711: =back
                   7712: 
                   7713: =head2 User Roles
                   7714: 
                   7715: =over 4
                   7716: 
                   7717: =item *
                   7718: 
                   7719: allowed($priv,$uri) : check for a user privilege; returns codes for allowed
                   7720: actions
                   7721:  F: full access
                   7722:  U,I,K: authentication modes (cxx only)
                   7723:  '': forbidden
                   7724:  1: user needs to choose course
                   7725:  2: browse allowed
1.766     albertel 7726:  A: passphrase authentication needed
1.243     albertel 7727: 
                   7728: =item *
                   7729: 
                   7730: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   7731: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   7732: and course level
                   7733: 
                   7734: =item *
                   7735: 
                   7736: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   7737: explanation of a user role term
                   7738: 
                   7739: =back
                   7740: 
                   7741: =head2 User Modification
                   7742: 
                   7743: =over 4
                   7744: 
                   7745: =item *
                   7746: 
                   7747: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
                   7748: user for the level given by URL.  Optional start and end dates (leave empty
                   7749: string or zero for "no date")
1.191     harris41 7750: 
                   7751: =item *
                   7752: 
1.243     albertel 7753: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   7754: change a users, password, possible return values are: ok,
                   7755: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   7756: refused
1.191     harris41 7757: 
                   7758: =item *
                   7759: 
1.243     albertel 7760: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 7761: 
                   7762: =item *
                   7763: 
1.243     albertel 7764: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
                   7765: modify user
1.191     harris41 7766: 
                   7767: =item *
                   7768: 
1.286     matthew  7769: modifystudent
                   7770: 
                   7771: modify a students enrollment and identification information.
                   7772: The course id is resolved based on the current users environment.  
                   7773: This means the envoking user must be a course coordinator or otherwise
                   7774: associated with a course.
                   7775: 
1.297     matthew  7776: This call is essentially a wrapper for lonnet::modifyuser and
                   7777: lonnet::modify_student_enrollment
1.286     matthew  7778: 
                   7779: Inputs: 
                   7780: 
                   7781: =over 4
                   7782: 
                   7783: =item B<$udom> Students loncapa domain
                   7784: 
                   7785: =item B<$uname> Students loncapa login name
                   7786: 
                   7787: =item B<$uid> Students id/student number
                   7788: 
                   7789: =item B<$umode> Students authentication mode
                   7790: 
                   7791: =item B<$upass> Students password
                   7792: 
                   7793: =item B<$first> Students first name
                   7794: 
                   7795: =item B<$middle> Students middle name
                   7796: 
                   7797: =item B<$last> Students last name
                   7798: 
                   7799: =item B<$gene> Students generation
                   7800: 
                   7801: =item B<$usec> Students section in course
                   7802: 
                   7803: =item B<$end> Unix time of the roles expiration
                   7804: 
                   7805: =item B<$start> Unix time of the roles start date
                   7806: 
                   7807: =item B<$forceid> If defined, allow $uid to be changed
                   7808: 
                   7809: =item B<$desiredhome> server to use as home server for student
                   7810: 
                   7811: =back
1.297     matthew  7812: 
                   7813: =item *
                   7814: 
                   7815: modify_student_enrollment
                   7816: 
                   7817: Change a students enrollment status in a class.  The environment variable
                   7818: 'role.request.course' must be defined for this function to proceed.
                   7819: 
                   7820: Inputs:
                   7821: 
                   7822: =over 4
                   7823: 
                   7824: =item $udom, students domain
                   7825: 
                   7826: =item $uname, students name
                   7827: 
                   7828: =item $uid, students user id
                   7829: 
                   7830: =item $first, students first name
                   7831: 
                   7832: =item $middle
                   7833: 
                   7834: =item $last
                   7835: 
                   7836: =item $gene
                   7837: 
                   7838: =item $usec
                   7839: 
                   7840: =item $end
                   7841: 
                   7842: =item $start
                   7843: 
                   7844: =back
                   7845: 
1.191     harris41 7846: 
                   7847: =item *
                   7848: 
1.243     albertel 7849: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   7850: custom role; give a custom role to a user for the level given by URL.  Specify
                   7851: name and domain of role author, and role name
1.191     harris41 7852: 
                   7853: =item *
                   7854: 
1.243     albertel 7855: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 7856: 
                   7857: =item *
                   7858: 
1.243     albertel 7859: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   7860: 
                   7861: =back
                   7862: 
                   7863: =head2 Course Infomation
                   7864: 
                   7865: =over 4
1.191     harris41 7866: 
                   7867: =item *
                   7868: 
1.631     albertel 7869: coursedescription($courseid) : returns a hash of information about the
                   7870: specified course id, including all environment settings for the
                   7871: course, the description of the course will be in the hash under the
                   7872: key 'description'
1.191     harris41 7873: 
                   7874: =item *
                   7875: 
1.624     albertel 7876: resdata($name,$domain,$type,@which) : request for current parameter
                   7877: setting for a specific $type, where $type is either 'course' or 'user',
                   7878: @what should be a list of parameters to ask about. This routine caches
                   7879: answers for 5 minutes.
1.243     albertel 7880: 
                   7881: =back
                   7882: 
                   7883: =head2 Course Modification
                   7884: 
                   7885: =over 4
1.191     harris41 7886: 
                   7887: =item *
                   7888: 
1.243     albertel 7889: writecoursepref($courseid,%prefs) : write preferences (environment
                   7890: database) for a course
1.191     harris41 7891: 
                   7892: =item *
                   7893: 
1.243     albertel 7894: createcourse($udom,$description,$url) : make/modify course
                   7895: 
                   7896: =back
                   7897: 
                   7898: =head2 Resource Subroutines
                   7899: 
                   7900: =over 4
1.191     harris41 7901: 
                   7902: =item *
                   7903: 
1.243     albertel 7904: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 7905: 
                   7906: =item *
                   7907: 
1.243     albertel 7908: repcopy($filename) : subscribes to the requested file, and attempts to
                   7909: replicate from the owning library server, Might return
1.607     raeburn  7910: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   7911: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 7912: resource. Expects the local filesystem pathname
                   7913: (/home/httpd/html/res/....)
                   7914: 
                   7915: =back
                   7916: 
                   7917: =head2 Resource Information
                   7918: 
                   7919: =over 4
1.191     harris41 7920: 
                   7921: =item *
                   7922: 
1.243     albertel 7923: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   7924: a vairety of different possible values, $varname should be a request
                   7925: string, and the other parameters can be used to specify who and what
                   7926: one is asking about.
                   7927: 
                   7928: Possible values for $varname are environment.lastname (or other item
                   7929: from the envirnment hash), user.name (or someother aspect about the
                   7930: user), resource.0.maxtries (or some other part and parameter of a
                   7931: resource)
1.204     albertel 7932: 
                   7933: =item *
                   7934: 
1.243     albertel 7935: directcondval($number) : get current value of a condition; reads from a state
                   7936: string
1.204     albertel 7937: 
                   7938: =item *
                   7939: 
1.243     albertel 7940: condval($condidx) : value of condition index based on state
1.204     albertel 7941: 
                   7942: =item *
                   7943: 
1.243     albertel 7944: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   7945: resource's metadata, $what should be either a specific key, or either
                   7946: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   7947: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   7948: 
                   7949: this function automatically caches all requests
1.191     harris41 7950: 
                   7951: =item *
                   7952: 
1.243     albertel 7953: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   7954: network of library servers; returns file handle of where SQL and regex results
                   7955: will be stored for query
1.191     harris41 7956: 
                   7957: =item *
                   7958: 
1.243     albertel 7959: symbread($filename) : return symbolic list entry (filename argument optional);
                   7960: returns the data handle
1.191     harris41 7961: 
                   7962: =item *
                   7963: 
1.243     albertel 7964: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 7965: a possible symb for the URL in $thisfn, and if is an encryypted
                   7966: resource that the user accessed using /enc/ returns a 1 on success, 0
                   7967: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 7968: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 7969: 
1.191     harris41 7970: 
                   7971: =item *
                   7972: 
1.243     albertel 7973: symbclean($symb) : removes versions numbers from a symb, returns the
                   7974: cleaned symb
1.191     harris41 7975: 
                   7976: =item *
                   7977: 
1.243     albertel 7978: is_on_map($uri) : checks if the $uri is somewhere on the current
                   7979: course map, user must be in a course for it to work.
1.191     harris41 7980: 
                   7981: =item *
                   7982: 
1.243     albertel 7983: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 7984: 
                   7985: =item *
                   7986: 
1.243     albertel 7987: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   7988: a random seed, all arguments are optional, if they aren't sent it uses the
                   7989: environment to derive them. Note: if symb isn't sent and it can't get one
                   7990: from &symbread it will use the current time as its return value
1.191     harris41 7991: 
                   7992: =item *
                   7993: 
1.243     albertel 7994: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   7995: unfakeable, receipt
1.191     harris41 7996: 
                   7997: =item *
                   7998: 
1.620     albertel 7999: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 8000: 
                   8001: =item *
                   8002: 
1.243     albertel 8003: countacc($url) : count the number of accesses to a given URL
1.191     harris41 8004: 
                   8005: =item *
                   8006: 
1.243     albertel 8007: 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 8008: 
                   8009: =item *
                   8010: 
1.243     albertel 8011: 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 8012: 
                   8013: =item *
                   8014: 
1.243     albertel 8015: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 8016: 
                   8017: =item *
                   8018: 
1.243     albertel 8019: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   8020: forcing spreadsheet to reevaluate the resource scores next time.
                   8021: 
                   8022: =back
                   8023: 
                   8024: =head2 Storing/Retreiving Data
                   8025: 
                   8026: =over 4
1.191     harris41 8027: 
                   8028: =item *
                   8029: 
1.243     albertel 8030: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   8031: for this url; hashref needs to be given and should be a \%hashname; the
                   8032: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 8033: be derived from the env
1.191     harris41 8034: 
                   8035: =item *
                   8036: 
1.243     albertel 8037: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   8038: uses critical subroutine
1.191     harris41 8039: 
                   8040: =item *
                   8041: 
1.243     albertel 8042: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   8043: all args are optional
1.191     harris41 8044: 
                   8045: =item *
                   8046: 
1.717     albertel 8047: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   8048: dumps the complete (or key matching regexp) namespace into a hash
                   8049: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   8050: normally &store()ed into
                   8051: 
                   8052: $range should be either an integer '100' (give me the first 100
                   8053:                                            matching records)
                   8054:               or be  two integers sperated by a - with no spaces
                   8055:                  '30-50' (give me the 30th through the 50th matching
                   8056:                           records)
                   8057: 
                   8058: 
                   8059: =item *
                   8060: 
                   8061: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   8062: replaces a &store() version of data with a replacement set of data
                   8063: for a particular resource in a namespace passed in the $storehash hash 
                   8064: reference
                   8065: 
                   8066: =item *
                   8067: 
1.243     albertel 8068: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   8069: works very similar to store/cstore, but all data is stored in a
                   8070: temporary location and can be reset using tmpreset, $storehash should
                   8071: be a hash reference, returns nothing on success
1.191     harris41 8072: 
                   8073: =item *
                   8074: 
1.243     albertel 8075: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   8076: similar to restore, but all data is stored in a temporary location and
                   8077: can be reset using tmpreset. Returns a hash of values on success,
                   8078: error string otherwise.
1.191     harris41 8079: 
                   8080: =item *
                   8081: 
1.243     albertel 8082: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   8083: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 8084: 
                   8085: =item *
                   8086: 
1.243     albertel 8087: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   8088: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 8089: 
                   8090: =item *
                   8091: 
1.243     albertel 8092: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   8093: namesp ($udom and $uname are optional)
1.191     harris41 8094: 
                   8095: =item *
                   8096: 
1.702     albertel 8097: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 8098: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 8099: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  8100: 
1.702     albertel 8101: $range should be either an integer '100' (give me the first 100
                   8102:                                            matching records)
                   8103:               or be  two integers sperated by a - with no spaces
                   8104:                  '30-50' (give me the 30th through the 50th matching
                   8105:                           records)
1.449     matthew  8106: =item *
                   8107: 
                   8108: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   8109: $store can be a scalar, an array reference, or if the amount to be 
                   8110: incremented is > 1, a hash reference.
                   8111: 
                   8112: ($udom and $uname are optional)
1.191     harris41 8113: 
                   8114: =item *
                   8115: 
1.243     albertel 8116: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   8117: ($udom and $uname are optional)
1.191     harris41 8118: 
                   8119: =item *
                   8120: 
1.243     albertel 8121: cput($namespace,$storehash,$udom,$uname) : critical put
                   8122: ($udom and $uname are optional)
1.191     harris41 8123: 
                   8124: =item *
                   8125: 
1.748     albertel 8126: newput($namespace,$storehash,$udom,$uname) :
                   8127: 
                   8128: Attempts to store the items in the $storehash, but only if they don't
                   8129: currently exist, if this succeeds you can be certain that you have 
                   8130: successfully created a new key value pair in the $namespace db.
                   8131: 
                   8132: 
                   8133: Args:
                   8134:  $namespace: name of database to store values to
                   8135:  $storehash: hashref to store to the db
                   8136:  $udom: (optional) domain of user containing the db
                   8137:  $uname: (optional) name of user caontaining the db
                   8138: 
                   8139: Returns:
                   8140:  'ok' -> succeeded in storing all keys of $storehash
                   8141:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   8142:                         least <key> already existed in the db (other
                   8143:                         requested keys may also already exist)
                   8144:  'error: <msg>' -> unable to tie the DB or other erorr occured
                   8145:  'con_lost' -> unable to contact request server
                   8146:  'refused' -> action was not allowed by remote machine
                   8147: 
                   8148: 
                   8149: =item *
                   8150: 
1.243     albertel 8151: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   8152: reference filled in from namesp (encrypts the return communication)
                   8153: ($udom and $uname are optional)
1.191     harris41 8154: 
                   8155: =item *
                   8156: 
1.243     albertel 8157: log($udom,$name,$home,$message) : write to permanent log for user; use
                   8158: critical subroutine
                   8159: 
1.806   ! raeburn  8160: =item *
        !          8161: 
        !          8162: get_dom($namespace,$storearr,$udomain) : returns hash with keys from array
        !          8163: reference filled in from namespace found in domain level on primary domain server ($udomain is optional)
        !          8164: 
        !          8165: =item *
        !          8166: 
        !          8167: put_dom($namespace,$storehash,$udomain) :  stores hash in namespace at domain level on primary domain server ($udomain is optional)
        !          8168: 
1.243     albertel 8169: =back
                   8170: 
                   8171: =head2 Network Status Functions
                   8172: 
                   8173: =over 4
1.191     harris41 8174: 
                   8175: =item *
                   8176: 
                   8177: dirlist($uri) : return directory list based on URI
                   8178: 
                   8179: =item *
                   8180: 
1.243     albertel 8181: spareserver() : find server with least workload from spare.tab
                   8182: 
                   8183: =back
                   8184: 
                   8185: =head2 Apache Request
                   8186: 
                   8187: =over 4
1.191     harris41 8188: 
                   8189: =item *
                   8190: 
1.243     albertel 8191: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   8192: localhost, posts hash
                   8193: 
                   8194: =back
                   8195: 
                   8196: =head2 Data to String to Data
                   8197: 
                   8198: =over 4
1.191     harris41 8199: 
                   8200: =item *
                   8201: 
1.243     albertel 8202: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   8203: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 8204: 
                   8205: =item *
                   8206: 
1.243     albertel 8207: hashref2str($hashref) : convert a hashref into a string complete with
                   8208: escaping and '=' and '&' separators, supports elements that are
                   8209: arrayrefs and hashrefs
1.191     harris41 8210: 
                   8211: =item *
                   8212: 
1.243     albertel 8213: arrayref2str($arrayref) : convert an arrayref into a string complete
                   8214: with escaping and '&' separators, supports elements that are arrayrefs
                   8215: and hashrefs
1.191     harris41 8216: 
                   8217: =item *
                   8218: 
1.243     albertel 8219: str2hash($string) : convert string to hash using unescaping and
                   8220: splitting on '=' and '&', supports elements that are arrayrefs and
                   8221: hashrefs
1.191     harris41 8222: 
                   8223: =item *
                   8224: 
1.243     albertel 8225: str2array($string) : convert string to hash using unescaping and
                   8226: splitting on '&', supports elements that are arrayrefs and hashrefs
                   8227: 
                   8228: =back
                   8229: 
                   8230: =head2 Logging Routines
                   8231: 
                   8232: =over 4
                   8233: 
                   8234: These routines allow one to make log messages in the lonnet.log and
                   8235: lonnet.perm logfiles.
1.191     harris41 8236: 
                   8237: =item *
                   8238: 
1.243     albertel 8239: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 8240: 
                   8241: =item *
                   8242: 
1.243     albertel 8243: logthis() : append message to the normal lonnet.log file, it gets
                   8244: preiodically rolled over and deleted.
1.191     harris41 8245: 
                   8246: =item *
                   8247: 
1.243     albertel 8248: logperm() : append a permanent message to lonnet.perm.log, this log
                   8249: file never gets deleted by any automated portion of the system, only
                   8250: messages of critical importance should go in here.
                   8251: 
                   8252: =back
                   8253: 
                   8254: =head2 General File Helper Routines
                   8255: 
                   8256: =over 4
1.191     harris41 8257: 
                   8258: =item *
                   8259: 
1.481     raeburn  8260: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   8261: (a) files in /uploaded
                   8262:   (i) If a local copy of the file exists - 
                   8263:       compares modification date of local copy with last-modified date for 
                   8264:       definitive version stored on home server for course. If local copy is 
                   8265:       stale, requests a new version from the home server and stores it. 
                   8266:       If the original has been removed from the home server, then local copy 
                   8267:       is unlinked.
                   8268:   (ii) If local copy does not exist -
                   8269:       requests the file from the home server and stores it. 
                   8270:   
                   8271:   If $caller is 'uploadrep':  
                   8272:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   8273:     for request for files originally uploaded via DOCS. 
                   8274:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   8275:   
                   8276:   Otherwise:
                   8277:      This indicates a call from the content generation phase of the request.
                   8278:      -  returns the entire contents of the file or -1.
                   8279:      
                   8280: (b) files in /res
                   8281:    - returns the entire contents of a file or -1; 
                   8282:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 8283: 
1.712     albertel 8284: 
                   8285: =item *
                   8286: 
                   8287: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   8288:                   reference
                   8289: 
                   8290: returns either a stat() list of data about the file or an empty list
                   8291: if the file doesn't exist or couldn't find out about it (connection
                   8292: problems or user unknown)
                   8293: 
1.191     harris41 8294: =item *
                   8295: 
1.243     albertel 8296: filelocation($dir,$file) : returns file system location of a file
                   8297: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   8298: directory that relative $file lookups are to looked in ($dir of /a/dir
                   8299: and a file of ../bob will become /a/bob)
1.191     harris41 8300: 
                   8301: =item *
                   8302: 
                   8303: hreflocation($dir,$file) : returns file system location or a URL; same as
                   8304: filelocation except for hrefs
                   8305: 
                   8306: =item *
                   8307: 
                   8308: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   8309: 
1.243     albertel 8310: =back
                   8311: 
1.608     albertel 8312: =head2 Usererfile file routines (/uploaded*)
                   8313: 
                   8314: =over 4
                   8315: 
                   8316: =item *
                   8317: 
                   8318: userfileupload(): main rotine for putting a file in a user or course's
                   8319:                   filespace, arguments are,
                   8320: 
1.620     albertel 8321:  formname - required - this is the name of the element in $env where the
1.608     albertel 8322:            filename, and the contents of the file to create/modifed exist
1.620     albertel 8323:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   8324:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 8325:  coursedoc - if true, store the file in the course of the active role
                   8326:              of the current user
                   8327:  subdir - required - subdirectory to put the file in under ../userfiles/
                   8328:          if undefined, it will be placed in "unknown"
                   8329: 
                   8330:  (This routine calls clean_filename() to remove any dangerous
                   8331:  characters from the filename, and then calls finuserfileupload() to
                   8332:  complete the transaction)
                   8333: 
                   8334:  returns either the url of the uploaded file (/uploaded/....) if successful
                   8335:  and /adm/notfound.html if unsuccessful
                   8336: 
                   8337: =item *
                   8338: 
                   8339: clean_filename(): routine for cleaing a filename up for storage in
                   8340:                  userfile space, argument is:
                   8341: 
                   8342:  filename - proposed filename
                   8343: 
                   8344: returns: the new clean filename
                   8345: 
                   8346: =item *
                   8347: 
                   8348: finishuserfileupload(): routine that creaes and sends the file to
                   8349: userspace, probably shouldn't be called directly
                   8350: 
                   8351:   docuname: username or courseid of destination for the file
                   8352:   docudom: domain of user/course of destination for the file
                   8353:   formname: same as for userfileupload()
                   8354:   fname: filename (inculding subdirectories) for the file
                   8355: 
                   8356:  returns either the url of the uploaded file (/uploaded/....) if successful
                   8357:  and /adm/notfound.html if unsuccessful
                   8358: 
                   8359: =item *
                   8360: 
                   8361: renameuserfile(): renames an existing userfile to a new name
                   8362: 
                   8363:   Args:
                   8364:    docuname: username or courseid of destination for the file
                   8365:    docudom: domain of user/course of destination for the file
                   8366:    old: current file name (including any subdirs under userfiles)
                   8367:    new: desired file name (including any subdirs under userfiles)
                   8368: 
                   8369: =item *
                   8370: 
                   8371: mkdiruserfile(): creates a directory is a userfiles dir
                   8372: 
                   8373:   Args:
                   8374:    docuname: username or courseid of destination for the file
                   8375:    docudom: domain of user/course of destination for the file
                   8376:    dir: dir to create (including any subdirs under userfiles)
                   8377: 
                   8378: =item *
                   8379: 
                   8380: removeuserfile(): removes a file that exists in userfiles
                   8381: 
                   8382:   Args:
                   8383:    docuname: username or courseid of destination for the file
                   8384:    docudom: domain of user/course of destination for the file
                   8385:    fname: filname to delete (including any subdirs under userfiles)
                   8386: 
                   8387: =item *
                   8388: 
                   8389: removeuploadedurl(): convience function for removeuserfile()
                   8390: 
                   8391:   Args:
                   8392:    url:  a full /uploaded/... url to delete
                   8393: 
1.747     albertel 8394: =item * 
                   8395: 
                   8396: get_portfile_permissions():
                   8397:   Args:
                   8398:     domain: domain of user or course contain the portfolio files
                   8399:     user: name of user or num of course contain the portfolio files
                   8400:   Returns:
                   8401:     hashref of a dump of the proper file_permissions.db
                   8402:    
                   8403: 
                   8404: =item * 
                   8405: 
                   8406: get_access_controls():
                   8407: 
                   8408: Args:
                   8409:   current_permissions: the hash ref returned from get_portfile_permissions()
                   8410:   group: (optional) the group you want the files associated with
                   8411:   file: (optional) the file you want access info on
                   8412: 
                   8413: Returns:
1.749     raeburn  8414:     a hash (keys are file names) of hashes containing
                   8415:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   8416:         values are XML containing access control settings (see below) 
1.747     albertel 8417: 
                   8418: Internal notes:
                   8419: 
1.749     raeburn  8420:  access controls are stored in file_permissions.db as key=value pairs.
                   8421:     key -> path to file/file_name\0uniqueID:scope_end_start
                   8422:         where scope -> public,guest,course,group,domains or users.
                   8423:               end -> UNIX time for end of access (0 -> no end date)
                   8424:               start -> UNIX time for start of access
                   8425: 
                   8426:     value -> XML description of access control
                   8427:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   8428:             <start></start>
                   8429:             <end></end>
                   8430: 
                   8431:             <password></password>  for scope type = guest
                   8432: 
                   8433:             <domain></domain>     for scope type = course or group
                   8434:             <number></number>
                   8435:             <roles id="">
                   8436:              <role></role>
                   8437:              <access></access>
                   8438:              <section></section>
                   8439:              <group></group>
                   8440:             </roles>
                   8441: 
                   8442:             <dom></dom>         for scope type = domains
                   8443: 
                   8444:             <users>             for scope type = users
                   8445:              <user>
                   8446:               <uname></uname>
                   8447:               <udom></udom>
                   8448:              </user>
                   8449:             </users>
                   8450:            </scope> 
                   8451:               
                   8452:  Access data is also aggregated for each file in an additional key=value pair:
                   8453:  key -> path to file/file_name\0accesscontrol 
                   8454:  value -> reference to hash
                   8455:           hash contains key = value pairs
                   8456:           where key = uniqueID:scope_end_start
                   8457:                 value = UNIX time record was last updated
                   8458: 
                   8459:           Used to improve speed of look-ups of access controls for each file.  
                   8460:  
                   8461:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   8462: 
                   8463: modify_access_controls():
                   8464: 
                   8465: Modifies access controls for a portfolio file
                   8466: Args
                   8467: 1. file name
                   8468: 2. reference to hash of required changes,
                   8469: 3. domain
                   8470: 4. username
                   8471:   where domain,username are the domain of the portfolio owner 
                   8472:   (either a user or a course) 
                   8473: 
                   8474: Returns:
                   8475: 1. result of additions or updates ('ok' or 'error', with error message). 
                   8476: 2. result of deletions ('ok' or 'error', with error message).
                   8477: 3. reference to hash of any new or updated access controls.
                   8478: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   8479:    key = integer (inbound ID)
                   8480:    value = uniqueID  
1.747     albertel 8481: 
1.608     albertel 8482: =back
                   8483: 
1.243     albertel 8484: =head2 HTTP Helper Routines
                   8485: 
                   8486: =over 4
                   8487: 
1.191     harris41 8488: =item *
                   8489: 
                   8490: escape() : unpack non-word characters into CGI-compatible hex codes
                   8491: 
                   8492: =item *
                   8493: 
                   8494: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   8495: 
1.243     albertel 8496: =back
                   8497: 
                   8498: =head1 PRIVATE SUBROUTINES
                   8499: 
                   8500: =head2 Underlying communication routines (Shouldn't call)
                   8501: 
                   8502: =over 4
                   8503: 
                   8504: =item *
                   8505: 
                   8506: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   8507: 
                   8508: =item *
                   8509: 
                   8510: reply() : uses subreply to send a message to remote machine, logs all failures
                   8511: 
                   8512: =item *
                   8513: 
                   8514: critical() : passes a critical message to another server; if cannot
                   8515: get through then place message in connection buffer directory and
                   8516: returns con_delayed, if incapable of saving message, returns
                   8517: con_failed
                   8518: 
                   8519: =item *
                   8520: 
                   8521: reconlonc() : tries to reconnect lonc client processes.
                   8522: 
                   8523: =back
                   8524: 
                   8525: =head2 Resource Access Logging
                   8526: 
                   8527: =over 4
                   8528: 
                   8529: =item *
                   8530: 
                   8531: flushcourselogs() : flush (save) buffer logs and access logs
                   8532: 
                   8533: =item *
                   8534: 
                   8535: courselog($what) : save message for course in hash
                   8536: 
                   8537: =item *
                   8538: 
                   8539: courseacclog($what) : save message for course using &courselog().  Perform
                   8540: special processing for specific resource types (problems, exams, quizzes, etc).
                   8541: 
1.191     harris41 8542: =item *
                   8543: 
                   8544: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   8545: as a PerlChildExitHandler
1.243     albertel 8546: 
                   8547: =back
                   8548: 
                   8549: =head2 Other
                   8550: 
                   8551: =over 4
                   8552: 
                   8553: =item *
                   8554: 
                   8555: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 8556: 
                   8557: =back
                   8558: 
                   8559: =cut

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