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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.859   ! albertel    4: # $Id: lonnet.pm,v 1.858 2007/04/03 17:51:50 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.847     albertel   38: qw(%perlvar %badServerCache %spareid 
1.845     albertel   39:    %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.685     raeburn    42:    $tmpdir $_64bit %env);
1.403     www        43: 
1.1       albertel   44: use IO::Socket;
1.31      www        45: use GDBM_File;
1.208     albertel   46: use HTML::LCParser;
1.637     raeburn    47: use HTML::Parser;
1.88      www        48: use Fcntl qw(:flock);
1.557     albertel   49: use Storable qw(lock_store lock_nstore lock_retrieve freeze thaw nfreeze);
1.539     albertel   50: use Time::HiRes qw( gettimeofday tv_interval );
1.599     albertel   51: use Cache::Memcached;
1.676     albertel   52: use Digest::MD5;
1.790     albertel   53: use Math::Random;
1.807     albertel   54: use LONCAPA qw(:DEFAULT :match);
1.740     www        55: use LONCAPA::Configuration;
1.676     albertel   56: 
1.195     www        57: my $readit;
1.550     foxr       58: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel   59: 
1.619     albertel   60: require Exporter;
                     61: 
                     62: our @ISA = qw (Exporter);
                     63: our @EXPORT = qw(%env);
                     64: 
1.449     matthew    65: =pod
                     66: 
                     67: =head1 Package Variables
                     68: 
                     69: These are largely undocumented, so if you decipher one please note it here.
                     70: 
                     71: =over 4
                     72: 
                     73: =item $processmarker
                     74: 
                     75: Contains the time this process was started and this servers host id.
                     76: 
                     77: =item $dumpcount
                     78: 
                     79: Counts the number of times a message log flush has been attempted (regardless
                     80: of success) by this process.  Used as part of the filename when messages are
                     81: delayed.
                     82: 
                     83: =back
                     84: 
                     85: =cut
                     86: 
                     87: 
1.1       albertel   88: # --------------------------------------------------------------------- Logging
1.729     www        89: {
                     90:     my $logid;
                     91:     sub instructor_log {
                     92: 	my ($hash_name,$storehash,$delflag,$uname,$udom)=@_;
                     93: 	$logid++;
                     94: 	my $id=time().'00000'.$$.'00000'.$logid;
                     95: 	return &Apache::lonnet::put('nohist_'.$hash_name,
1.730     www        96: 				    { $id => {
                     97: 					'exe_uname' => $env{'user.name'},
                     98: 					'exe_udom'  => $env{'user.domain'},
                     99: 					'exe_time'  => time(),
                    100: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    101: 					'delflag'   => $delflag,
                    102: 					'logentry'  => $storehash,
                    103: 					'uname'     => $uname,
                    104: 					'udom'      => $udom,
                    105: 				    }
                    106: 				  },
1.729     www       107: 				    $env{'course.'.$env{'request.course.id'}.'.domain'},
                    108: 				    $env{'course.'.$env{'request.course.id'}.'.num'}
                    109: 				    );
                    110:     }
                    111: }
1.1       albertel  112: 
1.163     harris41  113: sub logtouch {
                    114:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  115:     unless (-e "$execdir/logs/lonnet.log") {	
                    116: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  117: 	close $fh;
                    118:     }
                    119:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    120:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    121: }
                    122: 
1.1       albertel  123: sub logthis {
                    124:     my $message=shift;
                    125:     my $execdir=$perlvar{'lonDaemons'};
                    126:     my $now=time;
                    127:     my $local=localtime($now);
1.448     albertel  128:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
                    129: 	print $fh "$local ($$): $message\n";
                    130: 	close($fh);
                    131:     }
1.1       albertel  132:     return 1;
                    133: }
                    134: 
                    135: sub logperm {
                    136:     my $message=shift;
                    137:     my $execdir=$perlvar{'lonDaemons'};
                    138:     my $now=time;
                    139:     my $local=localtime($now);
1.448     albertel  140:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    141: 	print $fh "$now:$message:$local\n";
                    142: 	close($fh);
                    143:     }
1.1       albertel  144:     return 1;
                    145: }
                    146: 
1.850     albertel  147: sub create_connection {
1.853     albertel  148:     my ($hostname,$lonid) = @_;
1.851     albertel  149:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  150: 				     Type    => SOCK_STREAM,
                    151: 				     Timeout => 10);
                    152:     return 0 if (!$client);
1.854     albertel  153:     print $client (join(':',$hostname,$lonid,&machine_ids($lonid))."\n");
1.850     albertel  154:     my $result = <$client>;
                    155:     chomp($result);
                    156:     return 1 if ($result eq 'done');
                    157:     return 0;
                    158: }
                    159: 
                    160: 
1.1       albertel  161: # -------------------------------------------------- Non-critical communication
                    162: sub subreply {
                    163:     my ($cmd,$server)=@_;
1.838     albertel  164:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      165:     #
                    166:     #  With loncnew process trimming, there's a timing hole between lonc server
                    167:     #  process exit and the master server picking up the listen on the AF_UNIX
                    168:     #  socket.  In that time interval, a lock file will exist:
                    169: 
                    170:     my $lockfile=$peerfile.".lock";
                    171:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    172: 	sleep(1);
                    173:     }
                    174:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      175:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      176:     #
1.550     foxr      177:     #   We'll give the connection a few tries before abandoning it.  If
                    178:     #   connection is not possible, we'll con_lost back to the client.
                    179:     #   
                    180:     my $client;
                    181:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    182: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    183: 				      Type    => SOCK_STREAM,
                    184: 				      Timeout => 10);
                    185: 	if($client) {
                    186: 	    last;		# Connected!
1.850     albertel  187: 	} else {
1.853     albertel  188: 	    &create_connection(&hostname($server),$server);
1.550     foxr      189: 	}
1.850     albertel  190:         sleep(1);		# Try again later if failed connection.
1.550     foxr      191:     }
                    192:     my $answer;
                    193:     if ($client) {
1.704     albertel  194: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      195: 	$answer=<$client>;
                    196: 	if (!$answer) { $answer="con_lost"; }
                    197: 	chomp($answer);
                    198:     } else {
                    199: 	$answer = 'con_lost';	# Failed connection.
                    200:     }
1.1       albertel  201:     return $answer;
                    202: }
                    203: 
                    204: sub reply {
                    205:     my ($cmd,$server)=@_;
1.838     albertel  206:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  207:     my $answer=subreply($cmd,$server);
1.65      www       208:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  209:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       210:                 " $cmd to $server returned $answer</font>");
                    211:     }
1.1       albertel  212:     return $answer;
                    213: }
                    214: 
                    215: # ----------------------------------------------------------- Send USR1 to lonc
                    216: 
                    217: sub reconlonc {
1.836     www       218:     &logthis("Trying to reconnect lonc");
1.1       albertel  219:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  220:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  221: 	my $loncpid=<$fh>;
                    222:         chomp($loncpid);
                    223:         if (kill 0 => $loncpid) {
                    224: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    225:             kill USR1 => $loncpid;
                    226:             sleep 1;
1.836     www       227:          } else {
1.12      www       228: 	    &logthis(
1.672     albertel  229:                "<font color=\"blue\">WARNING:".
1.12      www       230:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  231:         }
                    232:     } else {
1.836     www       233: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  234:     }
                    235: }
                    236: 
                    237: # ------------------------------------------------------ Critical communication
1.12      www       238: 
1.1       albertel  239: sub critical {
                    240:     my ($cmd,$server)=@_;
1.838     albertel  241:     unless (&hostname($server)) {
1.672     albertel  242:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       243:                " Critical message to unknown server ($server)</font>");
                    244:         return 'no_such_host';
                    245:     }
1.1       albertel  246:     my $answer=reply($cmd,$server);
                    247:     if ($answer eq 'con_lost') {
                    248: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  249: 	my $answer=reply($cmd,$server);
1.1       albertel  250:         if ($answer eq 'con_lost') {
                    251:             my $now=time;
                    252:             my $middlename=$cmd;
1.5       www       253:             $middlename=substr($middlename,0,16);
1.1       albertel  254:             $middlename=~s/\W//g;
                    255:             my $dfilename=
1.305     www       256:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    257:             $dumpcount++;
1.1       albertel  258:             {
1.448     albertel  259: 		my $dfh;
                    260: 		if (open($dfh,">$dfilename")) {
                    261: 		    print $dfh "$cmd\n"; 
                    262: 		    close($dfh);
                    263: 		}
1.1       albertel  264:             }
                    265:             sleep 2;
                    266:             my $wcmd='';
                    267:             {
1.448     albertel  268: 		my $dfh;
                    269: 		if (open($dfh,"<$dfilename")) {
                    270: 		    $wcmd=<$dfh>; 
                    271: 		    close($dfh);
                    272: 		}
1.1       albertel  273:             }
                    274:             chomp($wcmd);
1.7       www       275:             if ($wcmd eq $cmd) {
1.672     albertel  276: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       277:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  278:                 &logperm("D:$server:$cmd");
                    279: 	        return 'con_delayed';
                    280:             } else {
1.672     albertel  281:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       282:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  283:                 &logperm("F:$server:$cmd");
                    284:                 return 'con_failed';
                    285:             }
                    286:         }
                    287:     }
                    288:     return $answer;
1.405     albertel  289: }
                    290: 
1.755     albertel  291: # ------------------------------------------- check if return value is an error
                    292: 
                    293: sub error {
                    294:     my ($result) = @_;
1.756     albertel  295:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  296: 	if ($2 == 2) { return undef; }
                    297: 	return $1;
                    298:     }
                    299:     return undef;
                    300: }
                    301: 
1.783     albertel  302: sub convert_and_load_session_env {
                    303:     my ($lonidsdir,$handle)=@_;
                    304:     my @profile;
                    305:     {
                    306: 	open(my $idf,"$lonidsdir/$handle.id");
                    307: 	flock($idf,LOCK_SH);
                    308: 	@profile=<$idf>;
                    309: 	close($idf);
                    310:     }
                    311:     my %temp_env;
                    312:     foreach my $line (@profile) {
1.786     albertel  313: 	if ($line !~ m/=/) {
                    314: 	    return 0;
                    315: 	}
1.783     albertel  316: 	chomp($line);
                    317: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    318: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    319:     }
                    320:     unlink("$lonidsdir/$handle.id");
                    321:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    322: 	    0640)) {
                    323: 	%disk_env = %temp_env;
                    324: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    325: 	untie(%disk_env);
                    326:     }
1.786     albertel  327:     return 1;
1.783     albertel  328: }
                    329: 
1.374     www       330: # ------------------------------------------- Transfer profile into environment
1.780     albertel  331: my $env_loaded;
                    332: sub transfer_profile_to_env {
1.788     albertel  333:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    334:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       335: 
1.720     albertel  336:     if (!defined($lonidsdir)) {
                    337: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    338:     }
                    339:     if (!defined($handle)) {
                    340:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    341:     }
                    342: 
1.786     albertel  343:     my $convert;
                    344:     {
                    345:     	open(my $idf,"$lonidsdir/$handle.id");
                    346: 	flock($idf,LOCK_SH);
                    347: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    348: 		&GDBM_READER(),0640)) {
                    349: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    350: 	    untie(%disk_env);
                    351: 	} else {
                    352: 	    $convert = 1;
                    353: 	}
                    354:     }
                    355:     if ($convert) {
                    356: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    357: 	    &logthis("Failed to load session, or convert session.");
                    358: 	}
1.374     www       359:     }
1.783     albertel  360: 
1.786     albertel  361:     my %remove;
1.783     albertel  362:     while ( my $envname = each(%env) ) {
1.433     matthew   363:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    364:             if ($time < time-300) {
1.783     albertel  365:                 $remove{$key}++;
1.433     matthew   366:             }
                    367:         }
                    368:     }
1.783     albertel  369: 
1.619     albertel  370:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  371:     $env_loaded=1;
1.783     albertel  372:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   373:         &delenv($expired_key);
1.374     www       374:     }
1.1       albertel  375: }
                    376: 
1.830     albertel  377: sub timed_flock {
                    378:     my ($file,$lock_type) = @_;
                    379:     my $failed=0;
                    380:     eval {
                    381: 	local $SIG{__DIE__}='DEFAULT';
                    382: 	local $SIG{ALRM}=sub {
                    383: 	    $failed=1;
                    384: 	    die("failed lock");
                    385: 	};
                    386: 	alarm(13);
                    387: 	flock($file,$lock_type);
                    388: 	alarm(0);
                    389:     };
                    390:     if ($failed) {
                    391: 	return undef;
                    392:     } else {
                    393: 	return 1;
                    394:     }
                    395: }
                    396: 
1.5       www       397: # ---------------------------------------------------------- Append Environment
                    398: 
                    399: sub appenv {
1.6       www       400:     my %newenv=@_;
1.692     albertel  401:     foreach my $key (keys(%newenv)) {
                    402: 	if (($newenv{$key}=~/^user\.role/) || ($newenv{$key}=~/^user\.priv/)) {
1.672     albertel  403:             &logthis("<font color=\"blue\">WARNING: ".
1.692     albertel  404:                 "Attempt to modify environment ".$key." to ".$newenv{$key}
1.151     www       405:                 .'</font>');
1.692     albertel  406: 	    delete($newenv{$key});
1.35      www       407:         } else {
1.692     albertel  408:             $env{$key}=$newenv{$key};
1.35      www       409:         }
1.191     harris41  410:     }
1.830     albertel  411:     open(my $env_file,$env{'user.environment'});
                    412:     if (&timed_flock($env_file,LOCK_EX)
                    413: 	&&
                    414: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    415: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  416: 	while (my ($key,$value) = each(%newenv)) {
                    417: 	    $disk_env{$key} = $value;
1.448     albertel  418: 	}
1.783     albertel  419: 	untie(%disk_env);
1.56      www       420:     }
                    421:     return 'ok';
                    422: }
                    423: # ----------------------------------------------------- Delete from Environment
                    424: 
                    425: sub delenv {
                    426:     my $delthis=shift;
                    427:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672     albertel  428:         &logthis("<font color=\"blue\">WARNING: ".
1.56      www       429:                 "Attempt to delete from environment ".$delthis);
                    430:         return 'error';
                    431:     }
1.830     albertel  432:     open(my $env_file,$env{'user.environment'});
                    433:     if (&timed_flock($env_file,LOCK_EX)
                    434: 	&&
                    435: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    436: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  437: 	foreach my $key (keys(%disk_env)) {
                    438: 	    if ($key=~/^$delthis/) { 
1.619     albertel  439:                 delete($env{$key});
1.783     albertel  440:                 delete($disk_env{$key});
1.473     matthew   441:             }
1.448     albertel  442: 	}
1.783     albertel  443: 	untie(%disk_env);
1.5       www       444:     }
                    445:     return 'ok';
1.369     albertel  446: }
                    447: 
1.790     albertel  448: sub get_env_multiple {
                    449:     my ($name) = @_;
                    450:     my @values;
                    451:     if (defined($env{$name})) {
                    452:         # exists is it an array
                    453:         if (ref($env{$name})) {
                    454:             @values=@{ $env{$name} };
                    455:         } else {
                    456:             $values[0]=$env{$name};
                    457:         }
                    458:     }
                    459:     return(@values);
                    460: }
                    461: 
1.369     albertel  462: # ------------------------------------------ Find out current server userload
                    463: # there is a copy in lond
                    464: sub userload {
                    465:     my $numusers=0;
                    466:     {
                    467: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    468: 	my $filename;
                    469: 	my $curtime=time;
                    470: 	while ($filename=readdir(LONIDS)) {
                    471: 	    if ($filename eq '.' || $filename eq '..') {next;}
1.404     albertel  472: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  473: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  474: 	}
                    475: 	closedir(LONIDS);
                    476:     }
                    477:     my $userloadpercent=0;
                    478:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    479:     if ($maxuserload) {
1.371     albertel  480: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  481:     }
1.372     albertel  482:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  483:     return $userloadpercent;
1.283     www       484: }
                    485: 
                    486: # ------------------------------------------ Fight off request when overloaded
                    487: 
                    488: sub overloaderror {
                    489:     my ($r,$checkserver)=@_;
                    490:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
                    491:     my $loadavg;
                    492:     if ($checkserver eq $perlvar{'lonHostID'}) {
1.448     albertel  493:        open(my $loadfile,'/proc/loadavg');
1.283     www       494:        $loadavg=<$loadfile>;
                    495:        $loadavg =~ s/\s.*//g;
1.285     matthew   496:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448     albertel  497:        close($loadfile);
1.283     www       498:     } else {
                    499:        $loadavg=&reply('load',$checkserver);
                    500:     }
1.285     matthew   501:     my $overload=$loadavg-100;
1.283     www       502:     if ($overload>0) {
1.285     matthew   503: 	$r->err_headers_out->{'Retry-After'}=$overload;
1.283     www       504:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554     www       505:         return 413;
1.283     www       506:     }    
                    507:     return '';
1.5       www       508: }
1.1       albertel  509: 
                    510: # ------------------------------ Find server with least workload from spare.tab
1.11      www       511: 
1.1       albertel  512: sub spareserver {
1.670     albertel  513:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.784     albertel  514:     my $spare_server;
1.370     albertel  515:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  516:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    517:                                                      :  $userloadpercent;
                    518:     
                    519:     foreach my $try_server (@{ $spareid{'primary'} }) {
                    520: 	($spare_server, $lowest_load) =
                    521: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
                    522:     }
                    523: 
                    524:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    525: 
                    526:     if (!$found_server) {
                    527: 	foreach my $try_server (@{ $spareid{'default'} }) {
                    528: 	    ($spare_server, $lowest_load) =
                    529: 		&compare_server_load($try_server, $spare_server, $lowest_load);
                    530: 	}
                    531:     }
                    532: 
                    533:     if (!$want_server_name) {
1.838     albertel  534: 	$spare_server="http://".&hostname($spare_server);
1.784     albertel  535:     }
                    536:     return $spare_server;
                    537: }
                    538: 
                    539: sub compare_server_load {
                    540:     my ($try_server, $spare_server, $lowest_load) = @_;
                    541: 
                    542:     my $loadans     = &reply('load',    $try_server);
                    543:     my $userloadans = &reply('userload',$try_server);
                    544: 
                    545:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
                    546: 	next; #didn't get a number from the server
                    547:     }
                    548: 
                    549:     my $load;
                    550:     if ($loadans =~ /\d/) {
                    551: 	if ($userloadans =~ /\d/) {
                    552: 	    #both are numbers, pick the bigger one
                    553: 	    $load = ($loadans > $userloadans) ? $loadans 
                    554: 		                              : $userloadans;
1.411     albertel  555: 	} else {
1.784     albertel  556: 	    $load = $loadans;
1.411     albertel  557: 	}
1.784     albertel  558:     } else {
                    559: 	$load = $userloadans;
                    560:     }
                    561: 
                    562:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    563: 	$spare_server = $try_server;
                    564: 	$lowest_load  = $load;
1.370     albertel  565:     }
1.784     albertel  566:     return ($spare_server,$lowest_load);
1.202     matthew   567: }
                    568: # --------------------------------------------- Try to change a user's password
                    569: 
                    570: sub changepass {
1.799     raeburn   571:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   572:     $currentpass = &escape($currentpass);
                    573:     $newpass     = &escape($newpass);
1.799     raeburn   574:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
1.202     matthew   575: 		       $server);
                    576:     if (! $answer) {
                    577: 	&logthis("No reply on password change request to $server ".
                    578: 		 "by $uname in domain $udom.");
                    579:     } elsif ($answer =~ "^ok") {
                    580:         &logthis("$uname in $udom successfully changed their password ".
                    581: 		 "on $server.");
                    582:     } elsif ($answer =~ "^pwchange_failure") {
                    583: 	&logthis("$uname in $udom was unable to change their password ".
                    584: 		 "on $server.  The action was blocked by either lcpasswd ".
                    585: 		 "or pwchange");
                    586:     } elsif ($answer =~ "^non_authorized") {
                    587:         &logthis("$uname in $udom did not get their password correct when ".
                    588: 		 "attempting to change it on $server.");
                    589:     } elsif ($answer =~ "^auth_mode_error") {
                    590:         &logthis("$uname in $udom attempted to change their password despite ".
                    591: 		 "not being locally or internally authenticated on $server.");
                    592:     } elsif ($answer =~ "^unknown_user") {
                    593:         &logthis("$uname in $udom attempted to change their password ".
                    594: 		 "on $server but were unable to because $server is not ".
                    595: 		 "their home server.");
                    596:     } elsif ($answer =~ "^refused") {
                    597: 	&logthis("$server refused to change $uname in $udom password because ".
                    598: 		 "it was sent an unencrypted request to change the password.");
                    599:     }
                    600:     return $answer;
1.1       albertel  601: }
                    602: 
1.169     harris41  603: # ----------------------- Try to determine user's current authentication scheme
                    604: 
                    605: sub queryauthenticate {
                    606:     my ($uname,$udom)=@_;
1.456     albertel  607:     my $uhome=&homeserver($uname,$udom);
                    608:     if (!$uhome) {
                    609: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                    610: 	return 'no_host';
                    611:     }
                    612:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                    613:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                    614: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41  615:     }
1.456     albertel  616:     return $answer;
1.169     harris41  617: }
                    618: 
1.1       albertel  619: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       620: 
1.1       albertel  621: sub authenticate {
                    622:     my ($uname,$upass,$udom)=@_;
1.807     albertel  623:     $upass=&escape($upass);
                    624:     $uname= &LONCAPA::clean_username($uname);
1.836     www       625:     my $uhome=&homeserver($uname,$udom,1);
                    626:     if ((!$uhome) || ($uhome eq 'no_host')) {
                    627: # Maybe the machine was offline and only re-appeared again recently?
                    628:         &reconlonc();
                    629: # One more
                    630: 	my $uhome=&homeserver($uname,$udom,1);
                    631: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                    632: 	    &logthis("User $uname at $udom is unknown in authenticate");
                    633: 	}
1.471     albertel  634: 	return 'no_host';
1.1       albertel  635:     }
1.471     albertel  636:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
                    637:     if ($answer eq 'authorized') {
                    638: 	&logthis("User $uname at $udom authorized by $uhome"); 
                    639: 	return $uhome; 
                    640:     }
                    641:     if ($answer eq 'non_authorized') {
                    642: 	&logthis("User $uname at $udom rejected by $uhome");
                    643: 	return 'no_host'; 
1.9       www       644:     }
1.471     albertel  645:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel  646:     return 'no_host';
                    647: }
                    648: 
                    649: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www       650: 
1.599     albertel  651: my %homecache;
1.1       albertel  652: sub homeserver {
1.230     stredwic  653:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel  654:     my $index="$uname:$udom";
1.426     albertel  655: 
1.599     albertel  656:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel  657: 
                    658:     my %servers = &get_servers($udom,'library');
                    659:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic  660:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic  661: 		 exists($badServerCache{$tryserver}));
1.841     albertel  662: 
                    663: 	my $answer=reply("home:$udom:$uname",$tryserver);
                    664: 	if ($answer eq 'found') {
                    665: 	    delete($badServerCache{$tryserver}); 
                    666: 	    return $homecache{$index}=$tryserver;
                    667: 	} elsif ($answer eq 'no_host') {
                    668: 	    $badServerCache{$tryserver}=1;
                    669: 	}
1.1       albertel  670:     }    
                    671:     return 'no_host';
1.70      www       672: }
                    673: 
                    674: # ------------------------------------- Find the usernames behind a list of IDs
                    675: 
                    676: sub idget {
                    677:     my ($udom,@ids)=@_;
                    678:     my %returnhash=();
                    679:     
1.841     albertel  680:     my %servers = &get_servers($udom,'library');
                    681:     foreach my $tryserver (keys(%servers)) {
                    682: 	my $idlist=join('&',@ids);
                    683: 	$idlist=~tr/A-Z/a-z/; 
                    684: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                    685: 	my @answer=();
                    686: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                    687: 	    @answer=split(/\&/,$reply);
                    688: 	}                    ;
                    689: 	my $i;
                    690: 	for ($i=0;$i<=$#ids;$i++) {
                    691: 	    if ($answer[$i]) {
                    692: 		$returnhash{$ids[$i]}=$answer[$i];
                    693: 	    } 
                    694: 	}
                    695:     } 
1.70      www       696:     return %returnhash;
                    697: }
                    698: 
                    699: # ------------------------------------- Find the IDs behind a list of usernames
                    700: 
                    701: sub idrget {
                    702:     my ($udom,@unames)=@_;
                    703:     my %returnhash=();
1.800     albertel  704:     foreach my $uname (@unames) {
                    705:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41  706:     }
1.70      www       707:     return %returnhash;
                    708: }
                    709: 
                    710: # ------------------------------- Store away a list of names and associated IDs
                    711: 
                    712: sub idput {
                    713:     my ($udom,%ids)=@_;
                    714:     my %servers=();
1.800     albertel  715:     foreach my $uname (keys(%ids)) {
                    716: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                    717:         my $uhom=&homeserver($uname,$udom);
1.70      www       718:         if ($uhom ne 'no_host') {
1.800     albertel  719:             my $id=&escape($ids{$uname});
1.70      www       720:             $id=~tr/A-Z/a-z/;
1.800     albertel  721:             my $esc_unam=&escape($uname);
1.70      www       722: 	    if ($servers{$uhom}) {
1.800     albertel  723: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www       724:             } else {
1.800     albertel  725:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www       726:             }
                    727:         }
1.191     harris41  728:     }
1.800     albertel  729:     foreach my $server (keys(%servers)) {
                    730:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41  731:     }
1.344     www       732: }
                    733: 
1.806     raeburn   734: # ------------------------------------------- get items from domain db files   
                    735: 
                    736: sub get_dom {
                    737:     my ($namespace,$storearr,$udom)=@_;
                    738:     my $items='';
                    739:     foreach my $item (@$storearr) {
                    740:         $items.=&escape($item).'&';
                    741:     }
                    742:     $items=~s/\&$//;
                    743:     if (!$udom) { $udom=$env{'user.domain'}; }
1.846     albertel  744:     if (defined(&domain($udom,'primary'))) {
                    745:         my $uhome=&domain($udom,'primary');
1.806     raeburn   746:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
                    747:         my @pairs=split(/\&/,$rep);
                    748:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                    749:             return @pairs;
                    750:         }
                    751:         my %returnhash=();
                    752:         my $i=0;
                    753:         foreach my $item (@$storearr) {
                    754:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                    755:             $i++;
                    756:         }
                    757:         return %returnhash;
                    758:     } else {
                    759:         &logthis("get_dom failed - no primary domain server for $udom");
                    760:     }
                    761: }
                    762: 
                    763: # -------------------------------------------- put items in domain db files 
                    764: 
                    765: sub put_dom {
                    766:     my ($namespace,$storehash,$udom)=@_;
                    767:     if (!$udom) { $udom=$env{'user.domain'}; }
1.846     albertel  768:     if (defined(&domain($udom,'primary'))) {
                    769:         my $uhome=&domain($udom,'primary');
1.806     raeburn   770:         my $items='';
                    771:         foreach my $item (keys(%$storehash)) {
                    772:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                    773:         }
                    774:         $items=~s/\&$//;
                    775:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                    776:     } else {
                    777:         &logthis("put_dom failed - no primary domain server for $udom");
                    778:     }
                    779: }
                    780: 
1.837     raeburn   781: sub retrieve_inst_usertypes {
                    782:     my ($udom) = @_;
                    783:     my (%returnhash,@order);
1.846     albertel  784:     if (defined(&domain($udom,'primary'))) {
                    785:         my $uhome=&domain($udom,'primary');
1.837     raeburn   786:         my $rep=&reply("inst_usertypes:$udom",$uhome);
                    787:         my ($hashitems,$orderitems) = split(/:/,$rep); 
                    788:         my @pairs=split(/\&/,$hashitems);
                    789:         foreach my $item (@pairs) {
                    790:             my ($key,$value)=split(/=/,$item,2);
                    791:             $key = &unescape($key);
                    792:             next if ($key =~ /^error: 2 /);
                    793:             $returnhash{$key}=&thaw_unescape($value);
                    794:         }
                    795:         my @esc_order = split(/\&/,$orderitems);
                    796:         foreach my $item (@esc_order) {
                    797:             push(@order,&unescape($item));
                    798:         }
                    799:     } else {
                    800:         &logthis("get_dom failed - no primary domain server for $udom");
                    801:     }
                    802:     return (\%returnhash,\@order);
                    803: }
                    804: 
1.344     www       805: # --------------------------------------------------- Assign a key to a student
                    806: 
                    807: sub assign_access_key {
1.364     www       808: #
                    809: # a valid key looks like uname:udom#comments
                    810: # comments are being appended
                    811: #
1.498     www       812:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                    813:     $kdom=
1.620     albertel  814:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www       815:     $knum=
1.620     albertel  816:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www       817:     $cdom=
1.620     albertel  818:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       819:     $cnum=
1.620     albertel  820:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    821:     $udom=$env{'user.name'} unless (defined($udom));
                    822:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www       823:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www       824:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel  825:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www       826:                                                   # assigned to this person
                    827:                                                   # - this should not happen,
1.345     www       828:                                                   # unless something went wrong
                    829:                                                   # the first time around
                    830: # ready to assign
1.364     www       831:         $logentry=$1.'; '.$logentry;
1.496     www       832:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www       833:                                                  $kdom,$knum) eq 'ok') {
1.345     www       834: # key now belongs to user
1.346     www       835: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www       836:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
                    837:                 &appenv('environment.'.$envkey => $ckey);
                    838:                 return 'ok';
                    839:             } else {
                    840:                 return 
                    841:   'error: Count not permanently assign key, will need to be re-entered later.';
                    842: 	    }
                    843:         } else {
                    844:             return 'error: Could not assign key, try again later.';
                    845:         }
1.364     www       846:     } elsif (!$existing{$ckey}) {
1.345     www       847: # the key does not exist
                    848: 	return 'error: The key does not exist';
                    849:     } else {
                    850: # the key is somebody else's
                    851: 	return 'error: The key is already in use';
                    852:     }
1.344     www       853: }
                    854: 
1.364     www       855: # ------------------------------------------ put an additional comment on a key
                    856: 
                    857: sub comment_access_key {
                    858: #
                    859: # a valid key looks like uname:udom#comments
                    860: # comments are being appended
                    861: #
                    862:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                    863:     $cdom=
1.620     albertel  864:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www       865:     $cnum=
1.620     albertel  866:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www       867:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                    868:     if ($existing{$ckey}) {
                    869:         $existing{$ckey}.='; '.$logentry;
                    870: # ready to assign
1.367     www       871:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www       872:                                                  $cdom,$cnum) eq 'ok') {
                    873: 	    return 'ok';
                    874:         } else {
                    875: 	    return 'error: Count not store comment.';
                    876:         }
                    877:     } else {
                    878: # the key does not exist
                    879: 	return 'error: The key does not exist';
                    880:     }
                    881: }
                    882: 
1.344     www       883: # ------------------------------------------------------ Generate a set of keys
                    884: 
                    885: sub generate_access_keys {
1.364     www       886:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www       887:     $cdom=
1.620     albertel  888:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       889:     $cnum=
1.620     albertel  890:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www       891:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www       892:     unless (($cdom) && ($cnum)) { return 0; }
                    893:     if ($number>10000) { return 0; }
                    894:     sleep(2); # make sure don't get same seed twice
                    895:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                    896:     my $total=0;
                    897:     for (my $i=1;$i<=$number;$i++) {
                    898:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                    899:                   sprintf("%lx",int(100000*rand)).'-'.
                    900:                   sprintf("%lx",int(100000*rand));
                    901:        $newkey=~s/1/g/g; # folks mix up 1 and l
                    902:        $newkey=~s/0/h/g; # and also 0 and O
                    903:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                    904:        if ($existing{$newkey}) {
                    905:            $i--;
                    906:        } else {
1.364     www       907: 	  if (&put('accesskeys',
                    908:               { $newkey => '# generated '.localtime().
1.620     albertel  909:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www       910:                            '; '.$logentry },
                    911: 		   $cdom,$cnum) eq 'ok') {
1.344     www       912:               $total++;
                    913: 	  }
                    914:        }
                    915:     }
1.620     albertel  916:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www       917:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                    918:     return $total;
                    919: }
                    920: 
                    921: # ------------------------------------------------------- Validate an accesskey
                    922: 
                    923: sub validate_access_key {
                    924:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                    925:     $cdom=
1.620     albertel  926:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       927:     $cnum=
1.620     albertel  928:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    929:     $udom=$env{'user.domain'} unless (defined($udom));
                    930:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www       931:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel  932:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www       933: }
                    934: 
                    935: # ------------------------------------- Find the section of student in a course
1.652     albertel  936: sub devalidate_getsection_cache {
                    937:     my ($udom,$unam,$courseid)=@_;
                    938:     my $hashid="$udom:$unam:$courseid";
                    939:     &devalidate_cache_new('getsection',$hashid);
                    940: }
1.298     matthew   941: 
1.815     albertel  942: sub courseid_to_courseurl {
                    943:     my ($courseid) = @_;
                    944:     #already url style courseid
                    945:     return $courseid if ($courseid =~ m{^/});
                    946: 
                    947:     if (exists($env{'course.'.$courseid.'.num'})) {
                    948: 	my $cnum = $env{'course.'.$courseid.'.num'};
                    949: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                    950: 	return "/$cdom/$cnum";
                    951:     }
                    952: 
                    953:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                    954:     if (exists($courseinfo{'num'})) {
                    955: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                    956:     }
                    957: 
                    958:     return undef;
                    959: }
                    960: 
1.298     matthew   961: sub getsection {
                    962:     my ($udom,$unam,$courseid)=@_;
1.599     albertel  963:     my $cachetime=1800;
1.551     albertel  964: 
                    965:     my $hashid="$udom:$unam:$courseid";
1.599     albertel  966:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel  967:     if (defined($cached)) { return $result; }
                    968: 
1.298     matthew   969:     my %Pending; 
                    970:     my %Expired;
                    971:     #
                    972:     # Each role can either have not started yet (pending), be active, 
                    973:     #    or have expired.
                    974:     #
                    975:     # If there is an active role, we are done.
                    976:     #
                    977:     # If there is more than one role which has not started yet, 
                    978:     #     choose the one which will start sooner
                    979:     # If there is one role which has not started yet, return it.
                    980:     #
                    981:     # If there is more than one expired role, choose the one which ended last.
                    982:     # If there is a role which has expired, return it.
                    983:     #
1.815     albertel  984:     $courseid = &courseid_to_courseurl($courseid);
1.817     raeburn   985:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
                    986:     foreach my $key (keys(%roleshash)) {
1.479     albertel  987:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew   988:         my $section=$1;
                    989:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn   990:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew   991:         my $now=time;
1.548     albertel  992:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew   993:             $Expired{$end}=$section;
                    994:             next;
                    995:         }
1.548     albertel  996:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew   997:             $Pending{$start}=$section;
                    998:             next;
                    999:         }
1.599     albertel 1000:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  1001:     }
                   1002:     #
                   1003:     # Presumedly there will be few matching roles from the above
                   1004:     # loop and the sorting time will be negligible.
                   1005:     if (scalar(keys(%Pending))) {
                   1006:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 1007:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  1008:     } 
                   1009:     if (scalar(keys(%Expired))) {
                   1010:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   1011:         my $time = pop(@sorted);
1.599     albertel 1012:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  1013:     }
1.599     albertel 1014:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  1015: }
1.70      www      1016: 
1.599     albertel 1017: sub save_cache {
                   1018:     &purge_remembered();
1.722     albertel 1019:     #&Apache::loncommon::validate_page();
1.620     albertel 1020:     undef(%env);
1.780     albertel 1021:     undef($env_loaded);
1.599     albertel 1022: }
1.452     albertel 1023: 
1.599     albertel 1024: my $to_remember=-1;
                   1025: my %remembered;
                   1026: my %accessed;
                   1027: my $kicks=0;
                   1028: my $hits=0;
1.849     albertel 1029: sub make_key {
                   1030:     my ($name,$id) = @_;
                   1031:     if (length($id) > 200) { $id=length($id).':'.&Digest::MD5::md5_hex($id); }
                   1032:     return &escape($name.':'.$id);
                   1033: }
                   1034: 
1.599     albertel 1035: sub devalidate_cache_new {
                   1036:     my ($name,$id,$debug) = @_;
                   1037:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 1038:     $id=&make_key($name,$id);
1.599     albertel 1039:     $memcache->delete($id);
                   1040:     delete($remembered{$id});
                   1041:     delete($accessed{$id});
                   1042: }
                   1043: 
                   1044: sub is_cached_new {
                   1045:     my ($name,$id,$debug) = @_;
1.849     albertel 1046:     $id=&make_key($name,$id);
1.599     albertel 1047:     if (exists($remembered{$id})) {
                   1048: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                   1049: 	$accessed{$id}=[&gettimeofday()];
                   1050: 	$hits++;
                   1051: 	return ($remembered{$id},1);
                   1052:     }
                   1053:     my $value = $memcache->get($id);
                   1054:     if (!(defined($value))) {
                   1055: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 1056: 	return (undef,undef);
1.416     albertel 1057:     }
1.599     albertel 1058:     if ($value eq '__undef__') {
                   1059: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   1060: 	$value=undef;
                   1061:     }
                   1062:     &make_room($id,$value,$debug);
                   1063:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   1064:     return ($value,1);
                   1065: }
                   1066: 
                   1067: sub do_cache_new {
                   1068:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 1069:     $id=&make_key($name,$id);
1.599     albertel 1070:     my $setvalue=$value;
                   1071:     if (!defined($setvalue)) {
                   1072: 	$setvalue='__undef__';
                   1073:     }
1.623     albertel 1074:     if (!defined($time) ) {
                   1075: 	$time=600;
                   1076:     }
1.599     albertel 1077:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.600     albertel 1078:     $memcache->set($id,$setvalue,$time);
                   1079:     # need to make a copy of $value
                   1080:     #&make_room($id,$value,$debug);
1.599     albertel 1081:     return $value;
                   1082: }
                   1083: 
                   1084: sub make_room {
                   1085:     my ($id,$value,$debug)=@_;
                   1086:     $remembered{$id}=$value;
                   1087:     if ($to_remember<0) { return; }
                   1088:     $accessed{$id}=[&gettimeofday()];
                   1089:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   1090:     my $to_kick;
                   1091:     my $max_time=0;
                   1092:     foreach my $other (keys(%accessed)) {
                   1093: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   1094: 	    $to_kick=$other;
                   1095: 	    $max_time=&tv_interval($accessed{$other});
                   1096: 	}
                   1097:     }
                   1098:     delete($remembered{$to_kick});
                   1099:     delete($accessed{$to_kick});
                   1100:     $kicks++;
                   1101:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 1102:     return;
                   1103: }
                   1104: 
1.599     albertel 1105: sub purge_remembered {
1.604     albertel 1106:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   1107:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 1108:     undef(%remembered);
                   1109:     undef(%accessed);
1.428     albertel 1110: }
1.70      www      1111: # ------------------------------------- Read an entry from a user's environment
                   1112: 
                   1113: sub userenvironment {
                   1114:     my ($udom,$unam,@what)=@_;
                   1115:     my %returnhash=();
                   1116:     my @answer=split(/\&/,
                   1117:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
                   1118:                       &homeserver($unam,$udom)));
                   1119:     my $i;
                   1120:     for ($i=0;$i<=$#what;$i++) {
                   1121: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                   1122:     }
                   1123:     return %returnhash;
1.1       albertel 1124: }
                   1125: 
1.617     albertel 1126: # ---------------------------------------------------------- Get a studentphoto
                   1127: sub studentphoto {
                   1128:     my ($udom,$unam,$ext) = @_;
                   1129:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1130:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1131:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1132:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1133:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1134:             } else {
                   1135:                 my ($result,$perm_reqd)=
1.707     albertel 1136: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1137:                 if ($result eq 'ok') {
                   1138:                     if (!($perm_reqd eq 'yes')) {
                   1139:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1140:                     }
                   1141:                 }
                   1142:             }
                   1143:         }
                   1144:     } else {
                   1145:         my ($result,$perm_reqd) = 
1.707     albertel 1146: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1147:         if ($result eq 'ok') {
                   1148:             if (!($perm_reqd eq 'yes')) {
                   1149:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1150:             }
                   1151:         }
                   1152:     }
                   1153:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1154: }
                   1155: 
                   1156: sub retrievestudentphoto {
                   1157:     my ($udom,$unam,$ext,$type) = @_;
                   1158:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1159:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1160:     if ($ret eq 'ok') {
                   1161:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1162:         if ($type eq 'thumbnail') {
                   1163:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1164:         }
                   1165:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1166:         return $tokenurl;
                   1167:     } else {
                   1168:         if ($type eq 'thumbnail') {
                   1169:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1170:         } else { 
                   1171:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1172:         }
1.617     albertel 1173:     }
                   1174: }
                   1175: 
1.263     www      1176: # -------------------------------------------------------------------- New chat
                   1177: 
                   1178: sub chatsend {
1.724     raeburn  1179:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1180:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1181:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1182:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1183:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1184: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1185: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1186: }
                   1187: 
                   1188: # ------------------------------------------ Find current version of a resource
                   1189: 
                   1190: sub getversion {
                   1191:     my $fname=&clutter(shift);
                   1192:     unless ($fname=~/^\/res\//) { return -1; }
                   1193:     return &currentversion(&filelocation('',$fname));
                   1194: }
                   1195: 
                   1196: sub currentversion {
                   1197:     my $fname=shift;
1.599     albertel 1198:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1199:     if (defined($cached)) { return $result; }
1.292     www      1200:     my $author=$fname;
                   1201:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1202:     my ($udom,$uname)=split(/\//,$author);
                   1203:     my $home=homeserver($uname,$udom);
                   1204:     if ($home eq 'no_host') { 
                   1205:         return -1; 
                   1206:     }
                   1207:     my $answer=reply("currentversion:$fname",$home);
                   1208:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1209: 	return -1;
                   1210:     }
1.599     albertel 1211:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1212: }
                   1213: 
1.1       albertel 1214: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1215: 
1.1       albertel 1216: sub subscribe {
                   1217:     my $fname=shift;
1.761     raeburn  1218:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1219:     $fname=~s/[\n\r]//g;
1.1       albertel 1220:     my $author=$fname;
                   1221:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1222:     my ($udom,$uname)=split(/\//,$author);
                   1223:     my $home=homeserver($uname,$udom);
1.335     albertel 1224:     if ($home eq 'no_host') {
                   1225:         return 'not_found';
1.1       albertel 1226:     }
                   1227:     my $answer=reply("sub:$fname",$home);
1.64      www      1228:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1229: 	$answer.=' by '.$home;
                   1230:     }
1.1       albertel 1231:     return $answer;
                   1232: }
                   1233:     
1.8       www      1234: # -------------------------------------------------------------- Replicate file
                   1235: 
                   1236: sub repcopy {
                   1237:     my $filename=shift;
1.23      www      1238:     $filename=~s/\/+/\//g;
1.607     raeburn  1239:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1240:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1241:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1242: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1243: 	return &repcopy_userfile($filename);
                   1244:     }
1.532     albertel 1245:     $filename=~s/[\n\r]//g;
1.8       www      1246:     my $transname="$filename.in.transfer";
1.828     www      1247: # FIXME: this should flock
1.607     raeburn  1248:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1249:     my $remoteurl=subscribe($filename);
1.64      www      1250:     if ($remoteurl =~ /^con_lost by/) {
                   1251: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1252:            return 'unavailable';
1.8       www      1253:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1254: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1255: 	   return 'not_found';
1.64      www      1256:     } elsif ($remoteurl =~ /^rejected by/) {
                   1257: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1258:            return 'forbidden';
1.20      www      1259:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1260:            return 'ok';
1.8       www      1261:     } else {
1.290     www      1262:         my $author=$filename;
                   1263:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1264:         my ($udom,$uname)=split(/\//,$author);
                   1265:         my $home=homeserver($uname,$udom);
                   1266:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1267:            my @parts=split(/\//,$filename);
                   1268:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1269:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1270:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1271: 	       return 'bad_request';
1.8       www      1272:            }
                   1273:            my $count;
                   1274:            for ($count=5;$count<$#parts;$count++) {
                   1275:                $path.="/$parts[$count]";
                   1276:                if ((-e $path)!=1) {
                   1277: 		   mkdir($path,0777);
                   1278:                }
                   1279:            }
                   1280:            my $ua=new LWP::UserAgent;
                   1281:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1282:            my $response=$ua->request($request,$transname);
                   1283:            if ($response->is_error()) {
                   1284: 	       unlink($transname);
                   1285:                my $message=$response->status_line;
1.672     albertel 1286:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      1287:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1288:                return 'unavailable';
1.8       www      1289:            } else {
1.16      www      1290: 	       if ($remoteurl!~/\.meta$/) {
                   1291:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1292:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1293:                   if ($mresponse->is_error()) {
                   1294: 		      unlink($filename.'.meta');
                   1295:                       &logthis(
1.672     albertel 1296:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      1297:                   }
                   1298: 	       }
1.8       www      1299:                rename($transname,$filename);
1.607     raeburn  1300:                return 'ok';
1.8       www      1301:            }
1.290     www      1302:        }
1.8       www      1303:     }
1.330     www      1304: }
                   1305: 
                   1306: # ------------------------------------------------ Get server side include body
                   1307: sub ssi_body {
1.381     albertel 1308:     my ($filelink,%form)=@_;
1.606     matthew  1309:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1310:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1311:     }
1.330     www      1312:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
1.381     albertel 1313:                                      &ssi($filelink,%form));
1.778     albertel 1314:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1315:     $output=~s/^.*?\<body[^\>]*\>//si;
                   1316:     $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
1.330     www      1317:     return $output;
1.8       www      1318: }
                   1319: 
1.15      www      1320: # --------------------------------------------------------- Server Side Include
                   1321: 
1.782     albertel 1322: sub absolute_url {
                   1323:     my ($host_name) = @_;
                   1324:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   1325:     if ($host_name eq '') {
                   1326: 	$host_name = $ENV{'SERVER_NAME'};
                   1327:     }
                   1328:     return $protocol.$host_name;
                   1329: }
                   1330: 
1.15      www      1331: sub ssi {
                   1332: 
1.23      www      1333:     my ($fn,%form)=@_;
1.15      www      1334: 
                   1335:     my $ua=new LWP::UserAgent;
1.23      www      1336:     
                   1337:     my $request;
1.711     albertel 1338: 
                   1339:     $form{'no_update_last_known'}=1;
                   1340: 
1.23      www      1341:     if (%form) {
1.782     albertel 1342:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.201     albertel 1343:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www      1344:     } else {
1.782     albertel 1345:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      1346:     }
                   1347: 
1.15      www      1348:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1349:     my $response=$ua->request($request);
                   1350: 
1.324     www      1351:     return $response->content;
                   1352: }
                   1353: 
                   1354: sub externalssi {
                   1355:     my ($url)=@_;
                   1356:     my $ua=new LWP::UserAgent;
                   1357:     my $request=new HTTP::Request('GET',$url);
                   1358:     my $response=$ua->request($request);
1.15      www      1359:     return $response->content;
                   1360: }
1.254     www      1361: 
1.492     albertel 1362: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1363: 
                   1364: sub allowuploaded {
                   1365:     my ($srcurl,$url)=@_;
                   1366:     $url=&clutter(&declutter($url));
                   1367:     my $dir=$url;
                   1368:     $dir=~s/\/[^\/]+$//;
                   1369:     my %httpref=();
                   1370:     my $httpurl=&hreflocation('',$url);
                   1371:     $httpref{'httpref.'.$httpurl}=$srcurl;
                   1372:     &Apache::lonnet::appenv(%httpref);
1.254     www      1373: }
1.477     raeburn  1374: 
1.478     albertel 1375: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 1376: # input: action, courseID, current domain, intended
1.637     raeburn  1377: #        path to file, source of file, instruction to parse file for objects,
                   1378: #        ref to hash for embedded objects,
                   1379: #        ref to hash for codebase of java objects.
                   1380: #
1.485     raeburn  1381: # output: url to file (if action was uploaddoc), 
                   1382: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  1383: #
1.478     albertel 1384: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   1385: # course.
1.477     raeburn  1386: #
1.478     albertel 1387: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1388: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   1389: #          course's home server.
1.477     raeburn  1390: #
1.478     albertel 1391: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   1392: #          be copied from $source (current location) to 
                   1393: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1394: #         and will then be copied to
                   1395: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   1396: #         course's home server.
1.485     raeburn  1397: #
1.481     raeburn  1398: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 1399: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  1400: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1401: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   1402: #         in course's home server.
1.637     raeburn  1403: #
1.477     raeburn  1404: 
                   1405: sub process_coursefile {
1.638     albertel 1406:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  1407:     my $fetchresult;
1.638     albertel 1408:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  1409:     if ($action eq 'propagate') {
1.638     albertel 1410:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1411: 			     $home);
1.481     raeburn  1412:     } else {
1.477     raeburn  1413:         my $fpath = '';
                   1414:         my $fname = $file;
1.478     albertel 1415:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  1416:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  1417:         my $filepath = &build_filepath($fpath);
1.481     raeburn  1418:         if ($action eq 'copy') {
                   1419:             if ($source eq '') {
                   1420:                 $fetchresult = 'no source file';
                   1421:                 return $fetchresult;
                   1422:             } else {
                   1423:                 my $destination = $filepath.'/'.$fname;
                   1424:                 rename($source,$destination);
                   1425:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1426:                                  $home);
1.481     raeburn  1427:             }
                   1428:         } elsif ($action eq 'uploaddoc') {
                   1429:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 1430:             print $fh $env{'form.'.$source};
1.481     raeburn  1431:             close($fh);
1.637     raeburn  1432:             if ($parser eq 'parse') {
                   1433:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
                   1434:                 unless ($parse_result eq 'ok') {
                   1435:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   1436:                 }
                   1437:             }
1.477     raeburn  1438:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1439:                                  $home);
1.481     raeburn  1440:             if ($fetchresult eq 'ok') {
                   1441:                 return '/uploaded/'.$fpath.'/'.$fname;
                   1442:             } else {
                   1443:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1444:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  1445:                 return '/adm/notfound.html';
                   1446:             }
1.477     raeburn  1447:         }
                   1448:     }
1.485     raeburn  1449:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  1450:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1451:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  1452:     }
                   1453:     return $fetchresult;
                   1454: }
                   1455: 
1.637     raeburn  1456: sub build_filepath {
                   1457:     my ($fpath) = @_;
                   1458:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   1459:     unless ($fpath eq '') {
                   1460:         my @parts=split('/',$fpath);
                   1461:         foreach my $part (@parts) {
                   1462:             $filepath.= '/'.$part;
                   1463:             if ((-e $filepath)!=1) {
                   1464:                 mkdir($filepath,0777);
                   1465:             }
                   1466:         }
                   1467:     }
                   1468:     return $filepath;
                   1469: }
                   1470: 
                   1471: sub store_edited_file {
1.638     albertel 1472:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  1473:     my $file = $primary_url;
                   1474:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   1475:     my $fpath = '';
                   1476:     my $fname = $file;
                   1477:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   1478:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   1479:     my $filepath = &build_filepath($fpath);
                   1480:     open(my $fh,'>'.$filepath.'/'.$fname);
                   1481:     print $fh $content;
                   1482:     close($fh);
1.638     albertel 1483:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  1484:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1485: 			  $home);
1.637     raeburn  1486:     if ($$fetchresult eq 'ok') {
                   1487:         return '/uploaded/'.$fpath.'/'.$fname;
                   1488:     } else {
1.638     albertel 1489:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   1490: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  1491:         return '/adm/notfound.html';
                   1492:     }
                   1493: }
                   1494: 
1.531     albertel 1495: sub clean_filename {
1.831     albertel 1496:     my ($fname,$args)=@_;
1.315     www      1497: # Replace Windows backslashes by forward slashes
1.257     www      1498:     $fname=~s/\\/\//g;
1.831     albertel 1499:     if (!$args->{'keep_path'}) {
                   1500:         # Get rid of everything but the actual filename
                   1501: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   1502:     }
1.315     www      1503: # Replace spaces by underscores
                   1504:     $fname=~s/\s+/\_/g;
                   1505: # Replace all other weird characters by nothing
1.831     albertel 1506:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 1507: # Replace all .\d. sequences with _\d. so they no longer look like version
                   1508: # numbers
                   1509:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 1510:     return $fname;
                   1511: }
                   1512: 
1.608     albertel 1513: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 1514: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 1515: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 1516: #        $coursedoc - if true up to the current course
                   1517: #                     if false
                   1518: #        $subdir - directory in userfile to store the file into
1.858     raeburn  1519: #        $parser - instruction to parse file for objects ($parser = parse)    
                   1520: #        $allfiles - reference to hash for embedded objects
                   1521: #        $codebase - reference to hash for codebase of java objects
                   1522: #        $desuname - username for permanent storage of uploaded file
                   1523: #        $dsetudom - domain for permanaent storage of uploaded file
                   1524: # 
1.686     albertel 1525: # output: url of file in userspace, or error: <message> 
                   1526: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 1527: 
                   1528: 
1.531     albertel 1529: sub userfileupload {
1.719     banghart 1530:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,$destudom)=@_;
1.531     albertel 1531:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 1532:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 1533:     $fname=&clean_filename($fname);
1.315     www      1534: # See if there is anything left
1.257     www      1535:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 1536:     chop($env{'form.'.$formname});
1.523     raeburn  1537:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   1538:         my $now = time;
                   1539:         my $filepath = 'tmp/helprequests/'.$now;
                   1540:         my @parts=split(/\//,$filepath);
                   1541:         my $fullpath = $perlvar{'lonDaemons'};
                   1542:         for (my $i=0;$i<@parts;$i++) {
                   1543:             $fullpath .= '/'.$parts[$i];
                   1544:             if ((-e $fullpath)!=1) {
                   1545:                 mkdir($fullpath,0777);
                   1546:             }
                   1547:         }
                   1548:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 1549:         print $fh $env{'form.'.$formname};
1.523     raeburn  1550:         close($fh);
1.741     raeburn  1551:         return $fullpath.'/'.$fname;
                   1552:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   1553:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   1554:                        '_'.$env{'user.domain'}.'/pending';
                   1555:         my @parts=split(/\//,$filepath);
                   1556:         my $fullpath = $perlvar{'lonDaemons'};
                   1557:         for (my $i=0;$i<@parts;$i++) {
                   1558:             $fullpath .= '/'.$parts[$i];
                   1559:             if ((-e $fullpath)!=1) {
                   1560:                 mkdir($fullpath,0777);
                   1561:             }
                   1562:         }
                   1563:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   1564:         print $fh $env{'form.'.$formname};
                   1565:         close($fh);
                   1566:         return $fullpath.'/'.$fname;
1.523     raeburn  1567:     }
1.719     banghart 1568:     
1.258     www      1569: # Create the directory if not present
1.493     albertel 1570:     $fname="$subdir/$fname";
1.259     www      1571:     if ($coursedoc) {
1.638     albertel 1572: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1573: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  1574:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 1575:             return &finishuserfileupload($docuname,$docudom,
                   1576: 					 $formname,$fname,$parser,$allfiles,
                   1577: 					 $codebase);
1.481     raeburn  1578:         } else {
1.620     albertel 1579:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 1580:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   1581: 				       $fname,$formname,$parser,
                   1582: 				       $allfiles,$codebase);
1.481     raeburn  1583:         }
1.719     banghart 1584:     } elsif (defined($destuname)) {
                   1585:         my $docuname=$destuname;
                   1586:         my $docudom=$destudom;
                   1587: 	return &finishuserfileupload($docuname,$docudom,$formname,
                   1588: 				     $fname,$parser,$allfiles,$codebase);
                   1589:         
1.259     www      1590:     } else {
1.638     albertel 1591:         my $docuname=$env{'user.name'};
                   1592:         my $docudom=$env{'user.domain'};
1.714     raeburn  1593:         if (exists($env{'form.group'})) {
                   1594:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1595:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1596:         }
1.638     albertel 1597: 	return &finishuserfileupload($docuname,$docudom,$formname,
                   1598: 				     $fname,$parser,$allfiles,$codebase);
1.259     www      1599:     }
1.271     www      1600: }
                   1601: 
                   1602: sub finishuserfileupload {
1.638     albertel 1603:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase) = @_;
1.477     raeburn  1604:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      1605:     my $filepath=$perlvar{'lonDocRoot'};
1.494     albertel 1606:     my ($fnamepath,$file);
                   1607:     $file=$fname;
                   1608:     if ($fname=~m|/|) {
                   1609:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   1610: 	$path.=$fnamepath.'/';
                   1611:     }
1.259     www      1612:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      1613:     my $count;
                   1614:     for ($count=4;$count<=$#parts;$count++) {
                   1615:         $filepath.="/$parts[$count]";
                   1616:         if ((-e $filepath)!=1) {
                   1617: 	    mkdir($filepath,0777);
                   1618:         }
                   1619:     }
                   1620: # Save the file
                   1621:     {
1.701     albertel 1622: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   1623: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   1624: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   1625: 	    return '/adm/notfound.html';
                   1626: 	}
                   1627: 	if (!print FH ($env{'form.'.$formname})) {
                   1628: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   1629: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   1630: 	    return '/adm/notfound.html';
                   1631: 	}
1.570     albertel 1632: 	close(FH);
1.258     www      1633:     }
1.637     raeburn  1634:     if ($parser eq 'parse') {
1.638     albertel 1635:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
                   1636: 						   $codebase);
1.637     raeburn  1637:         unless ($parse_result eq 'ok') {
1.638     albertel 1638:             &logthis('Failed to parse '.$filepath.$file.
                   1639: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  1640:         }
                   1641:     }
1.858     raeburn  1642:  
1.259     www      1643: # Notify homeserver to grep it
                   1644: #
1.638     albertel 1645:     my $docuhome=&homeserver($docuname,$docudom);
1.494     albertel 1646:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      1647:     if ($fetchresult eq 'ok') {
1.259     www      1648: #
1.258     www      1649: # Return the URL to it
1.494     albertel 1650:         return '/uploaded/'.$path.$file;
1.263     www      1651:     } else {
1.494     albertel 1652:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   1653: 		 ': '.$fetchresult);
1.263     www      1654:         return '/adm/notfound.html';
1.858     raeburn  1655:     }
1.493     albertel 1656: }
                   1657: 
1.637     raeburn  1658: sub extract_embedded_items {
1.648     raeburn  1659:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
1.637     raeburn  1660:     my @state = ();
                   1661:     my %javafiles = (
                   1662:                       codebase => '',
                   1663:                       code => '',
                   1664:                       archive => ''
                   1665:                     );
                   1666:     my %mediafiles = (
                   1667:                       src => '',
                   1668:                       movie => '',
                   1669:                      );
1.648     raeburn  1670:     my $p;
                   1671:     if ($content) {
                   1672:         $p = HTML::LCParser->new($content);
                   1673:     } else {
                   1674:         $p = HTML::LCParser->new($filepath.'/'.$file);
                   1675:     }
1.641     albertel 1676:     while (my $t=$p->get_token()) {
1.640     albertel 1677: 	if ($t->[0] eq 'S') {
                   1678: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
                   1679: 	    push (@state, $tagname);
1.648     raeburn  1680:             if (lc($tagname) eq 'allow') {
                   1681:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   1682:             }
1.640     albertel 1683: 	    if (lc($tagname) eq 'img') {
                   1684: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   1685: 	    }
1.645     raeburn  1686:             if (lc($tagname) eq 'script') {
                   1687:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   1688:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   1689:                 } else {
                   1690:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   1691:                 }
                   1692:             }
                   1693:             if (lc($tagname) eq 'link') {
                   1694:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   1695:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   1696:                 }
                   1697:             }
1.640     albertel 1698: 	    if (lc($tagname) eq 'object' ||
                   1699: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   1700: 		foreach my $item (keys(%javafiles)) {
                   1701: 		    $javafiles{$item} = '';
                   1702: 		}
                   1703: 	    }
                   1704: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   1705: 		my $name = lc($attr->{'name'});
                   1706: 		foreach my $item (keys(%javafiles)) {
                   1707: 		    if ($name eq $item) {
                   1708: 			$javafiles{$item} = $attr->{'value'};
                   1709: 			last;
                   1710: 		    }
                   1711: 		}
                   1712: 		foreach my $item (keys(%mediafiles)) {
                   1713: 		    if ($name eq $item) {
                   1714: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   1715: 			last;
                   1716: 		    }
                   1717: 		}
                   1718: 	    }
                   1719: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   1720: 		foreach my $item (keys(%javafiles)) {
                   1721: 		    if ($attr->{$item}) {
                   1722: 			$javafiles{$item} = $attr->{$item};
                   1723: 			last;
                   1724: 		    }
                   1725: 		}
                   1726: 		foreach my $item (keys(%mediafiles)) {
                   1727: 		    if ($attr->{$item}) {
                   1728: 			&add_filetype($allfiles,$attr->{$item},$item);
                   1729: 			last;
                   1730: 		    }
                   1731: 		}
                   1732: 	    }
                   1733: 	} elsif ($t->[0] eq 'E') {
                   1734: 	    my ($tagname) = ($t->[1]);
                   1735: 	    if ($javafiles{'codebase'} ne '') {
                   1736: 		$javafiles{'codebase'} .= '/';
                   1737: 	    }  
                   1738: 	    if (lc($tagname) eq 'applet' ||
                   1739: 		lc($tagname) eq 'object' ||
                   1740: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   1741: 		) {
                   1742: 		foreach my $item (keys(%javafiles)) {
                   1743: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   1744: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   1745: 			&add_filetype($allfiles,$file,$item);
                   1746: 		    }
                   1747: 		}
                   1748: 	    } 
                   1749: 	    pop @state;
                   1750: 	}
                   1751:     }
1.637     raeburn  1752:     return 'ok';
                   1753: }
                   1754: 
1.639     albertel 1755: sub add_filetype {
                   1756:     my ($allfiles,$file,$type)=@_;
                   1757:     if (exists($allfiles->{$file})) {
                   1758: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   1759: 	    push(@{$allfiles->{$file}}, &escape($type));
                   1760: 	}
                   1761:     } else {
                   1762: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  1763:     }
                   1764: }
                   1765: 
1.493     albertel 1766: sub removeuploadedurl {
                   1767:     my ($url)=@_;
                   1768:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613     albertel 1769:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 1770: }
                   1771: 
                   1772: sub removeuserfile {
                   1773:     my ($docuname,$docudom,$fname)=@_;
                   1774:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  1775:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
                   1776:     if ($result eq 'ok') {
                   1777:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   1778:             my $metafile = $fname.'.meta';
                   1779:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 1780: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
                   1781:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  1782:             my $sqlresult = 
1.823     albertel 1783:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  1784:                                         'portfolio_metadata',$group,
                   1785:                                         'delete');
1.798     raeburn  1786:         }
                   1787:     }
                   1788:     return $result;
1.257     www      1789: }
1.15      www      1790: 
1.530     albertel 1791: sub mkdiruserfile {
                   1792:     my ($docuname,$docudom,$dir)=@_;
                   1793:     my $home=&homeserver($docuname,$docudom);
                   1794:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   1795: }
                   1796: 
1.531     albertel 1797: sub renameuserfile {
                   1798:     my ($docuname,$docudom,$old,$new)=@_;
                   1799:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  1800:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   1801:                         &escape("$old").':'.&escape("$new"),$home);
                   1802:     if ($result eq 'ok') {
                   1803:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   1804:             my $oldmeta = $old.'.meta';
                   1805:             my $newmeta = $new.'.meta';
                   1806:             my $metaresult = 
                   1807:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 1808: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   1809:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  1810:             my $sqlresult = 
1.823     albertel 1811:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  1812:                                         'portfolio_metadata',$group,
                   1813:                                         'delete');
1.798     raeburn  1814:         }
                   1815:     }
                   1816:     return $result;
1.531     albertel 1817: }
                   1818: 
1.14      www      1819: # ------------------------------------------------------------------------- Log
                   1820: 
                   1821: sub log {
                   1822:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      1823:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      1824: }
                   1825: 
                   1826: # ------------------------------------------------------------------ Course Log
1.352     www      1827: #
                   1828: # This routine flushes several buffers of non-mission-critical nature
                   1829: #
1.157     www      1830: 
                   1831: sub flushcourselogs {
1.352     www      1832:     &logthis('Flushing log buffers');
                   1833: #
                   1834: # course logs
                   1835: # This is a log of all transactions in a course, which can be used
                   1836: # for data mining purposes
                   1837: #
                   1838: # It also collects the courseid database, which lists last transaction
                   1839: # times and course titles for all courseids
                   1840: #
                   1841:     my %courseidbuffer=();
1.800     albertel 1842:     foreach my $crsid (keys %courselogs) {
1.352     www      1843:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      1844: 		          &escape($courselogs{$crsid}),
                   1845: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      1846: 	    delete $courselogs{$crsid};
                   1847:         } else {
                   1848:             &logthis('Failed to flush log buffer for '.$crsid);
                   1849:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 1850:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      1851:                         " exceeded maximum size, deleting.</font>");
                   1852:                delete $courselogs{$crsid};
                   1853:             }
1.352     www      1854:         }
                   1855:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
                   1856:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
1.516     raeburn  1857: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  1858:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.352     www      1859:         } else {
                   1860:            $courseidbuffer{$coursehombuf{$crsid}}=
1.516     raeburn  1861: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  1862:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.571     raeburn  1863:         }
1.191     harris41 1864:     }
1.352     www      1865: #
                   1866: # Write course id database (reverse lookup) to homeserver of courses 
                   1867: # Is used in pickcourse
                   1868: #
1.840     albertel 1869:     foreach my $crs_home (keys(%courseidbuffer)) {
1.844     albertel 1870:         &courseidput(&host_domain($crs_home),$courseidbuffer{$crs_home},
1.840     albertel 1871: 		     $crs_home);
1.352     www      1872:     }
                   1873: #
                   1874: # File accesses
                   1875: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   1876: #
1.449     matthew  1877:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  1878:         if ($entry =~ /___count$/) {
                   1879:             my ($dom,$name);
1.807     albertel 1880:             ($dom,$name,undef)=
1.811     albertel 1881: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  1882:             if (! defined($dom) || $dom eq '' || 
                   1883:                 ! defined($name) || $name eq '') {
1.620     albertel 1884:                 my $cid = $env{'request.course.id'};
                   1885:                 $dom  = $env{'request.'.$cid.'.domain'};
                   1886:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  1887:             }
1.450     matthew  1888:             my $value = $accesshash{$entry};
                   1889:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   1890:             my %temphash=($url => $value);
1.449     matthew  1891:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   1892:             if ($result eq 'ok') {
                   1893:                 delete $accesshash{$entry};
                   1894:             } elsif ($result eq 'unknown_cmd') {
                   1895:                 # Target server has old code running on it.
1.450     matthew  1896:                 my %temphash=($entry => $value);
1.449     matthew  1897:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1898:                     delete $accesshash{$entry};
                   1899:                 }
                   1900:             }
                   1901:         } else {
1.811     albertel 1902:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  1903:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  1904:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1905:                 delete $accesshash{$entry};
                   1906:             }
1.185     www      1907:         }
1.191     harris41 1908:     }
1.352     www      1909: #
                   1910: # Roles
                   1911: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   1912: #
1.800     albertel 1913:     foreach my $entry (keys(%userrolehash)) {
1.351     www      1914:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      1915: 	    split(/\:/,$entry);
                   1916:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      1917:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      1918:                 $rudom,$runame) eq 'ok') {
                   1919: 	    delete $userrolehash{$entry};
                   1920:         }
                   1921:     }
1.662     raeburn  1922: #
                   1923: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   1924: #
                   1925:     my %domrolebuffer = ();
                   1926:     foreach my $entry (keys %domainrolehash) {
                   1927:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split/:/,$entry;
                   1928:         if ($domrolebuffer{$rudom}) {
                   1929:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   1930:                       '='.&escape($domainrolehash{$entry});
                   1931:         } else {
                   1932:             $domrolebuffer{$rudom}.=&escape($entry).
                   1933:                       '='.&escape($domainrolehash{$entry});
                   1934:         }
                   1935:         delete $domainrolehash{$entry};
                   1936:     }
                   1937:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 1938: 	my %servers = &get_servers($dom,'library');
                   1939: 	foreach my $tryserver (keys(%servers)) {
                   1940: 	    unless (&reply('domroleput:'.$dom.':'.
                   1941: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   1942: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   1943: 	    }
1.662     raeburn  1944:         }
                   1945:     }
1.186     www      1946:     $dumpcount++;
1.157     www      1947: }
                   1948: 
                   1949: sub courselog {
                   1950:     my $what=shift;
1.158     www      1951:     $what=time.':'.$what;
1.620     albertel 1952:     unless ($env{'request.course.id'}) { return ''; }
                   1953:     $coursedombuf{$env{'request.course.id'}}=
                   1954:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   1955:     $coursenumbuf{$env{'request.course.id'}}=
                   1956:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   1957:     $coursehombuf{$env{'request.course.id'}}=
                   1958:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   1959:     $coursedescrbuf{$env{'request.course.id'}}=
                   1960:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   1961:     $courseinstcodebuf{$env{'request.course.id'}}=
                   1962:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   1963:     $courseownerbuf{$env{'request.course.id'}}=
                   1964:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  1965:     $coursetypebuf{$env{'request.course.id'}}=
                   1966:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 1967:     if (defined $courselogs{$env{'request.course.id'}}) {
                   1968: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      1969:     } else {
1.620     albertel 1970: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      1971:     }
1.620     albertel 1972:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      1973: 	&flushcourselogs();
                   1974:     }
1.158     www      1975: }
                   1976: 
                   1977: sub courseacclog {
                   1978:     my $fnsymb=shift;
1.620     albertel 1979:     unless ($env{'request.course.id'}) { return ''; }
                   1980:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 1981:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      1982:         $what.=':POST';
1.583     matthew  1983:         # FIXME: Probably ought to escape things....
1.800     albertel 1984: 	foreach my $key (keys(%env)) {
                   1985:             if ($key=~/^form\.(.*)/) {
                   1986: 		$what.=':'.$1.'='.$env{$key};
1.158     www      1987:             }
1.191     harris41 1988:         }
1.583     matthew  1989:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   1990:         # FIXME: We should not be depending on a form parameter that someone
                   1991:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 1992:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  1993:             $what.= ':POST';
                   1994:             # FIXME: Probably ought to escape things....
                   1995:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   1996:                                  'crsdiscuss') {
1.620     albertel 1997:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  1998:             }
                   1999:         }
1.158     www      2000:     }
                   2001:     &courselog($what);
1.149     www      2002: }
                   2003: 
1.185     www      2004: sub countacc {
                   2005:     my $url=&declutter(shift);
1.458     matthew  2006:     return if (! defined($url) || $url eq '');
1.620     albertel 2007:     unless ($env{'request.course.id'}) { return ''; }
                   2008:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      2009:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  2010:     $accesshash{$key}++;
1.185     www      2011: }
1.349     www      2012: 
1.361     www      2013: sub linklog {
                   2014:     my ($from,$to)=@_;
                   2015:     $from=&declutter($from);
                   2016:     $to=&declutter($to);
                   2017:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   2018:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   2019: }
                   2020:   
1.349     www      2021: sub userrolelog {
                   2022:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  2023:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  2024:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  2025:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   2026:         ($trole=~/^ta/)) {
1.350     www      2027:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2028:        $userrolehash
                   2029:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      2030:                     =$tend.':'.$tstart;
1.662     raeburn  2031:     }
                   2032:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   2033:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   2034:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   2035:         ($trole=~/^sc/)) {
                   2036:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2037:        $domainrolehash
                   2038:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   2039:                     = $tend.':'.$tstart;
                   2040:     }
1.351     www      2041: }
                   2042: 
                   2043: sub get_course_adv_roles {
                   2044:     my $cid=shift;
1.620     albertel 2045:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      2046:     my %coursehash=&coursedescription($cid);
1.470     www      2047:     my %nothide=();
1.800     albertel 2048:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2049: 	$nothide{join(':',split(/[\@\:]/,$user))}=1;
1.470     www      2050:     }
1.351     www      2051:     my %returnhash=();
                   2052:     my %dumphash=
                   2053:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   2054:     my $now=time;
1.800     albertel 2055:     foreach my $entry (keys %dumphash) {
                   2056: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      2057:         if (($tstart) && ($tstart<0)) { next; }
                   2058:         if (($tend) && ($tend<$now)) { next; }
                   2059:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 2060:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 2061: 	if ($username eq '' || $domain eq '') { next; }
1.470     www      2062: 	if ((&privileged($username,$domain)) && 
                   2063: 	    (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 2064: 	if ($role eq 'cr') { next; }
1.351     www      2065:         my $key=&plaintext($role);
                   2066:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
                   2067:         if ($returnhash{$key}) {
                   2068: 	    $returnhash{$key}.=','.$username.':'.$domain;
                   2069:         } else {
                   2070:             $returnhash{$key}=$username.':'.$domain;
                   2071:         }
1.400     www      2072:      }
                   2073:     return %returnhash;
                   2074: }
                   2075: 
                   2076: sub get_my_roles {
1.858     raeburn  2077:     my ($uname,$udom,$context,$types,$roles,$roledoms)=@_;
1.620     albertel 2078:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   2079:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.858     raeburn  2080:     my %dumphash;
                   2081:     if ($context eq 'userroles') { 
                   2082:         %dumphash = &dump('roles',$udom,$uname);
                   2083:     } else {
                   2084:         %dumphash=
1.400     www      2085:             &dump('nohist_userroles',$udom,$uname);
1.858     raeburn  2086:     }
1.400     www      2087:     my %returnhash=();
                   2088:     my $now=time;
1.800     albertel 2089:     foreach my $entry (keys(%dumphash)) {
                   2090: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.400     www      2091:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  2092:         my $status = 'active';
                   2093:         if (($tend) && ($tend<$now)) {
                   2094:             $status = 'previous';
                   2095:         } 
                   2096:         if (($tstart) && ($now<$tstart)) {
                   2097:             $status = 'future';
                   2098:         }
                   2099:         if (ref($types) eq 'ARRAY') {
                   2100:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   2101:                 next;
                   2102:             } 
                   2103:         } else {
                   2104:             if ($status ne 'active') {
                   2105:                 next;
                   2106:             }
                   2107:         }
1.800     albertel 2108:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.832     raeburn  2109:         if (ref($roledoms) eq 'ARRAY') {
                   2110:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   2111:                 next;
                   2112:             }
                   2113:         }
                   2114:         if (ref($roles) eq 'ARRAY') {
                   2115:             if (!grep(/^\Q$role\E$/,@{$roles})) {
                   2116:                 next;
                   2117:             }
                   2118:         } 
1.400     www      2119: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
1.832     raeburn  2120:     }
1.373     www      2121:     return %returnhash;
1.399     www      2122: }
                   2123: 
                   2124: # ----------------------------------------------------- Frontpage Announcements
                   2125: #
                   2126: #
                   2127: 
                   2128: sub postannounce {
                   2129:     my ($server,$text)=@_;
1.844     albertel 2130:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      2131:     unless ($text=~/\w/) { $text=''; }
                   2132:     return &reply('setannounce:'.&escape($text),$server);
                   2133: }
                   2134: 
                   2135: sub getannounce {
1.448     albertel 2136: 
                   2137:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      2138: 	my $announcement='';
1.800     albertel 2139: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 2140: 	close($fh);
1.399     www      2141: 	if ($announcement=~/\w/) { 
                   2142: 	    return 
                   2143:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 2144:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      2145: 	} else {
                   2146: 	    return '';
                   2147: 	}
                   2148:     } else {
                   2149: 	return '';
                   2150:     }
1.351     www      2151: }
1.353     www      2152: 
                   2153: # ---------------------------------------------------------- Course ID routines
                   2154: # Deal with domain's nohist_courseid.db files
                   2155: #
                   2156: 
                   2157: sub courseidput {
                   2158:     my ($domain,$what,$coursehome)=@_;
                   2159:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   2160: }
                   2161: 
                   2162: sub courseiddump {
1.791     raeburn  2163:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok)=@_;
1.353     www      2164:     my %returnhash=();
1.355     www      2165:     unless ($domfilter) { $domfilter=''; }
1.845     albertel 2166:     my %libserv = &all_library();
                   2167:     foreach my $tryserver (keys(%libserv)) {
                   2168:         if ( (  $hostidflag == 1 
                   2169: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   2170: 	     || (!defined($hostidflag)) ) {
                   2171: 
                   2172: 	    if ($domfilter eq ''
                   2173: 		|| (&host_domain($tryserver) eq $domfilter)) {
1.800     albertel 2174: 	        foreach my $line (
1.844     albertel 2175:                  split(/\&/,&reply('courseiddump:'.&host_domain($tryserver).':'.
1.571     raeburn  2176: 			       $sincefilter.':'.&escape($descfilter).':'.
1.791     raeburn  2177:                                &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter).':'.&escape($typefilter).':'.&escape($regexp_ok),
1.354     www      2178:                                $tryserver))) {
1.800     albertel 2179: 		    my ($key,$value)=split(/\=/,$line,2);
1.506     raeburn  2180:                     if (($key) && ($value)) {
1.516     raeburn  2181: 		        $returnhash{&unescape($key)}=$value;
1.506     raeburn  2182:                     }
1.353     www      2183:                 }
                   2184:             }
                   2185:         }
                   2186:     }
                   2187:     return %returnhash;
                   2188: }
                   2189: 
1.658     raeburn  2190: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  2191: 
                   2192: sub dcmailput {
1.685     raeburn  2193:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  2194:     my $status = &Apache::lonnet::critical(
1.740     www      2195:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   2196:        &escape($message),$server);
1.662     raeburn  2197:     return $status;
                   2198: }
                   2199: 
1.658     raeburn  2200: sub dcmaildump {
                   2201:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  2202:     my %returnhash=();
1.846     albertel 2203: 
                   2204:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  2205:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   2206:                                                          &escape($enddate).':';
                   2207: 	my @esc_senders=map { &escape($_)} @$senders;
                   2208: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 2209: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 2210:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  2211:             if (($key) && ($value)) {
                   2212:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  2213:             }
                   2214:         }
                   2215:     }
                   2216:     return %returnhash;
                   2217: }
1.662     raeburn  2218: # ---------------------------------------------------------- Domain roles
                   2219: 
                   2220: sub get_domain_roles {
                   2221:     my ($dom,$roles,$startdate,$enddate)=@_;
                   2222:     if (undef($startdate) || $startdate eq '') {
                   2223:         $startdate = '.';
                   2224:     }
                   2225:     if (undef($enddate) || $enddate eq '') {
                   2226:         $enddate = '.';
                   2227:     }
                   2228:     my $rolelist = join(':',@{$roles});
                   2229:     my %personnel = ();
1.841     albertel 2230: 
                   2231:     my %servers = &get_servers($dom,'library');
                   2232:     foreach my $tryserver (keys(%servers)) {
                   2233: 	%{$personnel{$tryserver}}=();
                   2234: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   2235: 					    &escape($startdate).':'.
                   2236: 					    &escape($enddate).':'.
                   2237: 					    &escape($rolelist), $tryserver))) {
                   2238: 	    my ($key,$value) = split(/\=/,$line,2);
                   2239: 	    if (($key) && ($value)) {
                   2240: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   2241: 	    }
                   2242: 	}
1.662     raeburn  2243:     }
                   2244:     return %personnel;
                   2245: }
1.658     raeburn  2246: 
1.149     www      2247: # ----------------------------------------------------------- Check out an item
                   2248: 
1.504     albertel 2249: sub get_first_access {
                   2250:     my ($type,$argsymb)=@_;
1.790     albertel 2251:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2252:     if ($argsymb) { $symb=$argsymb; }
                   2253:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2254:     if ($type eq 'map') {
                   2255: 	$res=&symbread($map);
                   2256:     } else {
                   2257: 	$res=$symb;
                   2258:     }
                   2259:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   2260:     return $times{"$courseid\0$res"};
1.504     albertel 2261: }
                   2262: 
                   2263: sub set_first_access {
                   2264:     my ($type)=@_;
1.790     albertel 2265:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2266:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2267:     if ($type eq 'map') {
                   2268: 	$res=&symbread($map);
                   2269:     } else {
                   2270: 	$res=$symb;
                   2271:     }
                   2272:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 2273:     if (!$firstaccess) {
1.588     albertel 2274: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 2275:     }
                   2276:     return 'already_set';
1.504     albertel 2277: }
                   2278: 
1.149     www      2279: sub checkout {
                   2280:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   2281:     my $now=time;
                   2282:     my $lonhost=$perlvar{'lonHostID'};
                   2283:     my $infostr=&escape(
1.234     www      2284:                  'CHECKOUTTOKEN&'.
1.149     www      2285:                  $tuname.'&'.
                   2286:                  $tudom.'&'.
                   2287:                  $tcrsid.'&'.
                   2288:                  $symb.'&'.
                   2289: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   2290:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      2291:     if ($token=~/^error\:/) { 
1.672     albertel 2292:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2293:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2294:                  "</font>");
                   2295:         return ''; 
                   2296:     }
                   2297: 
1.149     www      2298:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   2299:     $token=~tr/a-z/A-Z/;
                   2300: 
1.153     www      2301:     my %infohash=('resource.0.outtoken' => $token,
                   2302:                   'resource.0.checkouttime' => $now,
                   2303:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      2304: 
                   2305:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2306:        return '';
1.151     www      2307:     } else {
1.672     albertel 2308:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2309:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2310:                  "</font>");
1.149     www      2311:     }    
                   2312: 
                   2313:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2314:                          &escape('Checkout '.$infostr.' - '.
                   2315:                                                  $token)) ne 'ok') {
                   2316: 	return '';
1.151     www      2317:     } else {
1.672     albertel 2318:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2319:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2320:                  "</font>");
1.149     www      2321:     }
1.151     www      2322:     return $token;
1.149     www      2323: }
                   2324: 
                   2325: # ------------------------------------------------------------ Check in an item
                   2326: 
                   2327: sub checkin {
                   2328:     my $token=shift;
1.150     www      2329:     my $now=time;
                   2330:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   2331:     $lonhost=~tr/A-Z/a-z/;
1.838     albertel 2332:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150     www      2333:     $dtoken=~s/\W/\_/g;
1.234     www      2334:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      2335:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   2336: 
1.154     www      2337:     unless (($tuname) && ($tudom)) {
                   2338:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   2339:         return '';
                   2340:     }
                   2341:     
                   2342:     unless (&allowed('mgr',$tcrsid)) {
                   2343:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 2344:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      2345:         return '';
                   2346:     }
                   2347: 
1.153     www      2348:     my %infohash=('resource.0.intoken' => $token,
                   2349:                   'resource.0.checkintime' => $now,
                   2350:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      2351: 
                   2352:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2353:        return '';
                   2354:     }    
                   2355: 
                   2356:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2357:                          &escape('Checkin - '.$token)) ne 'ok') {
                   2358: 	return '';
                   2359:     }
                   2360: 
                   2361:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      2362: }
                   2363: 
                   2364: # --------------------------------------------- Set Expire Date for Spreadsheet
                   2365: 
                   2366: sub expirespread {
                   2367:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 2368:     my $cid=$env{'request.course.id'}; 
1.110     www      2369:     if ($cid) {
                   2370:        my $now=time;
                   2371:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 2372:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   2373:                             $env{'course.'.$cid.'.num'}.
1.110     www      2374: 	        	    ':nohist_expirationdates:'.
                   2375:                             &escape($key).'='.$now,
1.620     albertel 2376:                             $env{'course.'.$cid.'.home'})
1.110     www      2377:     }
                   2378:     return 'ok';
1.14      www      2379: }
                   2380: 
1.109     www      2381: # ----------------------------------------------------- Devalidate Spreadsheets
                   2382: 
                   2383: sub devalidate {
1.325     www      2384:     my ($symb,$uname,$udom)=@_;
1.620     albertel 2385:     my $cid=$env{'request.course.id'}; 
1.109     www      2386:     if ($cid) {
1.391     matthew  2387:         # delete the stored spreadsheets for
                   2388:         # - the student level sheet of this user in course's homespace
                   2389:         # - the assessment level sheet for this resource 
                   2390:         #   for this user in user's homespace
1.553     albertel 2391: 	# - current conditional state info
1.325     www      2392: 	my $key=$uname.':'.$udom.':';
1.109     www      2393:         my $status=
1.299     matthew  2394: 	    &del('nohist_calculatedsheets',
1.391     matthew  2395: 		 [$key.'studentcalc:'],
1.620     albertel 2396: 		 $env{'course.'.$cid.'.domain'},
                   2397: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 2398: 		.' '.
                   2399: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  2400: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      2401:         unless ($status eq 'ok ok') {
                   2402:            &logthis('Could not devalidate spreadsheet '.
1.325     www      2403:                     $uname.' at '.$udom.' for '.
1.109     www      2404: 		    $symb.': '.$status);
1.133     albertel 2405:         }
1.553     albertel 2406: 	&delenv('user.state.'.$cid);
1.109     www      2407:     }
                   2408: }
                   2409: 
1.265     albertel 2410: sub get_scalar {
                   2411:     my ($string,$end) = @_;
                   2412:     my $value;
                   2413:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   2414: 	$value = $1;
                   2415:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   2416: 	$value = $1;
                   2417:     }
                   2418:     return &unescape($value);
                   2419: }
                   2420: 
                   2421: sub array2str {
                   2422:   my (@array) = @_;
                   2423:   my $result=&arrayref2str(\@array);
                   2424:   $result=~s/^__ARRAY_REF__//;
                   2425:   $result=~s/__END_ARRAY_REF__$//;
                   2426:   return $result;
                   2427: }
                   2428: 
1.204     albertel 2429: sub arrayref2str {
                   2430:   my ($arrayref) = @_;
1.265     albertel 2431:   my $result='__ARRAY_REF__';
1.204     albertel 2432:   foreach my $elem (@$arrayref) {
1.265     albertel 2433:     if(ref($elem) eq 'ARRAY') {
                   2434:       $result.=&arrayref2str($elem).'&';
                   2435:     } elsif(ref($elem) eq 'HASH') {
                   2436:       $result.=&hashref2str($elem).'&';
                   2437:     } elsif(ref($elem)) {
                   2438:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 2439:     } else {
                   2440:       $result.=&escape($elem).'&';
                   2441:     }
                   2442:   }
                   2443:   $result=~s/\&$//;
1.265     albertel 2444:   $result .= '__END_ARRAY_REF__';
1.204     albertel 2445:   return $result;
                   2446: }
                   2447: 
1.168     albertel 2448: sub hash2str {
1.204     albertel 2449:   my (%hash) = @_;
                   2450:   my $result=&hashref2str(\%hash);
1.265     albertel 2451:   $result=~s/^__HASH_REF__//;
                   2452:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 2453:   return $result;
                   2454: }
                   2455: 
                   2456: sub hashref2str {
                   2457:   my ($hashref)=@_;
1.265     albertel 2458:   my $result='__HASH_REF__';
1.800     albertel 2459:   foreach my $key (sort(keys(%$hashref))) {
                   2460:     if (ref($key) eq 'ARRAY') {
                   2461:       $result.=&arrayref2str($key).'=';
                   2462:     } elsif (ref($key) eq 'HASH') {
                   2463:       $result.=&hashref2str($key).'=';
                   2464:     } elsif (ref($key)) {
1.265     albertel 2465:       $result.='=';
1.800     albertel 2466:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 2467:     } else {
1.800     albertel 2468: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 2469:     }
                   2470: 
1.800     albertel 2471:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   2472:       $result.=&arrayref2str($hashref->{$key}).'&';
                   2473:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   2474:       $result.=&hashref2str($hashref->{$key}).'&';
                   2475:     } elsif(ref($hashref->{$key})) {
1.265     albertel 2476:        $result.='&';
1.800     albertel 2477:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 2478:     } else {
1.800     albertel 2479:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 2480:     }
                   2481:   }
1.168     albertel 2482:   $result=~s/\&$//;
1.265     albertel 2483:   $result .= '__END_HASH_REF__';
1.168     albertel 2484:   return $result;
                   2485: }
                   2486: 
                   2487: sub str2hash {
1.265     albertel 2488:     my ($string)=@_;
                   2489:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   2490:     return %$hash;
                   2491: }
                   2492: 
                   2493: sub str2hashref {
1.168     albertel 2494:   my ($string) = @_;
1.265     albertel 2495: 
                   2496:   my %hash;
                   2497: 
                   2498:   if($string !~ /^__HASH_REF__/) {
                   2499:       if (! ($string eq '' || !defined($string))) {
                   2500: 	  $hash{'error'}='Not hash reference';
                   2501:       }
                   2502:       return (\%hash, $string);
                   2503:   }
                   2504: 
                   2505:   $string =~ s/^__HASH_REF__//;
                   2506: 
                   2507:   while($string !~ /^__END_HASH_REF__/) {
                   2508:       #key
                   2509:       my $key='';
                   2510:       if($string =~ /^__HASH_REF__/) {
                   2511:           ($key, $string)=&str2hashref($string);
                   2512:           if(defined($key->{'error'})) {
                   2513:               $hash{'error'}='Bad data';
                   2514:               return (\%hash, $string);
                   2515:           }
                   2516:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2517:           ($key, $string)=&str2arrayref($string);
                   2518:           if($key->[0] eq 'Array reference error') {
                   2519:               $hash{'error'}='Bad data';
                   2520:               return (\%hash, $string);
                   2521:           }
                   2522:       } else {
                   2523:           $string =~ s/^(.*?)=//;
1.267     albertel 2524: 	  $key=&unescape($1);
1.265     albertel 2525:       }
                   2526:       $string =~ s/^=//;
                   2527: 
                   2528:       #value
                   2529:       my $value='';
                   2530:       if($string =~ /^__HASH_REF__/) {
                   2531:           ($value, $string)=&str2hashref($string);
                   2532:           if(defined($value->{'error'})) {
                   2533:               $hash{'error'}='Bad data';
                   2534:               return (\%hash, $string);
                   2535:           }
                   2536:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2537:           ($value, $string)=&str2arrayref($string);
                   2538:           if($value->[0] eq 'Array reference error') {
                   2539:               $hash{'error'}='Bad data';
                   2540:               return (\%hash, $string);
                   2541:           }
                   2542:       } else {
                   2543: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   2544:       }
                   2545:       $string =~ s/^&//;
                   2546: 
                   2547:       $hash{$key}=$value;
1.204     albertel 2548:   }
1.265     albertel 2549: 
                   2550:   $string =~ s/^__END_HASH_REF__//;
                   2551: 
                   2552:   return (\%hash, $string);
1.204     albertel 2553: }
                   2554: 
                   2555: sub str2array {
1.265     albertel 2556:     my ($string)=@_;
                   2557:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   2558:     return @$array;
                   2559: }
                   2560: 
                   2561: sub str2arrayref {
1.204     albertel 2562:   my ($string) = @_;
1.265     albertel 2563:   my @array;
                   2564: 
                   2565:   if($string !~ /^__ARRAY_REF__/) {
                   2566:       if (! ($string eq '' || !defined($string))) {
                   2567: 	  $array[0]='Array reference error';
                   2568:       }
                   2569:       return (\@array, $string);
                   2570:   }
                   2571: 
                   2572:   $string =~ s/^__ARRAY_REF__//;
                   2573: 
                   2574:   while($string !~ /^__END_ARRAY_REF__/) {
                   2575:       my $value='';
                   2576:       if($string =~ /^__HASH_REF__/) {
                   2577:           ($value, $string)=&str2hashref($string);
                   2578:           if(defined($value->{'error'})) {
                   2579:               $array[0] ='Array reference error';
                   2580:               return (\@array, $string);
                   2581:           }
                   2582:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2583:           ($value, $string)=&str2arrayref($string);
                   2584:           if($value->[0] eq 'Array reference error') {
                   2585:               $array[0] ='Array reference error';
                   2586:               return (\@array, $string);
                   2587:           }
                   2588:       } else {
                   2589: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   2590:       }
                   2591:       $string =~ s/^&//;
                   2592: 
                   2593:       push(@array, $value);
1.191     harris41 2594:   }
1.265     albertel 2595: 
                   2596:   $string =~ s/^__END_ARRAY_REF__//;
                   2597: 
                   2598:   return (\@array, $string);
1.168     albertel 2599: }
                   2600: 
1.167     albertel 2601: # -------------------------------------------------------------------Temp Store
                   2602: 
1.168     albertel 2603: sub tmpreset {
                   2604:   my ($symb,$namespace,$domain,$stuname) = @_;
                   2605:   if (!$symb) {
                   2606:     $symb=&symbread();
1.620     albertel 2607:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2608:   }
                   2609:   $symb=escape($symb);
                   2610: 
1.620     albertel 2611:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 2612:   $namespace=~s/\//\_/g;
                   2613:   $namespace=~s/\W//g;
                   2614: 
1.620     albertel 2615:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2616:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2617:   if ($domain eq 'public' && $stuname eq 'public') {
                   2618:       $stuname=$ENV{'REMOTE_ADDR'};
                   2619:   }
1.168     albertel 2620:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2621:   my %hash;
                   2622:   if (tie(%hash,'GDBM_File',
                   2623: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2624: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2625:     foreach my $key (keys %hash) {
1.180     albertel 2626:       if ($key=~ /:$symb/) {
1.168     albertel 2627: 	delete($hash{$key});
                   2628:       }
                   2629:     }
                   2630:   }
                   2631: }
                   2632: 
1.167     albertel 2633: sub tmpstore {
1.168     albertel 2634:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2635: 
                   2636:   if (!$symb) {
                   2637:     $symb=&symbread();
1.620     albertel 2638:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2639:   }
                   2640:   $symb=escape($symb);
                   2641: 
                   2642:   if (!$namespace) {
                   2643:     # I don't think we would ever want to store this for a course.
                   2644:     # it seems this will only be used if we don't have a course.
1.620     albertel 2645:     #$namespace=$env{'request.course.id'};
1.168     albertel 2646:     #if (!$namespace) {
1.620     albertel 2647:       $namespace=$env{'request.state'};
1.168     albertel 2648:     #}
                   2649:   }
                   2650:   $namespace=~s/\//\_/g;
                   2651:   $namespace=~s/\W//g;
1.620     albertel 2652:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2653:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2654:   if ($domain eq 'public' && $stuname eq 'public') {
                   2655:       $stuname=$ENV{'REMOTE_ADDR'};
                   2656:   }
1.168     albertel 2657:   my $now=time;
                   2658:   my %hash;
                   2659:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2660:   if (tie(%hash,'GDBM_File',
                   2661: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2662: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2663:     $hash{"version:$symb"}++;
                   2664:     my $version=$hash{"version:$symb"};
                   2665:     my $allkeys=''; 
                   2666:     foreach my $key (keys(%$storehash)) {
                   2667:       $allkeys.=$key.':';
1.591     albertel 2668:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 2669:     }
                   2670:     $hash{"$version:$symb:timestamp"}=$now;
                   2671:     $allkeys.='timestamp';
                   2672:     $hash{"$version:keys:$symb"}=$allkeys;
                   2673:     if (untie(%hash)) {
                   2674:       return 'ok';
                   2675:     } else {
                   2676:       return "error:$!";
                   2677:     }
                   2678:   } else {
                   2679:     return "error:$!";
                   2680:   }
                   2681: }
1.167     albertel 2682: 
1.168     albertel 2683: # -----------------------------------------------------------------Temp Restore
1.167     albertel 2684: 
1.168     albertel 2685: sub tmprestore {
                   2686:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 2687: 
1.168     albertel 2688:   if (!$symb) {
                   2689:     $symb=&symbread();
1.620     albertel 2690:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2691:   }
                   2692:   $symb=escape($symb);
                   2693: 
1.620     albertel 2694:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 2695: 
1.620     albertel 2696:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2697:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2698:   if ($domain eq 'public' && $stuname eq 'public') {
                   2699:       $stuname=$ENV{'REMOTE_ADDR'};
                   2700:   }
1.168     albertel 2701:   my %returnhash;
                   2702:   $namespace=~s/\//\_/g;
                   2703:   $namespace=~s/\W//g;
                   2704:   my %hash;
                   2705:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2706:   if (tie(%hash,'GDBM_File',
                   2707: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2708: 	  &GDBM_READER(),0640)) {
1.168     albertel 2709:     my $version=$hash{"version:$symb"};
                   2710:     $returnhash{'version'}=$version;
                   2711:     my $scope;
                   2712:     for ($scope=1;$scope<=$version;$scope++) {
                   2713:       my $vkeys=$hash{"$scope:keys:$symb"};
                   2714:       my @keys=split(/:/,$vkeys);
                   2715:       my $key;
                   2716:       $returnhash{"$scope:keys"}=$vkeys;
                   2717:       foreach $key (@keys) {
1.591     albertel 2718: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   2719: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 2720:       }
                   2721:     }
1.168     albertel 2722:     if (!(untie(%hash))) {
                   2723:       return "error:$!";
                   2724:     }
                   2725:   } else {
                   2726:     return "error:$!";
                   2727:   }
                   2728:   return %returnhash;
1.167     albertel 2729: }
                   2730: 
1.9       www      2731: # ----------------------------------------------------------------------- Store
                   2732: 
                   2733: sub store {
1.124     www      2734:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2735:     my $home='';
                   2736: 
1.168     albertel 2737:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2738: 
1.213     www      2739:     $symb=&symbclean($symb);
1.122     albertel 2740:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2741: 
1.620     albertel 2742:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2743:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2744: 
                   2745:     &devalidate($symb,$stuname,$domain);
1.109     www      2746: 
                   2747:     $symb=escape($symb);
1.187     www      2748:     if (!$namespace) { 
1.620     albertel 2749:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2750:           return ''; 
                   2751:        } 
                   2752:     }
1.620     albertel 2753:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2754: 
                   2755:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2756:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   2757: 
1.12      www      2758:     my $namevalue='';
1.800     albertel 2759:     foreach my $key (keys(%$storehash)) {
                   2760:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 2761:     }
1.12      www      2762:     $namevalue=~s/\&$//;
1.187     www      2763:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      2764:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      2765: }
                   2766: 
1.47      www      2767: # -------------------------------------------------------------- Critical Store
                   2768: 
                   2769: sub cstore {
1.124     www      2770:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2771:     my $home='';
                   2772: 
1.168     albertel 2773:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2774: 
1.213     www      2775:     $symb=&symbclean($symb);
1.122     albertel 2776:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2777: 
1.620     albertel 2778:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2779:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2780: 
                   2781:     &devalidate($symb,$stuname,$domain);
1.109     www      2782: 
                   2783:     $symb=escape($symb);
1.187     www      2784:     if (!$namespace) { 
1.620     albertel 2785:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2786:           return ''; 
                   2787:        } 
                   2788:     }
1.620     albertel 2789:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2790: 
                   2791:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2792:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 2793: 
1.47      www      2794:     my $namevalue='';
1.800     albertel 2795:     foreach my $key (keys(%$storehash)) {
                   2796:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 2797:     }
1.47      www      2798:     $namevalue=~s/\&$//;
1.187     www      2799:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      2800:     return critical
                   2801:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      2802: }
                   2803: 
1.9       www      2804: # --------------------------------------------------------------------- Restore
                   2805: 
                   2806: sub restore {
1.124     www      2807:     my ($symb,$namespace,$domain,$stuname) = @_;
                   2808:     my $home='';
                   2809: 
1.168     albertel 2810:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2811: 
1.122     albertel 2812:     if (!$symb) {
                   2813:       unless ($symb=escape(&symbread())) { return ''; }
                   2814:     } else {
1.213     www      2815:       $symb=&escape(&symbclean($symb));
1.122     albertel 2816:     }
1.188     www      2817:     if (!$namespace) { 
1.620     albertel 2818:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      2819:           return ''; 
                   2820:        } 
                   2821:     }
1.620     albertel 2822:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2823:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   2824:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 2825:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   2826: 
1.12      www      2827:     my %returnhash=();
1.800     albertel 2828:     foreach my $line (split(/\&/,$answer)) {
                   2829: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 2830:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 2831:     }
1.75      www      2832:     my $version;
                   2833:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 2834:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   2835:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 2836:        }
1.75      www      2837:     }
1.13      www      2838:     return %returnhash;
1.34      www      2839: }
                   2840: 
                   2841: # ---------------------------------------------------------- Course Description
                   2842: 
                   2843: sub coursedescription {
1.731     albertel 2844:     my ($courseid,$args)=@_;
1.34      www      2845:     $courseid=~s/^\///;
1.49      www      2846:     $courseid=~s/\_/\//g;
1.34      www      2847:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 2848:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 2849:     my $normalid=$cdomain.'_'.$cnum;
                   2850:     # need to always cache even if we get errors otherwise we keep 
                   2851:     # trying and trying and trying to get the course description.
                   2852:     my %envhash=();
                   2853:     my %returnhash=();
1.731     albertel 2854:     
                   2855:     my $expiretime=600;
                   2856:     if ($env{'request.course.id'} eq $normalid) {
                   2857: 	$expiretime=120;
                   2858:     }
                   2859: 
                   2860:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   2861:     if (!$args->{'freshen_cache'}
                   2862: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   2863: 	foreach my $key (keys(%env)) {
                   2864: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   2865: 	    my ($setting) = $1;
                   2866: 	    $returnhash{$setting} = $env{$key};
                   2867: 	}
                   2868: 	return %returnhash;
                   2869:     }
                   2870: 
                   2871:     # get the data agin
                   2872:     if (!$args->{'one_time'}) {
                   2873: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   2874:     }
1.811     albertel 2875: 
1.34      www      2876:     if ($chome ne 'no_host') {
1.302     albertel 2877:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 2878:        if (!exists($returnhash{'con_lost'})) {
                   2879:            $returnhash{'home'}= $chome;
                   2880: 	   $returnhash{'domain'} = $cdomain;
                   2881: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  2882:            if (!defined($returnhash{'type'})) {
                   2883:                $returnhash{'type'} = 'Course';
                   2884:            }
1.130     albertel 2885:            while (my ($name,$value) = each %returnhash) {
1.53      www      2886:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 2887:            }
1.270     www      2888:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      2889:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 2890: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      2891:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   2892:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   2893:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      2894:        }
                   2895:     }
1.731     albertel 2896:     if (!$args->{'one_time'}) {
                   2897: 	&appenv(%envhash);
                   2898:     }
1.302     albertel 2899:     return %returnhash;
1.461     www      2900: }
                   2901: 
                   2902: # -------------------------------------------------See if a user is privileged
                   2903: 
                   2904: sub privileged {
                   2905:     my ($username,$domain)=@_;
                   2906:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   2907: 			&homeserver($username,$domain));
                   2908:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   2909:     my $now=time;
                   2910:     if ($rolesdump ne '') {
1.800     albertel 2911:         foreach my $entry (split(/&/,$rolesdump)) {
                   2912: 	    if ($entry!~/^rolesdef_/) {
                   2913: 		my ($area,$role)=split(/=/,$entry);
1.461     www      2914: 		$area=~s/\_\w\w$//;
                   2915: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   2916: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   2917: 		    my $active=1;
                   2918: 		    if ($tend) {
                   2919: 			if ($tend<$now) { $active=0; }
                   2920: 		    }
                   2921: 		    if ($tstart) {
                   2922: 			if ($tstart>$now) { $active=0; }
                   2923: 		    }
                   2924: 		    if ($active) { return 1; }
                   2925: 		}
                   2926: 	    }
                   2927: 	}
                   2928:     }
                   2929:     return 0;
1.9       www      2930: }
1.1       albertel 2931: 
1.103     harris41 2932: # -------------------------------------------------------- Get user privileges
1.11      www      2933: 
                   2934: sub rolesinit {
                   2935:     my ($domain,$username,$authhost)=@_;
                   2936:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12      www      2937:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11      www      2938:     my %allroles=();
1.678     raeburn  2939:     my %allgroups=();   
1.11      www      2940:     my $now=time;
1.743     albertel 2941:     my %userroles = ('user.login.time' => $now);
1.678     raeburn  2942:     my $group_privs;
1.11      www      2943: 
                   2944:     if ($rolesdump ne '') {
1.800     albertel 2945:         foreach my $entry (split(/&/,$rolesdump)) {
                   2946: 	  if ($entry!~/^rolesdef_/) {
                   2947:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 2948: 	    $area=~s/\_\w\w$//;
1.678     raeburn  2949:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 2950: 	    if ($role=~/^cr/) { 
1.807     albertel 2951: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   2952: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 2953: 		    ($tend,$tstart)=split('_',$trest);
                   2954: 		} else {
                   2955: 		    $trole=$role;
                   2956: 		}
1.678     raeburn  2957:             } elsif ($role =~ m|^gr/|) {
                   2958:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   2959:                 ($trole,$group_privs) = split(/\//,$trole);
                   2960:                 $group_privs = &unescape($group_privs);
1.587     albertel 2961: 	    } else {
                   2962: 		($trole,$tend,$tstart)=split(/_/,$role);
                   2963: 	    }
1.743     albertel 2964: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   2965: 					 $username);
                   2966: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  2967:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   2968:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      2969:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 2970: 		my $spec=$trole.'.'.$area;
                   2971: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   2972: 		if ($trole =~ /^cr\//) {
1.567     raeburn  2973:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  2974:                 } elsif ($trole eq 'gr') {
                   2975:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 2976: 		} else {
1.567     raeburn  2977:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 2978: 		}
1.12      www      2979:             }
1.662     raeburn  2980:           }
1.191     harris41 2981:         }
1.743     albertel 2982:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   2983:         $userroles{'user.adv'}    = $adv;
                   2984: 	$userroles{'user.author'} = $author;
1.620     albertel 2985:         $env{'user.adv'}=$adv;
1.11      www      2986:     }
1.743     albertel 2987:     return \%userroles;  
1.11      www      2988: }
                   2989: 
1.567     raeburn  2990: sub set_arearole {
                   2991:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   2992: # log the associated role with the area
                   2993:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 2994:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  2995: }
                   2996: 
                   2997: sub custom_roleprivs {
                   2998:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   2999:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   3000:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 3001:     if (&hostname($homsvr) ne '') {
1.567     raeburn  3002:         my ($rdummy,$roledef)=
                   3003:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   3004:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   3005:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   3006:             if (defined($syspriv)) {
                   3007:                 $$allroles{'cm./'}.=':'.$syspriv;
                   3008:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   3009:             }
                   3010:             if ($tdomain ne '') {
                   3011:                 if (defined($dompriv)) {
                   3012:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   3013:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   3014:                 }
                   3015:                 if (($trest ne '') && (defined($coursepriv))) {
                   3016:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   3017:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   3018:                 }
                   3019:             }
                   3020:         }
                   3021:     }
                   3022: }
                   3023: 
1.678     raeburn  3024: sub group_roleprivs {
                   3025:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   3026:     my $access = 1;
                   3027:     my $now = time;
                   3028:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   3029:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   3030:     if ($access) {
1.811     albertel 3031:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  3032:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   3033:     }
                   3034: }
1.567     raeburn  3035: 
                   3036: sub standard_roleprivs {
                   3037:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   3038:     if (defined($pr{$trole.':s'})) {
                   3039:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   3040:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   3041:     }
                   3042:     if ($tdomain ne '') {
                   3043:         if (defined($pr{$trole.':d'})) {
                   3044:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3045:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3046:         }
                   3047:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   3048:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   3049:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   3050:         }
                   3051:     }
                   3052: }
                   3053: 
                   3054: sub set_userprivs {
1.678     raeburn  3055:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  3056:     my $author=0;
                   3057:     my $adv=0;
1.678     raeburn  3058:     my %grouproles = ();
                   3059:     if (keys(%{$allgroups}) > 0) {
                   3060:         foreach my $role (keys %{$allroles}) {
1.681     raeburn  3061:             my ($trole,$area,$sec,$extendedarea);
1.811     albertel 3062:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)-) {
1.678     raeburn  3063:                 $trole = $1;
                   3064:                 $area = $2;
1.681     raeburn  3065:                 $sec = $3;
                   3066:                 $extendedarea = $area.$sec;
                   3067:                 if (exists($$allgroups{$area})) {
                   3068:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   3069:                         my $spec = $trole.'.'.$extendedarea;
                   3070:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   3071:                                                 $$allgroups{$area}{$group};
1.678     raeburn  3072:                     }
                   3073:                 }
                   3074:             }
                   3075:         }
                   3076:     }
1.800     albertel 3077:     foreach my $group (keys(%grouproles)) {
                   3078:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  3079:     }
1.800     albertel 3080:     foreach my $role (keys(%{$allroles})) {
                   3081:         my %thesepriv;
                   3082:         if (($role=~/^au/) || ($role=~/^ca/)) { $author=1; }
                   3083:         foreach my $item (split(/:/,$$allroles{$role})) {
                   3084:             if ($item ne '') {
                   3085:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  3086:                 if ($restrictions eq '') {
                   3087:                     $thesepriv{$privilege}='F';
                   3088:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   3089:                     $thesepriv{$privilege}.=$restrictions;
                   3090:                 }
                   3091:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   3092:             }
                   3093:         }
                   3094:         my $thesestr='';
1.800     albertel 3095:         foreach my $priv (keys(%thesepriv)) {
                   3096: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   3097: 	}
                   3098:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  3099:     }
                   3100:     return ($author,$adv);
                   3101: }
                   3102: 
1.12      www      3103: # --------------------------------------------------------------- get interface
                   3104: 
                   3105: sub get {
1.131     albertel 3106:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3107:    my $items='';
1.800     albertel 3108:    foreach my $item (@$storearr) {
                   3109:        $items.=&escape($item).'&';
1.191     harris41 3110:    }
1.12      www      3111:    $items=~s/\&$//;
1.620     albertel 3112:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3113:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 3114:    my $uhome=&homeserver($uname,$udomain);
                   3115: 
1.133     albertel 3116:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3117:    my @pairs=split(/\&/,$rep);
1.273     albertel 3118:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   3119:      return @pairs;
                   3120:    }
1.15      www      3121:    my %returnhash=();
1.42      www      3122:    my $i=0;
1.800     albertel 3123:    foreach my $item (@$storearr) {
                   3124:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3125:       $i++;
1.191     harris41 3126:    }
1.15      www      3127:    return %returnhash;
1.27      www      3128: }
                   3129: 
                   3130: # --------------------------------------------------------------- del interface
                   3131: 
                   3132: sub del {
1.133     albertel 3133:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      3134:    my $items='';
1.800     albertel 3135:    foreach my $item (@$storearr) {
                   3136:        $items.=&escape($item).'&';
1.191     harris41 3137:    }
1.27      www      3138:    $items=~s/\&$//;
1.620     albertel 3139:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3140:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3141:    my $uhome=&homeserver($uname,$udomain);
                   3142: 
                   3143:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3144: }
                   3145: 
                   3146: # -------------------------------------------------------------- dump interface
                   3147: 
                   3148: sub dump {
1.755     albertel 3149:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   3150:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3151:     if (!$uname) { $uname=$env{'user.name'}; }
                   3152:     my $uhome=&homeserver($uname,$udomain);
                   3153:     if ($regexp) {
                   3154: 	$regexp=&escape($regexp);
                   3155:     } else {
                   3156: 	$regexp='.';
                   3157:     }
                   3158:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3159:     my @pairs=split(/\&/,$rep);
                   3160:     my %returnhash=();
                   3161:     foreach my $item (@pairs) {
                   3162: 	my ($key,$value)=split(/=/,$item,2);
                   3163: 	$key = &unescape($key);
                   3164: 	next if ($key =~ /^error: 2 /);
                   3165: 	$returnhash{$key}=&thaw_unescape($value);
                   3166:     }
                   3167:     return %returnhash;
1.407     www      3168: }
                   3169: 
1.717     albertel 3170: # --------------------------------------------------------- dumpstore interface
                   3171: 
                   3172: sub dumpstore {
                   3173:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 3174:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3175:    if (!$uname) { $uname=$env{'user.name'}; }
                   3176:    my $uhome=&homeserver($uname,$udomain);
                   3177:    if ($regexp) {
                   3178:        $regexp=&escape($regexp);
                   3179:    } else {
                   3180:        $regexp='.';
                   3181:    }
                   3182:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3183:    my @pairs=split(/\&/,$rep);
                   3184:    my %returnhash=();
                   3185:    foreach my $item (@pairs) {
                   3186:        my ($key,$value)=split(/=/,$item,2);
                   3187:        next if ($key =~ /^error: 2 /);
                   3188:        $returnhash{$key}=&thaw_unescape($value);
                   3189:    }
                   3190:    return %returnhash;
1.717     albertel 3191: }
                   3192: 
1.407     www      3193: # -------------------------------------------------------------- keys interface
                   3194: 
                   3195: sub getkeys {
                   3196:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 3197:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3198:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      3199:    my $uhome=&homeserver($uname,$udomain);
                   3200:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   3201:    my @keyarray=();
1.800     albertel 3202:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  3203:       next if ($key =~ /^error: 2 /);
1.800     albertel 3204:       push(@keyarray,&unescape($key));
1.407     www      3205:    }
                   3206:    return @keyarray;
1.318     matthew  3207: }
                   3208: 
1.319     matthew  3209: # --------------------------------------------------------------- currentdump
                   3210: sub currentdump {
1.328     matthew  3211:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 3212:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   3213:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   3214:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  3215:    my $uhome = &homeserver($sname,$sdom);
                   3216:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  3217:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  3218:    #
1.318     matthew  3219:    my %returnhash=();
1.319     matthew  3220:    #
                   3221:    if ($rep eq "unknown_cmd") { 
                   3222:        # an old lond will not know currentdump
                   3223:        # Do a dump and make it look like a currentdump
1.822     albertel 3224:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  3225:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   3226:        my %hash = @tmp;
                   3227:        @tmp=();
1.424     matthew  3228:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  3229:    } else {
                   3230:        my @pairs=split(/\&/,$rep);
1.800     albertel 3231:        foreach my $pair (@pairs) {
                   3232:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  3233:            my ($symb,$param) = split(/:/,$key);
                   3234:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 3235:                                                         &thaw_unescape($value);
1.319     matthew  3236:        }
1.191     harris41 3237:    }
1.12      www      3238:    return %returnhash;
1.424     matthew  3239: }
                   3240: 
                   3241: sub convert_dump_to_currentdump{
                   3242:     my %hash = %{shift()};
                   3243:     my %returnhash;
                   3244:     # Code ripped from lond, essentially.  The only difference
                   3245:     # here is the unescaping done by lonnet::dump().  Conceivably
                   3246:     # we might run in to problems with parameter names =~ /^v\./
                   3247:     while (my ($key,$value) = each(%hash)) {
                   3248:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 3249: 	$symb  = &unescape($symb);
                   3250: 	$param = &unescape($param);
1.424     matthew  3251:         next if ($v eq 'version' || $symb eq 'keys');
                   3252:         next if (exists($returnhash{$symb}) &&
                   3253:                  exists($returnhash{$symb}->{$param}) &&
                   3254:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   3255:         $returnhash{$symb}->{$param}=$value;
                   3256:         $returnhash{$symb}->{'v.'.$param}=$v;
                   3257:     }
                   3258:     #
                   3259:     # Remove all of the keys in the hashes which keep track of
                   3260:     # the version of the parameter.
                   3261:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   3262:         # use a foreach because we are going to delete from the hash.
                   3263:         foreach my $key (keys(%$param_hash)) {
                   3264:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   3265:         }
                   3266:     }
                   3267:     return \%returnhash;
1.12      www      3268: }
                   3269: 
1.627     albertel 3270: # ------------------------------------------------------ critical inc interface
                   3271: 
                   3272: sub cinc {
                   3273:     return &inc(@_,'critical');
                   3274: }
                   3275: 
1.449     matthew  3276: # --------------------------------------------------------------- inc interface
                   3277: 
                   3278: sub inc {
1.627     albertel 3279:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 3280:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3281:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  3282:     my $uhome=&homeserver($uname,$udomain);
                   3283:     my $items='';
                   3284:     if (! ref($store)) {
                   3285:         # got a single value, so use that instead
                   3286:         $items = &escape($store).'=&';
                   3287:     } elsif (ref($store) eq 'SCALAR') {
                   3288:         $items = &escape($$store).'=&';        
                   3289:     } elsif (ref($store) eq 'ARRAY') {
                   3290:         $items = join('=&',map {&escape($_);} @{$store});
                   3291:     } elsif (ref($store) eq 'HASH') {
                   3292:         while (my($key,$value) = each(%{$store})) {
                   3293:             $items.= &escape($key).'='.&escape($value).'&';
                   3294:         }
                   3295:     }
                   3296:     $items=~s/\&$//;
1.627     albertel 3297:     if ($critical) {
                   3298: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3299:     } else {
                   3300: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3301:     }
1.449     matthew  3302: }
                   3303: 
1.12      www      3304: # --------------------------------------------------------------- put interface
                   3305: 
                   3306: sub put {
1.134     albertel 3307:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3308:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3309:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3310:    my $uhome=&homeserver($uname,$udomain);
1.12      www      3311:    my $items='';
1.800     albertel 3312:    foreach my $item (keys(%$storehash)) {
                   3313:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3314:    }
1.12      www      3315:    $items=~s/\&$//;
1.134     albertel 3316:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      3317: }
                   3318: 
1.631     albertel 3319: # ------------------------------------------------------------ newput interface
                   3320: 
                   3321: sub newput {
                   3322:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   3323:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3324:    if (!$uname) { $uname=$env{'user.name'}; }
                   3325:    my $uhome=&homeserver($uname,$udomain);
                   3326:    my $items='';
                   3327:    foreach my $key (keys(%$storehash)) {
                   3328:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   3329:    }
                   3330:    $items=~s/\&$//;
                   3331:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   3332: }
                   3333: 
                   3334: # ---------------------------------------------------------  putstore interface
                   3335: 
1.524     raeburn  3336: sub putstore {
1.715     albertel 3337:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 3338:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3339:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  3340:    my $uhome=&homeserver($uname,$udomain);
                   3341:    my $items='';
1.715     albertel 3342:    foreach my $key (keys(%$storehash)) {
                   3343:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  3344:    }
1.715     albertel 3345:    $items=~s/\&$//;
1.716     albertel 3346:    my $esc_symb=&escape($symb);
                   3347:    my $esc_v=&escape($version);
1.715     albertel 3348:    my $reply =
1.716     albertel 3349:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 3350: 	      $uhome);
                   3351:    if ($reply eq 'unknown_cmd') {
1.716     albertel 3352:        # gfall back to way things use to be done
1.715     albertel 3353:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   3354: 			    $uname);
1.524     raeburn  3355:    }
1.715     albertel 3356:    return $reply;
                   3357: }
                   3358: 
                   3359: sub old_putstore {
1.716     albertel 3360:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   3361:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3362:     if (!$uname) { $uname=$env{'user.name'}; }
                   3363:     my $uhome=&homeserver($uname,$udomain);
                   3364:     my %newstorehash;
1.800     albertel 3365:     foreach my $item (keys(%$storehash)) {
                   3366: 	my $key = $version.':'.&escape($symb).':'.$item;
                   3367: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 3368:     }
                   3369:     my $items='';
                   3370:     my %allitems = ();
1.800     albertel 3371:     foreach my $item (keys(%newstorehash)) {
                   3372: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 3373: 	    my $key = $1.':keys:'.$2;
                   3374: 	    $allitems{$key} .= $3.':';
                   3375: 	}
1.800     albertel 3376: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 3377:     }
1.800     albertel 3378:     foreach my $item (keys(%allitems)) {
                   3379: 	$allitems{$item} =~ s/\:$//;
                   3380: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 3381:     }
                   3382:     $items=~s/\&$//;
                   3383:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  3384: }
                   3385: 
1.47      www      3386: # ------------------------------------------------------ critical put interface
                   3387: 
                   3388: sub cput {
1.134     albertel 3389:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3390:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3391:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3392:    my $uhome=&homeserver($uname,$udomain);
1.47      www      3393:    my $items='';
1.800     albertel 3394:    foreach my $item (keys(%$storehash)) {
                   3395:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3396:    }
1.47      www      3397:    $items=~s/\&$//;
1.134     albertel 3398:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3399: }
                   3400: 
                   3401: # -------------------------------------------------------------- eget interface
                   3402: 
                   3403: sub eget {
1.133     albertel 3404:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3405:    my $items='';
1.800     albertel 3406:    foreach my $item (@$storearr) {
                   3407:        $items.=&escape($item).'&';
1.191     harris41 3408:    }
1.12      www      3409:    $items=~s/\&$//;
1.620     albertel 3410:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3411:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3412:    my $uhome=&homeserver($uname,$udomain);
                   3413:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3414:    my @pairs=split(/\&/,$rep);
                   3415:    my %returnhash=();
1.42      www      3416:    my $i=0;
1.800     albertel 3417:    foreach my $item (@$storearr) {
                   3418:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3419:       $i++;
1.191     harris41 3420:    }
1.12      www      3421:    return %returnhash;
                   3422: }
                   3423: 
1.667     albertel 3424: # ------------------------------------------------------------ tmpput interface
                   3425: sub tmpput {
1.802     raeburn  3426:     my ($storehash,$server,$context)=@_;
1.667     albertel 3427:     my $items='';
1.800     albertel 3428:     foreach my $item (keys(%$storehash)) {
                   3429: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 3430:     }
                   3431:     $items=~s/\&$//;
1.802     raeburn  3432:     if (defined($context)) {
                   3433:         $items .= ':'.&escape($context);
                   3434:     }
1.667     albertel 3435:     return &reply("tmpput:$items",$server);
                   3436: }
                   3437: 
                   3438: # ------------------------------------------------------------ tmpget interface
                   3439: sub tmpget {
1.688     albertel 3440:     my ($token,$server)=@_;
                   3441:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3442:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 3443:     my %returnhash;
                   3444:     foreach my $item (split(/\&/,$rep)) {
                   3445: 	my ($key,$value)=split(/=/,$item);
                   3446: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   3447:     }
                   3448:     return %returnhash;
                   3449: }
                   3450: 
1.688     albertel 3451: # ------------------------------------------------------------ tmpget interface
                   3452: sub tmpdel {
                   3453:     my ($token,$server)=@_;
                   3454:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3455:     return &reply("tmpdel:$token",$server);
                   3456: }
                   3457: 
1.765     albertel 3458: # -------------------------------------------------- portfolio access checking
                   3459: 
                   3460: sub portfolio_access {
1.766     albertel 3461:     my ($requrl) = @_;
1.765     albertel 3462:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   3463:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  3464:     if ($result) {
                   3465:         my %setters;
                   3466:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3467:             my ($startblock,$endblock) =
                   3468:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   3469:             if ($startblock && $endblock) {
                   3470:                 return 'B';
                   3471:             }
                   3472:         } else {
                   3473:             my ($startblock,$endblock) =
                   3474:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   3475:             if ($startblock && $endblock) {
                   3476:                 return 'B';
                   3477:             }
                   3478:         }
                   3479:     }
1.765     albertel 3480:     if ($result eq 'ok') {
1.766     albertel 3481:        return 'F';
1.765     albertel 3482:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 3483:        return 'A';
1.765     albertel 3484:     }
1.766     albertel 3485:     return '';
1.765     albertel 3486: }
                   3487: 
                   3488: sub get_portfolio_access {
1.767     albertel 3489:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   3490: 
                   3491:     if (!ref($access_hash)) {
                   3492: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   3493: 	my %access_controls = &get_access_controls($current_perms,$group,
                   3494: 						   $file_name);
                   3495: 	$access_hash = $access_controls{$file_name};
                   3496:     }
                   3497: 
1.765     albertel 3498:     my ($public,$guest,@domains,@users,@courses,@groups);
                   3499:     my $now = time;
                   3500:     if (ref($access_hash) eq 'HASH') {
                   3501:         foreach my $key (keys(%{$access_hash})) {
                   3502:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   3503:             if ($start > $now) {
                   3504:                 next;
                   3505:             }
                   3506:             if ($end && $end<$now) {
                   3507:                 next;
                   3508:             }
                   3509:             if ($scope eq 'public') {
                   3510:                 $public = $key;
                   3511:                 last;
                   3512:             } elsif ($scope eq 'guest') {
                   3513:                 $guest = $key;
                   3514:             } elsif ($scope eq 'domains') {
                   3515:                 push(@domains,$key);
                   3516:             } elsif ($scope eq 'users') {
                   3517:                 push(@users,$key);
                   3518:             } elsif ($scope eq 'course') {
                   3519:                 push(@courses,$key);
                   3520:             } elsif ($scope eq 'group') {
                   3521:                 push(@groups,$key);
                   3522:             }
                   3523:         }
                   3524:         if ($public) {
                   3525:             return 'ok';
                   3526:         }
                   3527:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3528:             if ($guest) {
                   3529:                 return $guest;
                   3530:             }
                   3531:         } else {
                   3532:             if (@domains > 0) {
                   3533:                 foreach my $domkey (@domains) {
                   3534:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   3535:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   3536:                             return 'ok';
                   3537:                         }
                   3538:                     }
                   3539:                 }
                   3540:             }
                   3541:             if (@users > 0) {
                   3542:                 foreach my $userkey (@users) {
                   3543:                     if (exists($access_hash->{$userkey}{'users'}{$env{'user.name'}.':'.$env{'user.domain'}})) {
                   3544:                         return 'ok';
                   3545:                     }
                   3546:                 }
                   3547:             }
                   3548:             my %roleshash;
                   3549:             my @courses_and_groups = @courses;
                   3550:             push(@courses_and_groups,@groups); 
                   3551:             if (@courses_and_groups > 0) {
                   3552:                 my (%allgroups,%allroles); 
                   3553:                 my ($start,$end,$role,$sec,$group);
                   3554:                 foreach my $envkey (%env) {
1.811     albertel 3555:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 3556:                         my $cid = $2.'_'.$3; 
                   3557:                         if ($1 eq 'gr') {
                   3558:                             $group = $4;
                   3559:                             $allgroups{$cid}{$group} = $env{$envkey};
                   3560:                         } else {
                   3561:                             if ($4 eq '') {
                   3562:                                 $sec = 'none';
                   3563:                             } else {
                   3564:                                 $sec = $4;
                   3565:                             }
                   3566:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3567:                         }
1.811     albertel 3568:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 3569:                         my $cid = $2.'_'.$3;
                   3570:                         if ($4 eq '') {
                   3571:                             $sec = 'none';
                   3572:                         } else {
                   3573:                             $sec = $4;
                   3574:                         }
                   3575:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3576:                     }
                   3577:                 }
                   3578:                 if (keys(%allroles) == 0) {
                   3579:                     return;
                   3580:                 }
                   3581:                 foreach my $key (@courses_and_groups) {
                   3582:                     my %content = %{$$access_hash{$key}};
                   3583:                     my $cnum = $content{'number'};
                   3584:                     my $cdom = $content{'domain'};
                   3585:                     my $cid = $cdom.'_'.$cnum;
                   3586:                     if (!exists($allroles{$cid})) {
                   3587:                         next;
                   3588:                     }    
                   3589:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   3590:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   3591:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   3592:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   3593:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   3594:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   3595:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   3596:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   3597:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   3598:                                         if (grep/^all$/,@sections) {
                   3599:                                             return 'ok';
                   3600:                                         } else {
                   3601:                                             if (grep/^$sec$/,@sections) {
                   3602:                                                 return 'ok';
                   3603:                                             }
                   3604:                                         }
                   3605:                                     }
                   3606:                                 }
                   3607:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   3608:                                     if (grep/^none$/,@groups) {
                   3609:                                         return 'ok';
                   3610:                                     }
                   3611:                                 } else {
                   3612:                                     if (grep/^all$/,@groups) {
                   3613:                                         return 'ok';
                   3614:                                     } 
                   3615:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   3616:                                         if (grep/^$group$/,@groups) {
                   3617:                                             return 'ok';
                   3618:                                         }
                   3619:                                     }
                   3620:                                 } 
                   3621:                             }
                   3622:                         }
                   3623:                     }
                   3624:                 }
                   3625:             }
                   3626:             if ($guest) {
                   3627:                 return $guest;
                   3628:             }
                   3629:         }
                   3630:     }
                   3631:     return;
                   3632: }
                   3633: 
                   3634: sub course_group_datechecker {
                   3635:     my ($dates,$now,$status) = @_;
                   3636:     my ($start,$end) = split(/\./,$dates);
                   3637:     if (!$start && !$end) {
                   3638:         return 'ok';
                   3639:     }
                   3640:     if (grep/^active$/,@{$status}) {
                   3641:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   3642:             return 'ok';
                   3643:         }
                   3644:     }
                   3645:     if (grep/^previous$/,@{$status}) {
                   3646:         if ($end > $now ) {
                   3647:             return 'ok';
                   3648:         }
                   3649:     }
                   3650:     if (grep/^future$/,@{$status}) {
                   3651:         if ($start > $now) {
                   3652:             return 'ok';
                   3653:         }
                   3654:     }
                   3655:     return; 
                   3656: }
                   3657: 
                   3658: sub parse_portfolio_url {
                   3659:     my ($url) = @_;
                   3660: 
                   3661:     my ($type,$udom,$unum,$group,$file_name);
                   3662:     
1.823     albertel 3663:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 3664: 	$type = 1;
                   3665:         $udom = $1;
                   3666:         $unum = $2;
                   3667:         $file_name = $3;
1.823     albertel 3668:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 3669: 	$type = 2;
                   3670:         $udom = $1;
                   3671:         $unum = $2;
                   3672:         $group = $3;
                   3673:         $file_name = $3.'/'.$4;
                   3674:     }
                   3675:     if (wantarray) {
                   3676: 	return ($type,$udom,$unum,$file_name,$group);
                   3677:     }
                   3678:     return $type;
                   3679: }
                   3680: 
                   3681: sub is_portfolio_url {
                   3682:     my ($url) = @_;
                   3683:     return scalar(&parse_portfolio_url($url));
                   3684: }
                   3685: 
1.798     raeburn  3686: sub is_portfolio_file {
                   3687:     my ($file) = @_;
1.820     raeburn  3688:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  3689:         return 1;
                   3690:     }
                   3691:     return;
                   3692: }
                   3693: 
                   3694: 
1.341     www      3695: # ---------------------------------------------- Custom access rule evaluation
                   3696: 
                   3697: sub customaccess {
                   3698:     my ($priv,$uri)=@_;
1.807     albertel 3699:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      3700:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 3701:     $udom = &LONCAPA::clean_domain($udom);
                   3702:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      3703:     my $access=0;
1.800     albertel 3704:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
                   3705: 	my ($effect,$realm,$role)=split(/\:/,$right);
1.343     www      3706:         if ($role) {
                   3707: 	   if ($role ne $urole) { next; }
                   3708:         }
1.800     albertel 3709:         foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   3710:             my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
1.343     www      3711:             if ($tdom) {
                   3712: 		if ($tdom ne $udom) { next; }
                   3713:             }
                   3714:             if ($tcrs) {
                   3715: 		if ($tcrs ne $ucrs) { next; }
                   3716:             }
                   3717:             if ($tsec) {
                   3718: 		if ($tsec ne $usec) { next; }
                   3719:             }
                   3720:             $access=($effect eq 'allow');
                   3721:             last;
1.342     www      3722:         }
1.402     bowersj2 3723: 	if ($realm eq '' && $role eq '') {
                   3724:             $access=($effect eq 'allow');
                   3725: 	}
1.341     www      3726:     }
                   3727:     return $access;
                   3728: }
                   3729: 
1.103     harris41 3730: # ------------------------------------------------- Check for a user privilege
1.12      www      3731: 
                   3732: sub allowed {
1.810     raeburn  3733:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 3734:     my $ver_orguri=$uri;
1.439     www      3735:     $uri=&deversion($uri);
1.152     www      3736:     my $orguri=$uri;
1.52      www      3737:     $uri=&declutter($uri);
1.809     raeburn  3738: 
1.810     raeburn  3739:     if ($priv eq 'evb') {
                   3740: # Evade communication block restrictions for specified role in a course
                   3741:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   3742:             return $1;
                   3743:         } else {
                   3744:             return;
                   3745:         }
                   3746:     }
                   3747: 
1.620     albertel 3748:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      3749: # Free bre access to adm and meta resources
1.775     albertel 3750:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 3751: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   3752: 	&& ($priv eq 'bre')) {
1.14      www      3753: 	return 'F';
1.159     www      3754:     }
                   3755: 
1.545     banghart 3756: # Free bre access to user's own portfolio contents
1.714     raeburn  3757:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  3758:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  3759: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  3760:         my %setters;
                   3761:         my ($startblock,$endblock) = 
                   3762:             &Apache::loncommon::blockcheck(\%setters,'port');
                   3763:         if ($startblock && $endblock) {
                   3764:             return 'B';
                   3765:         } else {
                   3766:             return 'F';
                   3767:         }
1.545     banghart 3768:     }
                   3769: 
1.762     raeburn  3770: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  3771:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   3772:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   3773:         if (exists($env{'request.course.id'})) {
                   3774:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3775:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3776:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   3777:                 my $courseprivid=$env{'request.course.id'};
                   3778:                 $courseprivid=~s/\_/\//;
                   3779:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   3780:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   3781:                     return $1; 
1.762     raeburn  3782:                 } else {
                   3783:                     if ($env{'request.course.sec'}) {
                   3784:                         $courseprivid.='/'.$env{'request.course.sec'};
                   3785:                     }
                   3786:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   3787:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   3788:                         return $2;
                   3789:                     }
1.714     raeburn  3790:                 }
                   3791:             }
                   3792:         }
                   3793:     }
                   3794: 
1.159     www      3795: # Free bre to public access
                   3796: 
                   3797:     if ($priv eq 'bre') {
1.238     www      3798:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 3799: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      3800:            return 'F'; 
                   3801:         }
1.238     www      3802:         if ($copyright eq 'priv') {
                   3803:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3804: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      3805: 		return '';
                   3806:             }
                   3807:         }
                   3808:         if ($copyright eq 'domain') {
                   3809:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3810: 	    unless (($env{'user.domain'} eq $1) ||
                   3811:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      3812: 		return '';
                   3813:             }
1.262     matthew  3814:         }
1.620     albertel 3815:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  3816:             # Library role, so allow browsing of resources in this domain.
                   3817:             return 'F';
1.238     www      3818:         }
1.341     www      3819:         if ($copyright eq 'custom') {
                   3820: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   3821:         }
1.14      www      3822:     }
1.264     matthew  3823:     # Domain coordinator is trying to create a course
1.620     albertel 3824:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  3825:         # uri is the requested domain in this case.
                   3826:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  3827:         # a role of dc for the domain in question.
1.620     albertel 3828:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  3829:     }
1.29      www      3830: 
1.52      www      3831:     my $thisallowed='';
                   3832:     my $statecond=0;
                   3833:     my $courseprivid='';
                   3834: 
                   3835: # Course
                   3836: 
1.620     albertel 3837:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3838:        $thisallowed.=$1;
                   3839:     }
1.29      www      3840: 
1.52      www      3841: # Domain
                   3842: 
1.620     albertel 3843:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 3844:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3845:        $thisallowed.=$1;
                   3846:     }
1.52      www      3847: 
                   3848: # Course: uri itself is a course
1.66      www      3849:     my $courseuri=$uri;
                   3850:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      3851:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      3852: 
1.620     albertel 3853:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 3854:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3855:        $thisallowed.=$1;
                   3856:     }
1.29      www      3857: 
1.665     albertel 3858: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 3859: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 3860:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 3861: 	$thisallowed='';
1.671     raeburn  3862:         my ($match)=&is_on_map($uri);
                   3863:         if ($match) {
                   3864:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   3865:                   =~/\Q$priv\E\&([^\:]*)/) {
                   3866:                 $thisallowed.=$1;
                   3867:             }
                   3868:         } else {
1.705     albertel 3869:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  3870:             if ($refuri) {
                   3871:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  3872:                     $thisallowed='F';
1.671     raeburn  3873:                 } else {
                   3874:                     $refuri=&declutter($refuri);
                   3875:                     my ($match) = &is_on_map($refuri);
                   3876:                     if ($match) {
                   3877:                         $thisallowed='F';
                   3878:                     }
1.669     raeburn  3879:                 }
1.671     raeburn  3880:             }
                   3881:         }
1.314     www      3882:     }
1.492     albertel 3883: 
1.766     albertel 3884:     if ($priv eq 'bre'
                   3885: 	&& $thisallowed ne 'F' 
                   3886: 	&& $thisallowed ne '2'
                   3887: 	&& &is_portfolio_url($uri)) {
                   3888: 	$thisallowed = &portfolio_access($uri);
                   3889:     }
                   3890:     
1.52      www      3891: # Full access at system, domain or course-wide level? Exit.
1.29      www      3892: 
                   3893:     if ($thisallowed=~/F/) {
                   3894: 	return 'F';
                   3895:     }
                   3896: 
1.52      www      3897: # If this is generating or modifying users, exit with special codes
1.29      www      3898: 
1.643     www      3899:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   3900: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 3901: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      3902: # no author name given, so this just checks on the general right to make a co-author in this domain
                   3903: 	    unless ($auname) { return $thisallowed; }
                   3904: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 3905: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   3906: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   3907: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   3908: 	}
1.52      www      3909: 	return $thisallowed;
                   3910:     }
                   3911: #
1.103     harris41 3912: # Gathered so far: system, domain and course wide privileges
1.52      www      3913: #
                   3914: # Course: See if uri or referer is an individual resource that is part of 
                   3915: # the course
                   3916: 
1.620     albertel 3917:     if ($env{'request.course.id'}) {
1.232     www      3918: 
1.620     albertel 3919:        $courseprivid=$env{'request.course.id'};
                   3920:        if ($env{'request.course.sec'}) {
                   3921:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      3922:        }
                   3923:        $courseprivid=~s/\_/\//;
                   3924:        my $checkreferer=1;
1.232     www      3925:        my ($match,$cond)=&is_on_map($uri);
                   3926:        if ($match) {
                   3927:            $statecond=$cond;
1.620     albertel 3928:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 3929:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3930:                $thisallowed.=$1;
                   3931:                $checkreferer=0;
                   3932:            }
1.29      www      3933:        }
1.83      www      3934:        
1.148     www      3935:        if ($checkreferer) {
1.620     albertel 3936: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      3937:             unless ($refuri) {
1.800     albertel 3938:                 foreach my $key (keys(%env)) {
                   3939: 		    if ($key=~/^httpref\..*\*/) {
                   3940: 			my $pattern=$key;
1.156     www      3941:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      3942:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   3943:                         $pattern=~s/\//\\\//g;
1.152     www      3944:                         if ($orguri=~/$pattern/) {
1.800     albertel 3945: 			    $refuri=$env{$key};
1.148     www      3946:                         }
                   3947:                     }
1.191     harris41 3948:                 }
1.148     www      3949:             }
1.232     www      3950: 
1.148     www      3951:          if ($refuri) { 
1.152     www      3952: 	  $refuri=&declutter($refuri);
1.232     www      3953:           my ($match,$cond)=&is_on_map($refuri);
                   3954:             if ($match) {
                   3955:               my $refstatecond=$cond;
1.620     albertel 3956:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 3957:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3958:                   $thisallowed.=$1;
1.53      www      3959:                   $uri=$refuri;
                   3960:                   $statecond=$refstatecond;
1.52      www      3961:               }
                   3962:           }
1.148     www      3963:         }
1.29      www      3964:        }
1.52      www      3965:    }
1.29      www      3966: 
1.52      www      3967: #
1.103     harris41 3968: # Gathered now: all privileges that could apply, and condition number
1.52      www      3969: # 
                   3970: #
                   3971: # Full or no access?
                   3972: #
1.29      www      3973: 
1.52      www      3974:     if ($thisallowed=~/F/) {
                   3975: 	return 'F';
                   3976:     }
1.29      www      3977: 
1.52      www      3978:     unless ($thisallowed) {
                   3979:         return '';
                   3980:     }
1.29      www      3981: 
1.52      www      3982: # Restrictions exist, deal with them
                   3983: #
                   3984: #   C:according to course preferences
                   3985: #   R:according to resource settings
                   3986: #   L:unless locked
                   3987: #   X:according to user session state
                   3988: #
                   3989: 
                   3990: # Possibly locked functionality, check all courses
1.54      www      3991: # Locks might take effect only after 10 minutes cache expiration for other
                   3992: # courses, and 2 minutes for current course
1.52      www      3993: 
                   3994:     my $envkey;
                   3995:     if ($thisallowed=~/L/) {
1.620     albertel 3996:         foreach $envkey (keys %env) {
1.54      www      3997:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   3998:                my $courseid=$2;
                   3999:                my $roleid=$1.'.'.$2;
1.92      www      4000:                $courseid=~s/^\///;
1.54      www      4001:                my $expiretime=600;
1.620     albertel 4002:                if ($env{'request.role'} eq $roleid) {
1.54      www      4003: 		  $expiretime=120;
                   4004:                }
                   4005: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   4006:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 4007:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 4008: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      4009:                }
1.620     albertel 4010:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4011:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   4012: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   4013:                        &log($env{'user.domain'},$env{'user.name'},
                   4014:                             $env{'user.home'},
1.57      www      4015:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      4016:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4017:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4018: 		       return '';
                   4019:                    }
                   4020:                }
1.620     albertel 4021:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4022:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   4023: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   4024:                        &log($env{'user.domain'},$env{'user.name'},
                   4025:                             $env{'user.home'},
1.57      www      4026:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      4027:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4028:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4029: 		       return '';
                   4030:                    }
                   4031:                }
                   4032: 	   }
1.29      www      4033:        }
1.52      www      4034:     }
                   4035:    
                   4036: #
                   4037: # Rest of the restrictions depend on selected course
                   4038: #
                   4039: 
1.620     albertel 4040:     unless ($env{'request.course.id'}) {
1.766     albertel 4041: 	if ($thisallowed eq 'A') {
                   4042: 	    return 'A';
1.814     raeburn  4043:         } elsif ($thisallowed eq 'B') {
                   4044:             return 'B';
1.766     albertel 4045: 	} else {
                   4046: 	    return '1';
                   4047: 	}
1.52      www      4048:     }
1.29      www      4049: 
1.52      www      4050: #
                   4051: # Now user is definitely in a course
                   4052: #
1.53      www      4053: 
                   4054: 
                   4055: # Course preferences
                   4056: 
                   4057:    if ($thisallowed=~/C/) {
1.620     albertel 4058:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   4059:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   4060:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 4061: 	   =~/\Q$rolecode\E/) {
1.689     albertel 4062: 	   if ($priv ne 'pch') { 
                   4063: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4064: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   4065: 			$env{'request.course.id'});
                   4066: 	   }
1.237     www      4067:            return '';
                   4068:        }
                   4069: 
1.620     albertel 4070:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 4071: 	   =~/\Q$unamedom\E/) {
1.689     albertel 4072: 	   if ($priv ne 'pch') { 
                   4073: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   4074: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   4075: 			$env{'request.course.id'});
                   4076: 	   }
1.54      www      4077:            return '';
                   4078:        }
1.53      www      4079:    }
                   4080: 
                   4081: # Resource preferences
                   4082: 
                   4083:    if ($thisallowed=~/R/) {
1.620     albertel 4084:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 4085:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 4086: 	   if ($priv ne 'pch') { 
                   4087: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4088: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   4089: 	   }
                   4090: 	   return '';
1.54      www      4091:        }
1.53      www      4092:    }
1.30      www      4093: 
1.246     www      4094: # Restricted by state or randomout?
1.30      www      4095: 
1.52      www      4096:    if ($thisallowed=~/X/) {
1.620     albertel 4097:       if ($env{'acc.randomout'}) {
1.579     albertel 4098: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 4099:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      4100:             return ''; 
                   4101:          }
1.247     www      4102:       }
                   4103:       if (&condval($statecond)) {
1.52      www      4104: 	 return '2';
                   4105:       } else {
                   4106:          return '';
                   4107:       }
                   4108:    }
1.30      www      4109: 
1.766     albertel 4110:     if ($thisallowed eq 'A') {
                   4111: 	return 'A';
1.814     raeburn  4112:     } elsif ($thisallowed eq 'B') {
                   4113:         return 'B';
1.766     albertel 4114:     }
1.52      www      4115:    return 'F';
1.232     www      4116: }
                   4117: 
1.710     albertel 4118: sub split_uri_for_cond {
                   4119:     my $uri=&deversion(&declutter(shift));
                   4120:     my @uriparts=split(/\//,$uri);
                   4121:     my $filename=pop(@uriparts);
                   4122:     my $pathname=join('/',@uriparts);
                   4123:     return ($pathname,$filename);
                   4124: }
1.232     www      4125: # --------------------------------------------------- Is a resource on the map?
                   4126: 
                   4127: sub is_on_map {
1.710     albertel 4128:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 4129:     #Trying to find the conditional for the file
1.620     albertel 4130:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 4131: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      4132:     if ($match) {
1.289     bowersj2 4133: 	return (1,$1);
                   4134:     } else {
1.434     www      4135: 	return (0,0);
1.289     bowersj2 4136:     }
1.12      www      4137: }
                   4138: 
1.427     www      4139: # --------------------------------------------------------- Get symb from alias
                   4140: 
                   4141: sub get_symb_from_alias {
                   4142:     my $symb=shift;
                   4143:     my ($map,$resid,$url)=&decode_symb($symb);
                   4144: # Already is a symb
                   4145:     if ($url) { return $symb; }
                   4146: # Must be an alias
                   4147:     my $aliassymb='';
                   4148:     my %bighash;
1.620     albertel 4149:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      4150:                             &GDBM_READER(),0640)) {
                   4151:         my $rid=$bighash{'mapalias_'.$symb};
                   4152: 	if ($rid) {
                   4153: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 4154: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   4155: 				    $resid,$bighash{'src_'.$rid});
1.427     www      4156: 	}
                   4157:         untie %bighash;
                   4158:     }
                   4159:     return $aliassymb;
                   4160: }
                   4161: 
1.12      www      4162: # ----------------------------------------------------------------- Define Role
                   4163: 
                   4164: sub definerole {
                   4165:   if (allowed('mcr','/')) {
                   4166:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 4167:     foreach my $role (split(':',$sysrole)) {
                   4168: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4169:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   4170:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   4171: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4172:                return "refused:s:$crole&$cqual"; 
                   4173:             }
                   4174:         }
1.191     harris41 4175:     }
1.800     albertel 4176:     foreach my $role (split(':',$domrole)) {
                   4177: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4178:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   4179:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   4180: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      4181:                return "refused:d:$crole&$cqual"; 
                   4182:             }
                   4183:         }
1.191     harris41 4184:     }
1.800     albertel 4185:     foreach my $role (split(':',$courole)) {
                   4186: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4187:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   4188:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   4189: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4190:                return "refused:c:$crole&$cqual"; 
                   4191:             }
                   4192:         }
1.191     harris41 4193:     }
1.620     albertel 4194:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   4195:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4196: 	        "rolesdef_$rolename=".
                   4197:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 4198:     return reply($command,$env{'user.home'});
1.12      www      4199:   } else {
                   4200:     return 'refused';
                   4201:   }
1.105     harris41 4202: }
                   4203: 
                   4204: # ---------------- Make a metadata query against the network of library servers
                   4205: 
                   4206: sub metadata_query {
1.244     matthew  4207:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 4208:     my %rhash;
1.845     albertel 4209:     my %libserv = &all_library();
1.244     matthew  4210:     my @server_list = (defined($server_array) ? @$server_array
                   4211:                                               : keys(%libserv) );
                   4212:     for my $server (@server_list) {
1.118     harris41 4213: 	unless ($custom or $customshow) {
                   4214: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   4215: 	    $rhash{$server}=$reply;
                   4216: 	}
                   4217: 	else {
                   4218: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   4219: 			     &escape($custom).':'.&escape($customshow),
                   4220: 			     $server);
                   4221: 	    $rhash{$server}=$reply;
                   4222: 	}
1.112     harris41 4223:     }
1.118     harris41 4224:     return \%rhash;
1.240     www      4225: }
                   4226: 
                   4227: # ----------------------------------------- Send log queries and wait for reply
                   4228: 
                   4229: sub log_query {
                   4230:     my ($uname,$udom,$query,%filters)=@_;
                   4231:     my $uhome=&homeserver($uname,$udom);
                   4232:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 4233:     my $uhost=&hostname($uhome);
1.800     albertel 4234:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      4235:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   4236:                        $uhome);
1.479     albertel 4237:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      4238:     return get_query_reply($queryid);
                   4239: }
                   4240: 
1.818     raeburn  4241: # -------------------------- Update MySQL table for portfolio file
                   4242: 
                   4243: sub update_portfolio_table {
1.821     raeburn  4244:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.818     raeburn  4245:     my $homeserver = &homeserver($uname,$udom);
                   4246:     my $queryid=
1.821     raeburn  4247:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   4248:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  4249:     my $reply = &get_query_reply($queryid);
                   4250:     return $reply;
                   4251: }
                   4252: 
1.508     raeburn  4253: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  4254: 
                   4255: sub fetch_enrollment_query {
1.511     raeburn  4256:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  4257:     my $homeserver;
1.547     raeburn  4258:     my $maxtries = 1;
1.508     raeburn  4259:     if ($context eq 'automated') {
                   4260:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  4261:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  4262:     } else {
                   4263:         $homeserver = &homeserver($cnum,$dom);
                   4264:     }
1.838     albertel 4265:     my $host=&hostname($homeserver);
1.506     raeburn  4266:     my $cmd = '';
1.800     albertel 4267:     foreach my $affiliate (keys %{$affiliatesref}) {
                   4268:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  4269:     }
                   4270:     $cmd =~ s/%%$//;
                   4271:     $cmd = &escape($cmd);
                   4272:     my $query = 'fetchenrollment';
1.620     albertel 4273:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  4274:     unless ($queryid=~/^\Q$host\E\_/) { 
                   4275:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   4276:         return 'error: '.$queryid;
                   4277:     }
1.506     raeburn  4278:     my $reply = &get_query_reply($queryid);
1.547     raeburn  4279:     my $tries = 1;
                   4280:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4281:         $reply = &get_query_reply($queryid);
                   4282:         $tries ++;
                   4283:     }
1.526     raeburn  4284:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 4285:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  4286:     } else {
1.515     raeburn  4287:         my @responses = split/:/,$reply;
                   4288:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 4289:             foreach my $line (@responses) {
                   4290:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  4291:                 $$replyref{$key} = $value;
                   4292:             }
                   4293:         } else {
1.506     raeburn  4294:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 4295:             foreach my $line (@responses) {
                   4296:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  4297:                 $$replyref{$key} = $value;
                   4298:                 if ($value > 0) {
1.800     albertel 4299:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   4300:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  4301:                         my $destname = $pathname.'/'.$filename;
                   4302:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  4303:                         if ($xml_classlist =~ /^error/) {
                   4304:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   4305:                         } else {
1.506     raeburn  4306:                             if ( open(FILE,">$destname") ) {
                   4307:                                 print FILE &unescape($xml_classlist);
                   4308:                                 close(FILE);
1.526     raeburn  4309:                             } else {
                   4310:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  4311:                             }
                   4312:                         }
                   4313:                     }
                   4314:                 }
                   4315:             }
                   4316:         }
                   4317:         return 'ok';
                   4318:     }
                   4319:     return 'error';
                   4320: }
                   4321: 
1.242     www      4322: sub get_query_reply {
                   4323:     my $queryid=shift;
1.240     www      4324:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   4325:     my $reply='';
                   4326:     for (1..100) {
                   4327: 	sleep 2;
                   4328:         if (-e $replyfile.'.end') {
1.448     albertel 4329: 	    if (open(my $fh,$replyfile)) {
1.240     www      4330:                $reply.=<$fh>;
1.448     albertel 4331:                close($fh);
1.240     www      4332: 	   } else { return 'error: reply_file_error'; }
1.242     www      4333:            return &unescape($reply);
                   4334: 	}
1.240     www      4335:     }
1.242     www      4336:     return 'timeout:'.$queryid;
1.240     www      4337: }
                   4338: 
                   4339: sub courselog_query {
1.241     www      4340: #
                   4341: # possible filters:
                   4342: # url: url or symb
                   4343: # username
                   4344: # domain
                   4345: # action: view, submit, grade
                   4346: # start: timestamp
                   4347: # end: timestamp
                   4348: #
1.240     www      4349:     my (%filters)=@_;
1.620     albertel 4350:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      4351:     if ($filters{'url'}) {
                   4352: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   4353:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   4354:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   4355:     }
1.620     albertel 4356:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4357:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      4358:     return &log_query($cname,$cdom,'courselog',%filters);
                   4359: }
                   4360: 
                   4361: sub userlog_query {
1.858     raeburn  4362: #
                   4363: # possible filters:
                   4364: # action: log check role
                   4365: # start: timestamp
                   4366: # end: timestamp
                   4367: #
1.240     www      4368:     my ($uname,$udom,%filters)=@_;
                   4369:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      4370: }
                   4371: 
1.506     raeburn  4372: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   4373: 
                   4374: sub auto_run {
1.508     raeburn  4375:     my ($cnum,$cdom) = @_;
                   4376:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4377:     my $response = &reply('autorun:'.$cdom,$homeserver);
1.506     raeburn  4378:     return $response;
                   4379: }
1.776     albertel 4380: 
1.506     raeburn  4381: sub auto_get_sections {
1.508     raeburn  4382:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   4383:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  4384:     my @secs = ();
1.511     raeburn  4385:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  4386:     unless ($response eq 'refused') {
                   4387:         @secs = split/:/,$response;
                   4388:     }
                   4389:     return @secs;
                   4390: }
1.776     albertel 4391: 
1.506     raeburn  4392: sub auto_new_course {
1.508     raeburn  4393:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   4394:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  4395:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  4396:     return $response;
                   4397: }
1.776     albertel 4398: 
1.506     raeburn  4399: sub auto_validate_courseID {
1.508     raeburn  4400:     my ($cnum,$cdom,$inst_course_id) = @_;
                   4401:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4402:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  4403:     return $response;
                   4404: }
1.776     albertel 4405: 
1.506     raeburn  4406: sub auto_create_password {
1.508     raeburn  4407:     my ($cnum,$cdom,$authparam) = @_;
                   4408:     my $homeserver = &homeserver($cnum,$cdom); 
1.506     raeburn  4409:     my $create_passwd = 0;
                   4410:     my $authchk = '';
1.511     raeburn  4411:     my $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
1.506     raeburn  4412:     if ($response eq 'refused') {
                   4413:         $authchk = 'refused';
                   4414:     } else {
                   4415:         ($authparam,$create_passwd,$authchk) = split/:/,$response;
                   4416:     }
                   4417:     return ($authparam,$create_passwd,$authchk);
                   4418: }
                   4419: 
1.706     raeburn  4420: sub auto_photo_permission {
                   4421:     my ($cnum,$cdom,$students) = @_;
                   4422:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 4423:     my ($outcome,$perm_reqd,$conditions) = 
                   4424: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 4425:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4426: 	return (undef,undef);
                   4427:     }
1.706     raeburn  4428:     return ($outcome,$perm_reqd,$conditions);
                   4429: }
                   4430: 
                   4431: sub auto_checkphotos {
                   4432:     my ($uname,$udom,$pid) = @_;
                   4433:     my $homeserver = &homeserver($uname,$udom);
                   4434:     my ($result,$resulttype);
                   4435:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 4436: 				   &escape($uname).':'.&escape($pid),
                   4437: 				   $homeserver));
1.709     albertel 4438:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4439: 	return (undef,undef);
                   4440:     }
1.706     raeburn  4441:     if ($outcome) {
                   4442:         ($result,$resulttype) = split(/:/,$outcome);
                   4443:     } 
                   4444:     return ($result,$resulttype);
                   4445: }
                   4446: 
                   4447: sub auto_photochoice {
                   4448:     my ($cnum,$cdom) = @_;
                   4449:     my $homeserver = &homeserver($cnum,$cdom);
                   4450:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 4451: 						       &escape($cdom),
                   4452: 						       $homeserver)));
1.709     albertel 4453:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4454: 	return (undef,undef);
                   4455:     }
1.706     raeburn  4456:     return ($update,$comment);
                   4457: }
                   4458: 
                   4459: sub auto_photoupdate {
                   4460:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   4461:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 4462:     my $host=&hostname($homeserver);
1.706     raeburn  4463:     my $cmd = '';
                   4464:     my $maxtries = 1;
1.800     albertel 4465:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   4466:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  4467:     }
                   4468:     $cmd =~ s/%%$//;
                   4469:     $cmd = &escape($cmd);
                   4470:     my $query = 'institutionalphotos';
                   4471:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   4472:     unless ($queryid=~/^\Q$host\E\_/) {
                   4473:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   4474:         return 'error: '.$queryid;
                   4475:     }
                   4476:     my $reply = &get_query_reply($queryid);
                   4477:     my $tries = 1;
                   4478:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4479:         $reply = &get_query_reply($queryid);
                   4480:         $tries ++;
                   4481:     }
                   4482:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   4483:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   4484:     } else {
                   4485:         my @responses = split(/:/,$reply);
                   4486:         my $outcome = shift(@responses); 
                   4487:         foreach my $item (@responses) {
                   4488:             my ($key,$value) = split(/=/,$item);
                   4489:             $$photo{$key} = $value;
                   4490:         }
                   4491:         return $outcome;
                   4492:     }
                   4493:     return 'error';
                   4494: }
                   4495: 
1.521     raeburn  4496: sub auto_instcode_format {
1.793     albertel 4497:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   4498: 	$cat_order) = @_;
1.521     raeburn  4499:     my $courses = '';
1.772     raeburn  4500:     my @homeservers;
1.521     raeburn  4501:     if ($caller eq 'global') {
1.841     albertel 4502: 	my %servers = &get_servers($codedom,'library');
                   4503: 	foreach my $tryserver (keys(%servers)) {
                   4504: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   4505: 		push(@homeservers,$tryserver);
                   4506: 	    }
1.584     raeburn  4507:         }
1.521     raeburn  4508:     } else {
1.772     raeburn  4509:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  4510:     }
1.793     albertel 4511:     foreach my $code (keys(%{$instcodes})) {
                   4512:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  4513:     }
                   4514:     chop($courses);
1.772     raeburn  4515:     my $ok_response = 0;
                   4516:     my $response;
                   4517:     while (@homeservers > 0 && $ok_response == 0) {
                   4518:         my $server = shift(@homeservers); 
                   4519:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   4520:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   4521:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.793     albertel 4522: 		split/:/,$response;
1.772     raeburn  4523:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   4524:             push(@{$codetitles},&str2array($codetitles_str));
                   4525:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   4526:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   4527:             $ok_response = 1;
                   4528:         }
                   4529:     }
                   4530:     if ($ok_response) {
1.521     raeburn  4531:         return 'ok';
1.772     raeburn  4532:     } else {
                   4533:         return $response;
1.521     raeburn  4534:     }
                   4535: }
                   4536: 
1.792     raeburn  4537: sub auto_instcode_defaults {
                   4538:     my ($domain,$returnhash,$code_order) = @_;
                   4539:     my @homeservers;
1.841     albertel 4540: 
                   4541:     my %servers = &get_servers($domain,'library');
                   4542:     foreach my $tryserver (keys(%servers)) {
                   4543: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   4544: 	    push(@homeservers,$tryserver);
                   4545: 	}
1.792     raeburn  4546:     }
1.841     albertel 4547: 
1.792     raeburn  4548:     my $response;
1.841     albertel 4549:     foreach my $server (@homeservers) {
1.792     raeburn  4550:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 4551:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   4552: 	
                   4553: 	foreach my $pair (split(/\&/,$response)) {
                   4554: 	    my ($name,$value)=split(/\=/,$pair);
                   4555: 	    if ($name eq 'code_order') {
                   4556: 		@{$code_order} = split(/\&/,&unescape($value));
                   4557: 	    } else {
                   4558: 		$returnhash->{&unescape($name)}=&unescape($value);
                   4559: 	    }
                   4560: 	}
                   4561: 	return 'ok';
1.792     raeburn  4562:     }
1.841     albertel 4563: 
                   4564:     return $response;
1.792     raeburn  4565: } 
                   4566: 
1.777     albertel 4567: sub auto_validate_class_sec {
1.773     raeburn  4568:     my ($cdom,$cnum,$owner,$inst_class) = @_;
                   4569:     my $homeserver = &homeserver($cnum,$cdom);
                   4570:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.774     banghart 4571:                         &escape($owner).':'.$cdom,$homeserver);
1.773     raeburn  4572:     return $response;
                   4573: }
                   4574: 
1.679     raeburn  4575: # ------------------------------------------------------- Course Group routines
                   4576: 
                   4577: sub get_coursegroups {
1.809     raeburn  4578:     my ($cdom,$cnum,$group,$namespace) = @_;
                   4579:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  4580: }
                   4581: 
1.679     raeburn  4582: sub modify_coursegroup {
                   4583:     my ($cdom,$cnum,$groupsettings) = @_;
                   4584:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   4585: }
                   4586: 
1.809     raeburn  4587: sub toggle_coursegroup_status {
                   4588:     my ($cdom,$cnum,$group,$action) = @_;
                   4589:     my ($from_namespace,$to_namespace);
                   4590:     if ($action eq 'delete') {
                   4591:         $from_namespace = 'coursegroups';
                   4592:         $to_namespace = 'deleted_groups';
                   4593:     } else {
                   4594:         $from_namespace = 'deleted_groups';
                   4595:         $to_namespace = 'coursegroups';
                   4596:     }
                   4597:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  4598:     if (my $tmp = &error(%curr_group)) {
                   4599:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   4600:         return ('read error',$tmp);
                   4601:     } else {
                   4602:         my %savedsettings = %curr_group; 
1.809     raeburn  4603:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  4604:         my $deloutcome;
                   4605:         if ($result eq 'ok') {
1.809     raeburn  4606:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  4607:         } else {
                   4608:             return ('write error',$result);
                   4609:         }
                   4610:         if ($deloutcome eq 'ok') {
                   4611:             return 'ok';
                   4612:         } else {
                   4613:             return ('delete error',$deloutcome);
                   4614:         }
                   4615:     }
                   4616: }
                   4617: 
1.679     raeburn  4618: sub modify_group_roles {
                   4619:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
                   4620:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   4621:     my $role = 'gr/'.&escape($userprivs);
                   4622:     my ($uname,$udom) = split(/:/,$user);
                   4623:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
1.684     raeburn  4624:     if ($result eq 'ok') {
                   4625:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   4626:     }
1.679     raeburn  4627:     return $result;
                   4628: }
                   4629: 
                   4630: sub modify_coursegroup_membership {
                   4631:     my ($cdom,$cnum,$membership) = @_;
                   4632:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   4633:     return $result;
                   4634: }
                   4635: 
1.682     raeburn  4636: sub get_active_groups {
                   4637:     my ($udom,$uname,$cdom,$cnum) = @_;
                   4638:     my $now = time;
                   4639:     my %groups = ();
                   4640:     foreach my $key (keys(%env)) {
1.811     albertel 4641:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  4642:             my ($start,$end) = split(/\./,$env{$key});
                   4643:             if (($end!=0) && ($end<$now)) { next; }
                   4644:             if (($start!=0) && ($start>$now)) { next; }
                   4645:             if ($1 eq $cdom && $2 eq $cnum) {
                   4646:                 $groups{$3} = $env{$key} ;
                   4647:             }
                   4648:         }
                   4649:     }
                   4650:     return %groups;
                   4651: }
                   4652: 
1.683     raeburn  4653: sub get_group_membership {
                   4654:     my ($cdom,$cnum,$group) = @_;
                   4655:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   4656: }
                   4657: 
                   4658: sub get_users_groups {
                   4659:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  4660:     my @usersgroups;
1.683     raeburn  4661:     my $cachetime=1800;
                   4662: 
                   4663:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  4664:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   4665:     if (defined($cached)) {
1.734     albertel 4666:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  4667:     } else {  
                   4668:         $grouplist = '';
1.816     raeburn  4669:         my $courseurl = &courseid_to_courseurl($courseid);
                   4670:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  4671:         my $access_end = $env{'course.'.$courseid.
                   4672:                               '.default_enrollment_end_date'};
                   4673:         my $now = time;
                   4674:         foreach my $key (keys(%roleshash)) {
                   4675:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   4676:                 my $group = $1;
                   4677:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   4678:                     my $start = $2;
                   4679:                     my $end = $1;
                   4680:                     if ($start == -1) { next; } # deleted from group
                   4681:                     if (($start!=0) && ($start>$now)) { next; }
                   4682:                     if (($end!=0) && ($end<$now)) {
                   4683:                         if ($access_end && $access_end < $now) {
                   4684:                             if ($access_end - $end < 86400) {
                   4685:                                 push(@usersgroups,$group);
1.733     raeburn  4686:                             }
                   4687:                         }
1.817     raeburn  4688:                         next;
1.733     raeburn  4689:                     }
1.817     raeburn  4690:                     push(@usersgroups,$group);
1.683     raeburn  4691:                 }
                   4692:             }
                   4693:         }
1.817     raeburn  4694:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   4695:         $grouplist = join(':',@usersgroups);
                   4696:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  4697:     }
1.733     raeburn  4698:     return @usersgroups;
1.683     raeburn  4699: }
                   4700: 
                   4701: sub devalidate_getgroups_cache {
                   4702:     my ($udom,$uname,$cdom,$cnum)=@_;
                   4703:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 4704: 
1.683     raeburn  4705:     my $hashid="$udom:$uname:$courseid";
                   4706:     &devalidate_cache_new('getgroups',$hashid);
                   4707: }
                   4708: 
1.12      www      4709: # ------------------------------------------------------------------ Plain Text
                   4710: 
                   4711: sub plaintext {
1.742     raeburn  4712:     my ($short,$type,$cid) = @_;
1.758     albertel 4713:     if ($short =~ /^cr/) {
                   4714: 	return (split('/',$short))[-1];
                   4715:     }
1.742     raeburn  4716:     if (!defined($cid)) {
                   4717:         $cid = $env{'request.course.id'};
                   4718:     }
                   4719:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
                   4720:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
                   4721:                                           '.plaintext'});
                   4722:     }
                   4723:     my %rolenames = (
                   4724:                       Course => 'std',
                   4725:                       Group => 'alt1',
                   4726:                     );
                   4727:     if (defined($type) && 
                   4728:          defined($rolenames{$type}) && 
                   4729:          defined($prp{$short}{$rolenames{$type}})) {
                   4730:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   4731:     } else {
                   4732:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   4733:     }
1.12      www      4734: }
                   4735: 
                   4736: # ----------------------------------------------------------------- Assign Role
                   4737: 
                   4738: sub assignrole {
1.357     www      4739:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
1.21      www      4740:     my $mrole;
                   4741:     if ($role =~ /^cr\//) {
1.393     www      4742:         my $cwosec=$url;
1.811     albertel 4743:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      4744: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      4745:            &logthis('Refused custom assignrole: '.
                   4746:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4747: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4748:            return 'refused'; 
                   4749:         }
1.21      www      4750:         $mrole='cr';
1.678     raeburn  4751:     } elsif ($role =~ /^gr\//) {
                   4752:         my $cwogrp=$url;
1.811     albertel 4753:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  4754:         unless (&allowed('mdg',$cwogrp)) {
                   4755:             &logthis('Refused group assignrole: '.
                   4756:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   4757:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   4758:             return 'refused';
                   4759:         }
                   4760:         $mrole='gr';
1.21      www      4761:     } else {
1.82      www      4762:         my $cwosec=$url;
1.811     albertel 4763:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.373     www      4764:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
1.104     www      4765:            &logthis('Refused assignrole: '.
                   4766:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4767: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4768:            return 'refused'; 
                   4769:         }
1.21      www      4770:         $mrole=$role;
                   4771:     }
1.620     albertel 4772:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4773:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      4774:     if ($end) { $command.='_'.$end; }
1.21      www      4775:     if ($start) {
                   4776: 	if ($end) { 
1.81      www      4777:            $command.='_'.$start; 
1.21      www      4778:         } else {
1.81      www      4779:            $command.='_0_'.$start;
1.21      www      4780:         }
                   4781:     }
1.739     raeburn  4782:     my $origstart = $start;
                   4783:     my $origend = $end;
1.357     www      4784: # actually delete
                   4785:     if ($deleteflag) {
1.373     www      4786: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      4787: # modify command to delete the role
1.620     albertel 4788:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      4789:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 4790: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      4791: # set start and finish to negative values for userrolelog
                   4792:            $start=-1;
                   4793:            $end=-1;
                   4794:         }
                   4795:     }
                   4796: # send command
1.349     www      4797:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      4798: # log new user role if status is ok
1.349     www      4799:     if ($answer eq 'ok') {
1.663     raeburn  4800: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  4801: # for course roles, perform group memberships changes triggered by role change.
                   4802:         unless ($role =~ /^gr/) {
                   4803:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   4804:                                              $origstart);
                   4805:         }
1.349     www      4806:     }
                   4807:     return $answer;
1.169     harris41 4808: }
                   4809: 
                   4810: # -------------------------------------------------- Modify user authentication
1.197     www      4811: # Overrides without validation
                   4812: 
1.169     harris41 4813: sub modifyuserauth {
                   4814:     my ($udom,$uname,$umode,$upass)=@_;
                   4815:     my $uhome=&homeserver($uname,$udom);
1.197     www      4816:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   4817:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 4818:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4819:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 4820:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   4821: 		     &escape($upass),$uhome);
1.620     albertel 4822:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      4823:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   4824:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   4825:     &log($udom,,$uname,$uhome,
1.620     albertel 4826:         'Authentication changed by '.$env{'user.domain'}.', '.
                   4827:                                      $env{'user.name'}.', '.$umode.
1.197     www      4828:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 4829:     unless ($reply eq 'ok') {
1.197     www      4830:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 4831: 	return 'error: '.$reply;
                   4832:     }   
1.170     harris41 4833:     return 'ok';
1.80      www      4834: }
                   4835: 
1.81      www      4836: # --------------------------------------------------------------- Modify a user
1.80      www      4837: 
1.81      www      4838: sub modifyuser {
1.206     matthew  4839:     my ($udom,    $uname, $uid,
                   4840:         $umode,   $upass, $first,
                   4841:         $middle,  $last,  $gene,
1.387     www      4842:         $forceid, $desiredhome, $email)=@_;
1.807     albertel 4843:     $udom= &LONCAPA::clean_domain($udom);
                   4844:     $uname=&LONCAPA::clean_username($uname);
1.81      www      4845:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4846:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  4847: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   4848:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   4849:                                      ' desiredhome not specified'). 
1.620     albertel 4850:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4851:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 4852:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      4853: # ----------------------------------------------------------------- Create User
1.406     albertel 4854:     if (($uhome eq 'no_host') && 
                   4855: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      4856:         my $unhome='';
1.844     albertel 4857:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  4858:             $unhome = $desiredhome;
1.620     albertel 4859: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   4860: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  4861:         } else { # load balancing routine for determining $unhome
1.81      www      4862:             my $loadm=10000000;
1.841     albertel 4863: 	    my %servers = &get_servers($udom,'library');
                   4864: 	    foreach my $tryserver (keys(%servers)) {
                   4865: 		my $answer=reply('load',$tryserver);
                   4866: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   4867: 		    $loadm=$answer;
                   4868: 		    $unhome=$tryserver;
                   4869: 		}
1.80      www      4870: 	    }
                   4871:         }
                   4872:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  4873: 	    return 'error: unable to find a home server for '.$uname.
                   4874:                    ' in domain '.$udom;
1.80      www      4875:         }
                   4876:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   4877:                          &escape($upass),$unhome);
                   4878: 	unless ($reply eq 'ok') {
                   4879:             return 'error: '.$reply;
                   4880:         }   
1.230     stredwic 4881:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      4882:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  4883: 	    return 'error: unable verify users home machine.';
1.80      www      4884:         }
1.209     matthew  4885:     }   # End of creation of new user
1.80      www      4886: # ---------------------------------------------------------------------- Add ID
                   4887:     if ($uid) {
                   4888:        $uid=~tr/A-Z/a-z/;
                   4889:        my %uidhash=&idrget($udom,$uname);
1.196     www      4890:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   4891:          && (!$forceid)) {
1.80      www      4892: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  4893: 	      return 'error: user id "'.$uid.'" does not match '.
                   4894:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      4895:           }
                   4896:        } else {
                   4897: 	  &idput($udom,($uname => $uid));
                   4898:        }
                   4899:     }
                   4900: # -------------------------------------------------------------- Add names, etc
1.313     matthew  4901:     my @tmp=&get('environment',
1.134     albertel 4902: 		   ['firstname','middlename','lastname','generation'],
                   4903: 		   $udom,$uname);
1.313     matthew  4904:     my %names;
                   4905:     if ($tmp[0] =~ m/^error:.*/) { 
                   4906:         %names=(); 
                   4907:     } else {
                   4908:         %names = @tmp;
                   4909:     }
1.388     www      4910: #
                   4911: # Make sure to not trash student environment if instructor does not bother
                   4912: # to supply name and email information
                   4913: #
                   4914:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  4915:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      4916:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  4917:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      4918:     if ($email) {
                   4919:        $email=~s/[^\w\@\.\-\,]//gs;
                   4920:        if ($email=~/\@/) { $names{'notification'} = $email;
                   4921: 			   $names{'critnotification'} = $email;
                   4922: 			   $names{'permanentemail'} = $email; }
                   4923:     }
1.134     albertel 4924:     my $reply = &put('environment', \%names, $udom,$uname);
                   4925:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.680     www      4926:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.81      www      4927:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4928:              $umode.', '.$first.', '.$middle.', '.
                   4929: 	     $last.', '.$gene.' by '.
1.620     albertel 4930:              $env{'user.name'}.' at '.$env{'user.domain'});
1.134     albertel 4931:     return 'ok';
1.80      www      4932: }
                   4933: 
1.81      www      4934: # -------------------------------------------------------------- Modify student
1.80      www      4935: 
1.81      www      4936: sub modifystudent {
                   4937:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.515     raeburn  4938:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
1.455     albertel 4939:     if (!$cid) {
1.620     albertel 4940: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 4941: 	    return 'not_in_class';
                   4942: 	}
1.80      www      4943:     }
                   4944: # --------------------------------------------------------------- Make the user
1.81      www      4945:     my $reply=&modifyuser
1.209     matthew  4946: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      4947:          $desiredhome,$email);
1.80      www      4948:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  4949:     # This will cause &modify_student_enrollment to get the uid from the
                   4950:     # students environment
                   4951:     $uid = undef if (!$forceid);
1.455     albertel 4952:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.515     raeburn  4953: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
1.297     matthew  4954:     return $reply;
                   4955: }
                   4956: 
                   4957: sub modify_student_enrollment {
1.515     raeburn  4958:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
1.455     albertel 4959:     my ($cdom,$cnum,$chome);
                   4960:     if (!$cid) {
1.620     albertel 4961: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 4962: 	    return 'not_in_class';
                   4963: 	}
1.620     albertel 4964: 	$cdom=$env{'course.'.$cid.'.domain'};
                   4965: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 4966:     } else {
                   4967: 	($cdom,$cnum)=split(/_/,$cid);
                   4968:     }
1.620     albertel 4969:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 4970:     if (!$chome) {
1.457     raeburn  4971: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  4972:     }
1.455     albertel 4973:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  4974:     # Make sure the user exists
1.81      www      4975:     my $uhome=&homeserver($uname,$udom);
                   4976:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   4977: 	return 'error: no such user';
                   4978:     }
1.297     matthew  4979:     # Get student data if we were not given enough information
                   4980:     if (!defined($first)  || $first  eq '' || 
                   4981:         !defined($last)   || $last   eq '' || 
                   4982:         !defined($uid)    || $uid    eq '' || 
                   4983:         !defined($middle) || $middle eq '' || 
                   4984:         !defined($gene)   || $gene   eq '') {
1.294     matthew  4985:         # They did not supply us with enough data to enroll the student, so
                   4986:         # we need to pick up more information.
1.297     matthew  4987:         my %tmp = &get('environment',
1.294     matthew  4988:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  4989:                        ,$udom,$uname);
                   4990: 
1.800     albertel 4991:         #foreach my $key (keys(%tmp)) {
                   4992:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 4993:         #}
1.294     matthew  4994:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   4995:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   4996:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  4997:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  4998:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   4999:     }
1.556     albertel 5000:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 5001:     my $reply=cput('classlist',
                   5002: 		   {"$uname:$udom" => 
1.515     raeburn  5003: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 5004: 		   $cdom,$cnum);
1.81      www      5005:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   5006: 	return 'error: '.$reply;
1.652     albertel 5007:     } else {
                   5008: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      5009:     }
1.297     matthew  5010:     # Add student role to user
1.83      www      5011:     my $uurl='/'.$cid;
1.81      www      5012:     $uurl=~s/\_/\//g;
                   5013:     if ($usec) {
                   5014: 	$uurl.='/'.$usec;
                   5015:     }
                   5016:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21      www      5017: }
                   5018: 
1.556     albertel 5019: sub format_name {
                   5020:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   5021:     my $name;
                   5022:     if ($first ne 'lastname') {
                   5023: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   5024:     } else {
                   5025: 	if ($lastname=~/\S/) {
                   5026: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   5027: 	    $name=~s/\s+,/,/;
                   5028: 	} else {
                   5029: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   5030: 	}
                   5031:     }
                   5032:     $name=~s/^\s+//;
                   5033:     $name=~s/\s+$//;
                   5034:     $name=~s/\s+/ /g;
                   5035:     return $name;
                   5036: }
                   5037: 
1.84      www      5038: # ------------------------------------------------- Write to course preferences
                   5039: 
                   5040: sub writecoursepref {
                   5041:     my ($courseid,%prefs)=@_;
                   5042:     $courseid=~s/^\///;
                   5043:     $courseid=~s/\_/\//g;
                   5044:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   5045:     my $chome=homeserver($cnum,$cdomain);
                   5046:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   5047: 	return 'error: no such course';
                   5048:     }
                   5049:     my $cstring='';
1.800     albertel 5050:     foreach my $pref (keys(%prefs)) {
                   5051: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 5052:     }
1.84      www      5053:     $cstring=~s/\&$//;
                   5054:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   5055: }
                   5056: 
                   5057: # ---------------------------------------------------------- Make/modify course
                   5058: 
                   5059: sub createcourse {
1.741     raeburn  5060:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
                   5061:         $course_owner,$crstype)=@_;
1.84      www      5062:     $url=&declutter($url);
                   5063:     my $cid='';
1.264     matthew  5064:     unless (&allowed('ccc',$udom)) {
1.84      www      5065:         return 'refused';
                   5066:     }
                   5067: # ------------------------------------------------------------------- Create ID
1.674     www      5068:    my $uname=int(1+rand(9)).
                   5069:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   5070:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      5071:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   5072: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 5073:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      5074:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5075:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   5076:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 5077:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      5078:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5079:            return 'error: unable to generate unique course-ID';
                   5080:        } 
                   5081:    }
1.264     matthew  5082: # ------------------------------------------------ Check supplied server name
1.620     albertel 5083:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.845     albertel 5084:     if (! &is_library($course_server)) {
1.264     matthew  5085:         return 'error:bad server name '.$course_server;
                   5086:     }
1.84      www      5087: # ------------------------------------------------------------- Make the course
                   5088:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  5089:                       $course_server);
1.84      www      5090:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 5091:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      5092:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5093: 	return 'error: no such course';
                   5094:     }
1.271     www      5095: # ----------------------------------------------------------------- Course made
1.516     raeburn  5096: # log existence
                   5097:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
1.741     raeburn  5098:                  ':'.&escape($inst_code).':'.&escape($course_owner).':'.
                   5099:                   &escape($crstype),$uhome);
1.358     www      5100:     &flushcourselogs();
                   5101: # set toplevel url
1.271     www      5102:     my $topurl=$url;
                   5103:     unless ($nonstandard) {
                   5104: # ------------------------------------------ For standard courses, make top url
                   5105:         my $mapurl=&clutter($url);
1.278     www      5106:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 5107:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      5108: <map>
                   5109: <resource id="1" type="start"></resource>
                   5110: <resource id="2" src="$mapurl"></resource>
                   5111: <resource id="3" type="finish"></resource>
                   5112: <link index="1" from="1" to="2"></link>
                   5113: <link index="2" from="2" to="3"></link>
                   5114: </map>
                   5115: ENDINITMAP
                   5116:         $topurl=&declutter(
1.638     albertel 5117:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      5118:                           );
                   5119:     }
                   5120: # ----------------------------------------------------------- Write preferences
1.84      www      5121:     &writecoursepref($udom.'_'.$uname,
                   5122:                      ('description' => $description,
1.271     www      5123:                       'url'         => $topurl));
1.84      www      5124:     return '/'.$udom.'/'.$uname;
                   5125: }
                   5126: 
1.813     albertel 5127: sub is_course {
                   5128:     my ($cdom,$cnum) = @_;
                   5129:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
                   5130: 				undef,'.');
                   5131:     if (exists($courses{$cdom.'_'.$cnum})) {
                   5132:         return 1;
                   5133:     }
                   5134:     return 0;
                   5135: }
                   5136: 
1.21      www      5137: # ---------------------------------------------------------- Assign Custom Role
                   5138: 
                   5139: sub assigncustomrole {
1.357     www      5140:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21      www      5141:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357     www      5142:                        $end,$start,$deleteflag);
1.21      www      5143: }
                   5144: 
                   5145: # ----------------------------------------------------------------- Revoke Role
                   5146: 
                   5147: sub revokerole {
1.357     www      5148:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21      www      5149:     my $now=time;
1.357     www      5150:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21      www      5151: }
                   5152: 
                   5153: # ---------------------------------------------------------- Revoke Custom Role
                   5154: 
                   5155: sub revokecustomrole {
1.357     www      5156:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21      www      5157:     my $now=time;
1.357     www      5158:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
                   5159:            $deleteflag);
1.17      www      5160: }
                   5161: 
1.533     banghart 5162: # ------------------------------------------------------------ Disk usage
1.535     albertel 5163: sub diskusage {
1.533     banghart 5164:     my ($udom,$uname,$directoryRoot)=@_;
                   5165:     $directoryRoot =~ s/\/$//;
1.535     albertel 5166:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
1.514     albertel 5167:     return $listing;
1.512     banghart 5168: }
                   5169: 
1.566     banghart 5170: sub is_locked {
                   5171:     my ($file_name, $domain, $user) = @_;
                   5172:     my @check;
                   5173:     my $is_locked;
                   5174:     push @check, $file_name;
1.613     albertel 5175:     my %locked = &get('file_permissions',\@check,
1.620     albertel 5176: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 5177:     my ($tmp)=keys(%locked);
                   5178:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  5179:     
1.566     banghart 5180:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  5181:         $is_locked = 'false';
                   5182:         foreach my $entry (@{$locked{$file_name}}) {
                   5183:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  5184:                $is_locked = 'true';
                   5185:                last;
1.745     raeburn  5186:            }
                   5187:        }
1.566     banghart 5188:     } else {
                   5189:         $is_locked = 'false';
                   5190:     }
                   5191: }
                   5192: 
1.759     albertel 5193: sub declutter_portfile {
                   5194:     my ($file) = @_;
1.833     albertel 5195:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 5196:     return $file;
                   5197: }
                   5198: 
1.559     banghart 5199: # ------------------------------------------------------------- Mark as Read Only
                   5200: 
                   5201: sub mark_as_readonly {
                   5202:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 5203:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5204:     my ($tmp)=keys(%current_permissions);
                   5205:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 5206:     foreach my $file (@{$files}) {
1.759     albertel 5207: 	$file = &declutter_portfile($file);
1.561     banghart 5208:         push(@{$current_permissions{$file}},$what);
1.559     banghart 5209:     }
1.613     albertel 5210:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5211:     return;
                   5212: }
                   5213: 
1.572     banghart 5214: # ------------------------------------------------------------Save Selected Files
                   5215: 
                   5216: sub save_selected_files {
                   5217:     my ($user, $path, @files) = @_;
                   5218:     my $filename = $user."savedfiles";
1.573     banghart 5219:     my @other_files = &files_not_in_path($user, $path);
1.574     banghart 5220:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 5221:     foreach my $file (@files) {
1.620     albertel 5222:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 5223:     }
                   5224:     foreach my $file (@other_files) {
1.574     banghart 5225:         print (OUT $file."\n");
1.572     banghart 5226:     }
1.574     banghart 5227:     close (OUT);
1.572     banghart 5228:     return 'ok';
                   5229: }
                   5230: 
1.574     banghart 5231: sub clear_selected_files {
                   5232:     my ($user) = @_;
                   5233:     my $filename = $user."savedfiles";
                   5234:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5235:     print (OUT undef);
                   5236:     close (OUT);
                   5237:     return ("ok");    
                   5238: }
                   5239: 
1.572     banghart 5240: sub files_in_path {
                   5241:     my ($user, $path) = @_;
                   5242:     my $filename = $user."savedfiles";
                   5243:     my %return_files;
1.574     banghart 5244:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 5245:     while (my $line_in = <IN>) {
1.574     banghart 5246:         chomp ($line_in);
                   5247:         my @paths_and_file = split (m!/!, $line_in);
                   5248:         my $file_part = pop (@paths_and_file);
                   5249:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 5250:         $path_part.='/';
                   5251:         my $path_and_file = $path_part.$file_part;
                   5252:         if ($path_part eq $path) {
                   5253:             $return_files{$file_part}= 'selected';
                   5254:         }
                   5255:     }
1.574     banghart 5256:     close (IN);
                   5257:     return (\%return_files);
1.572     banghart 5258: }
                   5259: 
                   5260: # called in portfolio select mode, to show files selected NOT in current directory
                   5261: sub files_not_in_path {
                   5262:     my ($user, $path) = @_;
                   5263:     my $filename = $user."savedfiles";
                   5264:     my @return_files;
                   5265:     my $path_part;
1.800     albertel 5266:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5267:     while (my $line = <IN>) {
1.572     banghart 5268:         #ok, I know it's clunky, but I want it to work
1.800     albertel 5269:         my @paths_and_file = split(m|/|, $line);
                   5270:         my $file_part = pop(@paths_and_file);
                   5271:         chomp($file_part);
                   5272:         my $path_part = join('/', @paths_and_file);
1.572     banghart 5273:         $path_part .= '/';
                   5274:         my $path_and_file = $path_part.$file_part;
                   5275:         if ($path_part ne $path) {
1.800     albertel 5276:             push(@return_files, ($path_and_file));
1.572     banghart 5277:         }
                   5278:     }
1.800     albertel 5279:     close(OUT);
1.574     banghart 5280:     return (@return_files);
1.572     banghart 5281: }
                   5282: 
1.745     raeburn  5283: #----------------------------------------------Get portfolio file permissions
1.629     banghart 5284: 
1.745     raeburn  5285: sub get_portfile_permissions {
                   5286:     my ($domain,$user) = @_;
1.613     albertel 5287:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5288:     my ($tmp)=keys(%current_permissions);
                   5289:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5290:     return \%current_permissions;
                   5291: }
                   5292: 
                   5293: #---------------------------------------------Get portfolio file access controls
                   5294: 
1.749     raeburn  5295: sub get_access_controls {
1.745     raeburn  5296:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 5297:     my %access;
                   5298:     my $real_file = $file;
                   5299:     $file =~ s/\.meta$//;
1.745     raeburn  5300:     if (defined($file)) {
1.749     raeburn  5301:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   5302:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 5303:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  5304:             }
                   5305:         }
1.745     raeburn  5306:     } else {
1.749     raeburn  5307:         foreach my $key (keys(%{$current_permissions})) {
                   5308:             if ($key =~ /\0accesscontrol$/) {
                   5309:                 if (defined($group)) {
                   5310:                     if ($key !~ m-^\Q$group\E/-) {
                   5311:                         next;
                   5312:                     }
                   5313:                 }
                   5314:                 my ($fullpath) = split(/\0/,$key);
                   5315:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   5316:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   5317:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   5318:                     }
                   5319:                 }
                   5320:             }
                   5321:         }
                   5322:     }
                   5323:     return %access;
                   5324: }
                   5325: 
                   5326: sub modify_access_controls {
                   5327:     my ($file_name,$changes,$domain,$user)=@_;
                   5328:     my ($outcome,$deloutcome);
                   5329:     my %store_permissions;
                   5330:     my %new_values;
                   5331:     my %new_control;
                   5332:     my %translation;
                   5333:     my @deletions = ();
                   5334:     my $now = time;
                   5335:     if (exists($$changes{'activate'})) {
                   5336:         if (ref($$changes{'activate'}) eq 'HASH') {
                   5337:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   5338:             my $numnew = scalar(@newitems);
                   5339:             for (my $i=0; $i<$numnew; $i++) {
                   5340:                 my $newkey = $newitems[$i];
                   5341:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  5342:                 if ($newkey =~ /^\d+:/) { 
                   5343:                     $newkey =~ s/^(\d+)/$newid/;
                   5344:                     $translation{$1} = $newid;
                   5345:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   5346:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   5347:                     $translation{$1} = $newid;
                   5348:                 }
1.749     raeburn  5349:                 $new_values{$file_name."\0".$newkey} = 
                   5350:                                           $$changes{'activate'}{$newitems[$i]};
                   5351:                 $new_control{$newkey} = $now;
                   5352:             }
                   5353:         }
                   5354:     }
                   5355:     my %todelete;
                   5356:     my %changed_items;
                   5357:     foreach my $action ('delete','update') {
                   5358:         if (exists($$changes{$action})) {
                   5359:             if (ref($$changes{$action}) eq 'HASH') {
                   5360:                 foreach my $key (keys(%{$$changes{$action}})) {
                   5361:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   5362:                     if ($action eq 'delete') { 
                   5363:                         $todelete{$itemnum} = 1;
                   5364:                     } else {
                   5365:                         $changed_items{$itemnum} = $key;
                   5366:                     }
                   5367:                 }
1.745     raeburn  5368:             }
                   5369:         }
1.749     raeburn  5370:     }
                   5371:     # get lock on access controls for file.
                   5372:     my $lockhash = {
                   5373:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   5374:                                                        ':'.$env{'user.domain'},
                   5375:                    }; 
                   5376:     my $tries = 0;
                   5377:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5378:    
                   5379:     while (($gotlock ne 'ok') && $tries <3) {
                   5380:         $tries ++;
                   5381:         sleep 1;
                   5382:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5383:     }
                   5384:     if ($gotlock eq 'ok') {
                   5385:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   5386:         my ($tmp)=keys(%curr_permissions);
                   5387:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   5388:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   5389:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   5390:             if (ref($curr_controls) eq 'HASH') {
                   5391:                 foreach my $control_item (keys(%{$curr_controls})) {
                   5392:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   5393:                     if (defined($todelete{$itemnum})) {
                   5394:                         push(@deletions,$file_name."\0".$control_item);
                   5395:                     } else {
                   5396:                         if (defined($changed_items{$itemnum})) {
                   5397:                             $new_control{$changed_items{$itemnum}} = $now;
                   5398:                             push(@deletions,$file_name."\0".$control_item);
                   5399:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   5400:                         } else {
                   5401:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   5402:                         }
                   5403:                     }
1.745     raeburn  5404:                 }
                   5405:             }
                   5406:         }
1.749     raeburn  5407:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   5408:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   5409:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   5410:         #  remove lock
                   5411:         my @del_lock = ($file_name."\0".'locked_access_records');
                   5412:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  5413:         my ($file,$group);
                   5414:         if (&is_course($domain,$user)) {
                   5415:             ($group,$file) = split(/\//,$file_name,2);
                   5416:         } else {
                   5417:             $file = $file_name;
                   5418:         }
                   5419:         my $sqlresult =
                   5420:             &update_portfolio_table($user,$domain,$file,'portfolio_access',
                   5421:                                     $group);
1.749     raeburn  5422:     } else {
                   5423:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  5424:     }
1.749     raeburn  5425:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  5426: }
                   5427: 
1.827     raeburn  5428: sub make_public_indefinitely {
                   5429:     my ($requrl) = @_;
                   5430:     my $now = time;
                   5431:     my $action = 'activate';
                   5432:     my $aclnum = 0;
                   5433:     if (&is_portfolio_url($requrl)) {
                   5434:         my (undef,$udom,$unum,$file_name,$group) =
                   5435:             &parse_portfolio_url($requrl);
                   5436:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   5437:         my %access_controls = &get_access_controls($current_perms,
                   5438:                                                    $group,$file_name);
                   5439:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   5440:             my ($num,$scope,$end,$start) = 
                   5441:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   5442:             if ($scope eq 'public') {
                   5443:                 if ($start <= $now && $end == 0) {
                   5444:                     $action = 'none';
                   5445:                 } else {
                   5446:                     $action = 'update';
                   5447:                     $aclnum = $num;
                   5448:                 }
                   5449:                 last;
                   5450:             }
                   5451:         }
                   5452:         if ($action eq 'none') {
                   5453:              return 'ok';
                   5454:         } else {
                   5455:             my %changes;
                   5456:             my $newend = 0;
                   5457:             my $newstart = $now;
                   5458:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   5459:             $changes{$action}{$newkey} = {
                   5460:                 type => 'public',
                   5461:                 time => {
                   5462:                     start => $newstart,
                   5463:                     end   => $newend,
                   5464:                 },
                   5465:             };
                   5466:             my ($outcome,$deloutcome,$new_values,$translation) =
                   5467:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   5468:             return $outcome;
                   5469:         }
                   5470:     } else {
                   5471:         return 'invalid';
                   5472:     }
                   5473: }
                   5474: 
1.745     raeburn  5475: #------------------------------------------------------Get Marked as Read Only
                   5476: 
                   5477: sub get_marked_as_readonly {
                   5478:     my ($domain,$user,$what,$group) = @_;
                   5479:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 5480:     my @readonly_files;
1.629     banghart 5481:     my $cmp1=$what;
                   5482:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  5483:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5484:         if (defined($group)) {
                   5485:             if ($file_name !~ m-^\Q$group\E/-) {
                   5486:                 next;
                   5487:             }
                   5488:         }
1.561     banghart 5489:         if (ref($value) eq "ARRAY"){
                   5490:             foreach my $stored_what (@{$value}) {
1.629     banghart 5491:                 my $cmp2=$stored_what;
1.759     albertel 5492:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  5493:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  5494:                 }
1.629     banghart 5495:                 if ($cmp1 eq $cmp2) {
1.561     banghart 5496:                     push(@readonly_files, $file_name);
1.745     raeburn  5497:                     last;
1.563     banghart 5498:                 } elsif (!defined($what)) {
                   5499:                     push(@readonly_files, $file_name);
1.745     raeburn  5500:                     last;
1.561     banghart 5501:                 }
                   5502:             }
1.745     raeburn  5503:         }
1.561     banghart 5504:     }
                   5505:     return @readonly_files;
                   5506: }
1.577     banghart 5507: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 5508: 
1.577     banghart 5509: sub get_marked_as_readonly_hash {
1.745     raeburn  5510:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 5511:     my %readonly_files;
1.745     raeburn  5512:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5513:         if (defined($group)) {
                   5514:             if ($file_name !~ m-^\Q$group\E/-) {
                   5515:                 next;
                   5516:             }
                   5517:         }
1.577     banghart 5518:         if (ref($value) eq "ARRAY"){
                   5519:             foreach my $stored_what (@{$value}) {
1.745     raeburn  5520:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 5521:                     foreach my $lock_descriptor(@{$stored_what}) {
                   5522:                         if ($lock_descriptor eq 'graded') {
                   5523:                             $readonly_files{$file_name} = 'graded';
                   5524:                         } elsif ($lock_descriptor eq 'handback') {
                   5525:                             $readonly_files{$file_name} = 'handback';
                   5526:                         } else {
                   5527:                             if (!exists($readonly_files{$file_name})) {
                   5528:                                 $readonly_files{$file_name} = 'locked';
                   5529:                             }
                   5530:                         }
1.745     raeburn  5531:                     }
1.750     banghart 5532:                 } 
1.577     banghart 5533:             }
                   5534:         } 
                   5535:     }
                   5536:     return %readonly_files;
                   5537: }
1.559     banghart 5538: # ------------------------------------------------------------ Unmark as Read Only
                   5539: 
                   5540: sub unmark_as_readonly {
1.629     banghart 5541:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   5542:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  5543:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 5544:     $file_name = &declutter_portfile($file_name);
1.634     albertel 5545:     my $symb_crs = $what;
                   5546:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  5547:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 5548:     my ($tmp)=keys(%current_permissions);
                   5549:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5550:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 5551:     foreach my $file (@readonly_files) {
1.759     albertel 5552: 	my $clean_file = &declutter_portfile($file);
                   5553: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 5554: 	my $current_locks = $current_permissions{$file};
1.563     banghart 5555:         my @new_locks;
                   5556:         my @del_keys;
                   5557:         if (ref($current_locks) eq "ARRAY"){
                   5558:             foreach my $locker (@{$current_locks}) {
1.632     albertel 5559:                 my $compare=$locker;
1.749     raeburn  5560:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  5561:                     $compare=join('',@{$locker});
1.746     raeburn  5562:                     if ($compare ne $symb_crs) {
                   5563:                         push(@new_locks, $locker);
                   5564:                     }
1.563     banghart 5565:                 }
                   5566:             }
1.650     albertel 5567:             if (scalar(@new_locks) > 0) {
1.563     banghart 5568:                 $current_permissions{$file} = \@new_locks;
                   5569:             } else {
                   5570:                 push(@del_keys, $file);
1.613     albertel 5571:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 5572:                 delete($current_permissions{$file});
1.563     banghart 5573:             }
                   5574:         }
1.561     banghart 5575:     }
1.613     albertel 5576:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5577:     return;
                   5578: }
1.512     banghart 5579: 
1.17      www      5580: # ------------------------------------------------------------ Directory lister
                   5581: 
                   5582: sub dirlist {
1.253     stredwic 5583:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
                   5584: 
1.18      www      5585:     $uri=~s/^\///;
                   5586:     $uri=~s/\/$//;
1.253     stredwic 5587:     my ($udom, $uname);
                   5588:     (undef,$udom,$uname)=split(/\//,$uri);
                   5589:     if(defined($userdomain)) {
                   5590:         $udom = $userdomain;
                   5591:     }
                   5592:     if(defined($username)) {
                   5593:         $uname = $username;
                   5594:     }
                   5595: 
                   5596:     my $dirRoot = $perlvar{'lonDocRoot'};
                   5597:     if(defined($alternateDirectoryRoot)) {
                   5598:         $dirRoot = $alternateDirectoryRoot;
                   5599:         $dirRoot =~ s/\/$//;
1.751     banghart 5600:     }
1.253     stredwic 5601: 
                   5602:     if($udom) {
                   5603:         if($uname) {
1.800     albertel 5604:             my $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   5605: 				 &homeserver($uname,$udom));
1.605     matthew  5606:             my @listing_results;
                   5607:             if ($listing eq 'unknown_cmd') {
1.800     albertel 5608:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   5609: 				  &homeserver($uname,$udom));
1.605     matthew  5610:                 @listing_results = split(/:/,$listing);
                   5611:             } else {
                   5612:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   5613:             }
                   5614:             return @listing_results;
1.253     stredwic 5615:         } elsif(!defined($alternateDirectoryRoot)) {
1.800     albertel 5616:             my %allusers;
1.841     albertel 5617: 	    my %servers = &get_servers($udom,'library');
                   5618: 	    foreach my $tryserver (keys(%servers)) {
                   5619: 		my $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   5620: 				     $udom, $tryserver);
                   5621: 		my @listing_results;
                   5622: 		if ($listing eq 'unknown_cmd') {
                   5623: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   5624: 				      $udom, $tryserver);
                   5625: 		    @listing_results = split(/:/,$listing);
                   5626: 		} else {
                   5627: 		    @listing_results =
                   5628: 			map { &unescape($_); } split(/:/,$listing);
                   5629: 		}
                   5630: 		if ($listing_results[0] ne 'no_such_dir' && 
                   5631: 		    $listing_results[0] ne 'empty'       &&
                   5632: 		    $listing_results[0] ne 'con_lost') {
                   5633: 		    foreach my $line (@listing_results) {
                   5634: 			my ($entry) = split(/&/,$line,2);
                   5635: 			$allusers{$entry} = 1;
                   5636: 		    }
                   5637: 		}
1.253     stredwic 5638:             }
                   5639:             my $alluserstr='';
1.800     albertel 5640:             foreach my $user (sort(keys(%allusers))) {
                   5641:                 $alluserstr.=$user.'&user:';
1.253     stredwic 5642:             }
                   5643:             $alluserstr=~s/:$//;
                   5644:             return split(/:/,$alluserstr);
                   5645:         } else {
1.800     albertel 5646:             return ('missing user name');
1.253     stredwic 5647:         }
                   5648:     } elsif(!defined($alternateDirectoryRoot)) {
1.841     albertel 5649:         my @all_domains = sort(&all_domains());
                   5650:          foreach my $domain (@all_domains) {
                   5651:              $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   5652:          }
                   5653:          return @all_domains;
                   5654:      } else {
1.800     albertel 5655:         return ('missing domain');
1.275     stredwic 5656:     }
                   5657: }
                   5658: 
                   5659: # --------------------------------------------- GetFileTimestamp
                   5660: # This function utilizes dirlist and returns the date stamp for
                   5661: # when it was last modified.  It will also return an error of -1
                   5662: # if an error occurs
                   5663: 
1.410     matthew  5664: ##
                   5665: ## FIXME: This subroutine assumes its caller knows something about the
                   5666: ## directory structure of the home server for the student ($root).
                   5667: ## Not a good assumption to make.  Since this is for looking up files
                   5668: ## in user directories, the full path should be constructed by lond, not
                   5669: ## whatever machine we request data from.
                   5670: ##
1.275     stredwic 5671: sub GetFileTimestamp {
                   5672:     my ($studentDomain,$studentName,$filename,$root)=@_;
1.807     albertel 5673:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   5674:     $studentName   = &LONCAPA::clean_username($studentName);
1.275     stredwic 5675:     my $subdir=$studentName.'__';
                   5676:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   5677:     my $proname="$studentDomain/$subdir/$studentName";
                   5678:     $proname .= '/'.$filename;
1.375     matthew  5679:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
                   5680:                                               $studentName, $root);
1.275     stredwic 5681:     my @stats = split('&', $fileStat);
                   5682:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  5683:         # @stats contains first the filename, then the stat output
                   5684:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 5685:     } else {
                   5686:         return -1;
1.253     stredwic 5687:     }
1.26      www      5688: }
                   5689: 
1.712     albertel 5690: sub stat_file {
                   5691:     my ($uri) = @_;
1.787     albertel 5692:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 5693: 
1.712     albertel 5694:     my ($udom,$uname,$file,$dir);
                   5695:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   5696: 	($udom,$uname,$file) =
1.811     albertel 5697: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 5698: 	$file = 'userfiles/'.$file;
1.740     www      5699: 	$dir = &propath($udom,$uname);
1.712     albertel 5700:     }
                   5701:     if ($uri =~ m-^/res/-) {
                   5702: 	($udom,$uname) = 
1.807     albertel 5703: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 5704: 	$file = $uri;
                   5705:     }
                   5706: 
                   5707:     if (!$udom || !$uname || !$file) {
                   5708: 	# unable to handle the uri
                   5709: 	return ();
                   5710:     }
                   5711: 
                   5712:     my ($result) = &dirlist($file,$udom,$uname,$dir);
                   5713:     my @stats = split('&', $result);
1.721     banghart 5714:     
1.712     albertel 5715:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   5716: 	shift(@stats); #filename is first
                   5717: 	return @stats;
                   5718:     }
                   5719:     return ();
                   5720: }
                   5721: 
1.26      www      5722: # -------------------------------------------------------- Value of a Condition
                   5723: 
1.713     albertel 5724: # gets the value of a specific preevaluated condition
                   5725: #    stored in the string  $env{user.state.<cid>}
                   5726: # or looks up a condition reference in the bighash and if if hasn't
                   5727: # already been evaluated recurses into docondval to get the value of
                   5728: # the condition, then memoizing it to 
                   5729: #   $env{user.state.<cid>.<condition>}
1.40      www      5730: sub directcondval {
                   5731:     my $number=shift;
1.620     albertel 5732:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 5733: 	&Apache::lonuserstate::evalstate();
                   5734:     }
1.713     albertel 5735:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   5736: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   5737:     } elsif ($number =~ /^_/) {
                   5738: 	my $sub_condition;
                   5739: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   5740: 		&GDBM_READER(),0640)) {
                   5741: 	    $sub_condition=$bighash{'conditions'.$number};
                   5742: 	    untie(%bighash);
                   5743: 	}
                   5744: 	my $value = &docondval($sub_condition);
                   5745: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
                   5746: 	return $value;
                   5747:     }
1.620     albertel 5748:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   5749:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      5750:     } else {
                   5751:        return 2;
                   5752:     }
                   5753: }
                   5754: 
1.713     albertel 5755: # get the collection of conditions for this resource
1.26      www      5756: sub condval {
                   5757:     my $condidx=shift;
1.54      www      5758:     my $allpathcond='';
1.713     albertel 5759:     foreach my $cond (split(/\|/,$condidx)) {
                   5760: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   5761: 	    $allpathcond.=
                   5762: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   5763: 	}
1.191     harris41 5764:     }
1.54      www      5765:     $allpathcond=~s/\|$//;
1.713     albertel 5766:     return &docondval($allpathcond);
                   5767: }
                   5768: 
                   5769: #evaluates an expression of conditions
                   5770: sub docondval {
                   5771:     my ($allpathcond) = @_;
                   5772:     my $result=0;
                   5773:     if ($env{'request.course.id'}
                   5774: 	&& defined($allpathcond)) {
                   5775: 	my $operand='|';
                   5776: 	my @stack;
                   5777: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   5778: 	    if ($chunk eq '(') {
                   5779: 		push @stack,($operand,$result);
                   5780: 	    } elsif ($chunk eq ')') {
                   5781: 		my $before=pop @stack;
                   5782: 		if (pop @stack eq '&') {
                   5783: 		    $result=$result>$before?$before:$result;
                   5784: 		} else {
                   5785: 		    $result=$result>$before?$result:$before;
                   5786: 		}
                   5787: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   5788: 		$operand=$chunk;
                   5789: 	    } else {
                   5790: 		my $new=directcondval($chunk);
                   5791: 		if ($operand eq '&') {
                   5792: 		    $result=$result>$new?$new:$result;
                   5793: 		} else {
                   5794: 		    $result=$result>$new?$result:$new;
                   5795: 		}
                   5796: 	    }
                   5797: 	}
1.26      www      5798:     }
                   5799:     return $result;
1.421     albertel 5800: }
                   5801: 
                   5802: # ---------------------------------------------------- Devalidate courseresdata
                   5803: 
                   5804: sub devalidatecourseresdata {
                   5805:     my ($coursenum,$coursedomain)=@_;
                   5806:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 5807:     &devalidate_cache_new('courseres',$hashid);
1.28      www      5808: }
                   5809: 
1.763     www      5810: 
1.200     www      5811: # --------------------------------------------------- Course Resourcedata Query
                   5812: 
1.624     albertel 5813: sub get_courseresdata {
                   5814:     my ($coursenum,$coursedomain)=@_;
1.200     www      5815:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   5816:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 5817:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 5818:     my %dumpreply;
1.417     albertel 5819:     unless (defined($cached)) {
1.624     albertel 5820: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 5821: 	$result=\%dumpreply;
1.251     albertel 5822: 	my ($tmp) = keys(%dumpreply);
                   5823: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 5824: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 5825: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   5826: 	    return $tmp;
1.416     albertel 5827: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 5828: 	    $result=undef;
1.599     albertel 5829: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 5830: 	}
                   5831:     }
1.624     albertel 5832:     return $result;
                   5833: }
                   5834: 
1.633     albertel 5835: sub devalidateuserresdata {
                   5836:     my ($uname,$udom)=@_;
                   5837:     my $hashid="$udom:$uname";
                   5838:     &devalidate_cache_new('userres',$hashid);
                   5839: }
                   5840: 
1.624     albertel 5841: sub get_userresdata {
                   5842:     my ($uname,$udom)=@_;
                   5843:     #most student don\'t have any data set, check if there is some data
                   5844:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   5845: 
                   5846:     my $hashid="$udom:$uname";
                   5847:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   5848:     if (!defined($cached)) {
                   5849: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   5850: 	$result=\%resourcedata;
                   5851: 	&do_cache_new('userres',$hashid,$result,600);
                   5852:     }
                   5853:     my ($tmp)=keys(%$result);
                   5854:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   5855: 	return $result;
                   5856:     }
                   5857:     #error 2 occurs when the .db doesn't exist
                   5858:     if ($tmp!~/error: 2 /) {
1.672     albertel 5859: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 5860: 		 " Trying to get resource data for ".
                   5861: 		 $uname." at ".$udom.": ".
                   5862: 		 $tmp."</font>");
                   5863:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 5864: 	#&EXT_cache_set($udom,$uname);
                   5865: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 5866: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 5867:     }
                   5868:     return $tmp;
                   5869: }
                   5870: 
                   5871: sub resdata {
                   5872:     my ($name,$domain,$type,@which)=@_;
                   5873:     my $result;
                   5874:     if ($type eq 'course') {
                   5875: 	$result=&get_courseresdata($name,$domain);
                   5876:     } elsif ($type eq 'user') {
                   5877: 	$result=&get_userresdata($name,$domain);
                   5878:     }
                   5879:     if (!ref($result)) { return $result; }    
1.251     albertel 5880:     foreach my $item (@which) {
1.417     albertel 5881: 	if (defined($result->{$item})) {
                   5882: 	    return $result->{$item};
1.251     albertel 5883: 	}
1.250     albertel 5884:     }
1.291     albertel 5885:     return undef;
1.200     www      5886: }
                   5887: 
1.379     matthew  5888: #
                   5889: # EXT resource caching routines
                   5890: #
                   5891: 
                   5892: sub clear_EXT_cache_status {
1.383     albertel 5893:     &delenv('cache.EXT.');
1.379     matthew  5894: }
                   5895: 
                   5896: sub EXT_cache_status {
                   5897:     my ($target_domain,$target_user) = @_;
1.383     albertel 5898:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 5899:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  5900:         # We know already the user has no data
                   5901:         return 1;
                   5902:     } else {
                   5903:         return 0;
                   5904:     }
                   5905: }
                   5906: 
                   5907: sub EXT_cache_set {
                   5908:     my ($target_domain,$target_user) = @_;
1.383     albertel 5909:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.633     albertel 5910:     #&appenv($cachename => time);
1.379     matthew  5911: }
                   5912: 
1.28      www      5913: # --------------------------------------------------------- Value of a Variable
1.58      www      5914: sub EXT {
1.715     albertel 5915: 
1.395     albertel 5916:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      5917:     unless ($varname) { return ''; }
1.218     albertel 5918:     #get real user name/domain, courseid and symb
                   5919:     my $courseid;
1.359     albertel 5920:     my $publicuser;
1.427     www      5921:     if ($symbparm) {
                   5922: 	$symbparm=&get_symb_from_alias($symbparm);
                   5923:     }
1.218     albertel 5924:     if (!($uname && $udom)) {
1.790     albertel 5925:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 5926:       if (!$symbparm) {	$symbparm=$cursymb; }
                   5927:     } else {
1.620     albertel 5928: 	$courseid=$env{'request.course.id'};
1.218     albertel 5929:     }
1.48      www      5930:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   5931:     my $rest;
1.320     albertel 5932:     if (defined($therest[0])) {
1.48      www      5933:        $rest=join('.',@therest);
                   5934:     } else {
                   5935:        $rest='';
                   5936:     }
1.320     albertel 5937: 
1.57      www      5938:     my $qualifierrest=$qualifier;
                   5939:     if ($rest) { $qualifierrest.='.'.$rest; }
                   5940:     my $spacequalifierrest=$space;
                   5941:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      5942:     if ($realm eq 'user') {
1.48      www      5943: # --------------------------------------------------------------- user.resource
                   5944: 	if ($space eq 'resource') {
1.651     albertel 5945: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   5946: 		  || defined($Apache::lonhomework::parsing_a_task))
                   5947: 		 &&
1.744     albertel 5948: 		 ($symbparm eq &symbread()) ) {	
                   5949: 		# if we are in the middle of processing the resource the
                   5950: 		# get the value we are planning on committing
                   5951:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   5952:                     return $Apache::lonhomework::results{$qualifierrest};
                   5953:                 } else {
                   5954:                     return $Apache::lonhomework::history{$qualifierrest};
                   5955:                 }
1.335     albertel 5956: 	    } else {
1.359     albertel 5957: 		my %restored;
1.620     albertel 5958: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 5959: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   5960: 		} else {
                   5961: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   5962: 		}
1.335     albertel 5963: 		return $restored{$qualifierrest};
                   5964: 	    }
1.48      www      5965: # ----------------------------------------------------------------- user.access
                   5966:         } elsif ($space eq 'access') {
1.218     albertel 5967: 	    # FIXME - not supporting calls for a specific user
1.48      www      5968:             return &allowed($qualifier,$rest);
                   5969: # ------------------------------------------ user.preferences, user.environment
                   5970:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 5971: 	    if (($uname eq $env{'user.name'}) &&
                   5972: 		($udom eq $env{'user.domain'})) {
                   5973: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 5974: 	    } else {
1.359     albertel 5975: 		my %returnhash;
                   5976: 		if (!$publicuser) {
                   5977: 		    %returnhash=&userenvironment($udom,$uname,
                   5978: 						 $qualifierrest);
                   5979: 		}
1.218     albertel 5980: 		return $returnhash{$qualifierrest};
                   5981: 	    }
1.48      www      5982: # ----------------------------------------------------------------- user.course
                   5983:         } elsif ($space eq 'course') {
1.218     albertel 5984: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 5985:             return $env{join('.',('request.course',$qualifier))};
1.48      www      5986: # ------------------------------------------------------------------- user.role
                   5987:         } elsif ($space eq 'role') {
1.218     albertel 5988: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 5989:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      5990:             if ($qualifier eq 'value') {
                   5991: 		return $role;
                   5992:             } elsif ($qualifier eq 'extent') {
                   5993:                 return $where;
                   5994:             }
                   5995: # ----------------------------------------------------------------- user.domain
                   5996:         } elsif ($space eq 'domain') {
1.218     albertel 5997:             return $udom;
1.48      www      5998: # ------------------------------------------------------------------- user.name
                   5999:         } elsif ($space eq 'name') {
1.218     albertel 6000:             return $uname;
1.48      www      6001: # ---------------------------------------------------- Any other user namespace
1.29      www      6002:         } else {
1.359     albertel 6003: 	    my %reply;
                   6004: 	    if (!$publicuser) {
                   6005: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   6006: 	    }
                   6007: 	    return $reply{$qualifierrest};
1.48      www      6008:         }
1.236     www      6009:     } elsif ($realm eq 'query') {
                   6010: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 6011:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   6012: 						[$spacequalifierrest]);
1.620     albertel 6013: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      6014:    } elsif ($realm eq 'request') {
1.48      www      6015: # ------------------------------------------------------------- request.browser
                   6016:         if ($space eq 'browser') {
1.430     www      6017: 	    if ($qualifier eq 'textremote') {
1.676     albertel 6018: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      6019: 		    return 1;
                   6020: 		} else {
                   6021: 		    return 0;
                   6022: 		}
                   6023: 	    } else {
1.620     albertel 6024: 		return $env{'browser.'.$qualifier};
1.430     www      6025: 	    }
1.57      www      6026: # ------------------------------------------------------------ request.filename
                   6027:         } else {
1.620     albertel 6028:             return $env{'request.'.$spacequalifierrest};
1.29      www      6029:         }
1.28      www      6030:     } elsif ($realm eq 'course') {
1.48      www      6031: # ---------------------------------------------------------- course.description
1.620     albertel 6032:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      6033:     } elsif ($realm eq 'resource') {
1.165     www      6034: 
1.620     albertel 6035: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 6036: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   6037: 	}
1.693     albertel 6038: 
                   6039: 	if ($space eq 'title') {
                   6040: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   6041: 	    return &gettitle($symbparm);
                   6042: 	}
                   6043: 	
                   6044: 	if ($space eq 'map') {
                   6045: 	    my ($map) = &decode_symb($symbparm);
                   6046: 	    return &symbread($map);
                   6047: 	}
                   6048: 
                   6049: 	my ($section, $group, @groups);
1.593     albertel 6050: 	my ($courselevelm,$courselevel);
1.539     albertel 6051: 	if ($symbparm && defined($courseid) && 
1.620     albertel 6052: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      6053: 
1.218     albertel 6054: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      6055: 
1.60      www      6056: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 6057: 	    my $symbp=$symbparm;
1.735     albertel 6058: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 6059: 
                   6060: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   6061: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   6062: 
1.620     albertel 6063: 	    if (($env{'user.name'} eq $uname) &&
                   6064: 		($env{'user.domain'} eq $udom)) {
                   6065: 		$section=$env{'request.course.sec'};
1.733     raeburn  6066:                 @groups = split(/:/,$env{'request.course.groups'});  
                   6067:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 6068: 	    } else {
1.539     albertel 6069: 		if (! defined($usection)) {
1.551     albertel 6070: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 6071: 		} else {
                   6072: 		    $section = $usection;
                   6073: 		}
1.733     raeburn  6074:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 6075: 	    }
                   6076: 
                   6077: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   6078: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   6079: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   6080: 
1.593     albertel 6081: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 6082: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 6083: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      6084: 
1.60      www      6085: # ----------------------------------------------------------- first, check user
1.624     albertel 6086: 
                   6087: 	    my $userreply=&resdata($uname,$udom,'user',
                   6088: 				       ($courselevelr,$courselevelm,
                   6089: 					$courselevel));
                   6090: 	    if (defined($userreply)) { return $userreply; }
1.95      www      6091: 
1.594     albertel 6092: # ------------------------------------------------ second, check some of course
1.684     raeburn  6093:             my $coursereply;
1.691     raeburn  6094:             if (@groups > 0) {
                   6095:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   6096:                                        $mapparm,$spacequalifierrest);
1.684     raeburn  6097:                 if (defined($coursereply)) { return $coursereply; }
                   6098:             }
1.96      www      6099: 
1.684     raeburn  6100: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.624     albertel 6101: 				     $env{'course.'.$courseid.'.domain'},
                   6102: 				     'course',
                   6103: 				     ($seclevelr,$seclevelm,$seclevel,
                   6104: 				      $courselevelr));
1.287     albertel 6105: 	    if (defined($coursereply)) { return $coursereply; }
1.200     www      6106: 
1.60      www      6107: # ------------------------------------------------------ third, check map parms
1.218     albertel 6108: 	    my %parmhash=();
                   6109: 	    my $thisparm='';
                   6110: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 6111: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 6112: 		    &GDBM_READER(),0640)) {
1.218     albertel 6113: 		$thisparm=$parmhash{$symbparm};
                   6114: 		untie(%parmhash);
                   6115: 	    }
                   6116: 	    if ($thisparm) { return $thisparm; }
                   6117: 	}
1.594     albertel 6118: # ------------------------------------------ fourth, look in resource metadata
1.71      www      6119: 
1.218     albertel 6120: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 6121: 	my $filename;
                   6122: 	if (!$symbparm) { $symbparm=&symbread(); }
                   6123: 	if ($symbparm) {
1.409     www      6124: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 6125: 	} else {
1.620     albertel 6126: 	    $filename=$env{'request.filename'};
1.282     albertel 6127: 	}
                   6128: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.288     albertel 6129: 	if (defined($metadata)) { return $metadata; }
1.282     albertel 6130: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.288     albertel 6131: 	if (defined($metadata)) { return $metadata; }
1.142     www      6132: 
1.594     albertel 6133: # ---------------------------------------------- fourth, look in rest pf course
1.593     albertel 6134: 	if ($symbparm && defined($courseid) && 
1.620     albertel 6135: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 6136: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   6137: 				     $env{'course.'.$courseid.'.domain'},
                   6138: 				     'course',
                   6139: 				     ($courselevelm,$courselevel));
1.593     albertel 6140: 	    if (defined($coursereply)) { return $coursereply; }
                   6141: 	}
1.145     www      6142: # ------------------------------------------------------------------ Cascade up
1.218     albertel 6143: 	unless ($space eq '0') {
1.336     albertel 6144: 	    my @parts=split(/_/,$space);
                   6145: 	    my $id=pop(@parts);
                   6146: 	    my $part=join('_',@parts);
                   6147: 	    if ($part eq '') { $part='0'; }
                   6148: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 6149: 				 $symbparm,$udom,$uname,$section,1);
1.337     albertel 6150: 	    if (defined($partgeneral)) { return $partgeneral; }
1.218     albertel 6151: 	}
1.395     albertel 6152: 	if ($recurse) { return undef; }
                   6153: 	my $pack_def=&packages_tab_default($filename,$varname);
                   6154: 	if (defined($pack_def)) { return $pack_def; }
1.71      www      6155: 
1.48      www      6156: # ---------------------------------------------------- Any other user namespace
                   6157:     } elsif ($realm eq 'environment') {
                   6158: # ----------------------------------------------------------------- environment
1.620     albertel 6159: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   6160: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 6161: 	} else {
1.770     albertel 6162: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   6163: 		return '';
                   6164: 	    }
1.219     albertel 6165: 	    my %returnhash=&userenvironment($udom,$uname,
                   6166: 					    $spacequalifierrest);
                   6167: 	    return $returnhash{$spacequalifierrest};
                   6168: 	}
1.28      www      6169:     } elsif ($realm eq 'system') {
1.48      www      6170: # ----------------------------------------------------------------- system.time
                   6171: 	if ($space eq 'time') {
                   6172: 	    return time;
                   6173:         }
1.696     albertel 6174:     } elsif ($realm eq 'server') {
                   6175: # ----------------------------------------------------------------- system.time
                   6176: 	if ($space eq 'name') {
                   6177: 	    return $ENV{'SERVER_NAME'};
                   6178:         }
1.28      www      6179:     }
1.48      www      6180:     return '';
1.61      www      6181: }
                   6182: 
1.691     raeburn  6183: sub check_group_parms {
                   6184:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   6185:     my @groupitems = ();
                   6186:     my $resultitem;
                   6187:     my @levels = ($symbparm,$mapparm,$what);
                   6188:     foreach my $group (@{$groups}) {
                   6189:         foreach my $level (@levels) {
                   6190:              my $item = $courseid.'.['.$group.'].'.$level;
                   6191:              push(@groupitems,$item);
                   6192:         }
                   6193:     }
                   6194:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   6195:                             $env{'course.'.$courseid.'.domain'},
                   6196:                                      'course',@groupitems);
                   6197:     return $coursereply;
                   6198: }
                   6199: 
                   6200: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  6201:     my ($courseid,@groups) = @_;
                   6202:     @groups = sort(@groups);
1.691     raeburn  6203:     return @groups;
                   6204: }
                   6205: 
1.395     albertel 6206: sub packages_tab_default {
                   6207:     my ($uri,$varname)=@_;
                   6208:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 6209: 
                   6210:     my (@extension,@specifics,$do_default);
                   6211:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 6212: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 6213: 	if ($pack_type eq 'default') {
                   6214: 	    $do_default=1;
                   6215: 	} elsif ($pack_type eq 'extension') {
                   6216: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.848     albertel 6217: 	} elsif ($pack_part eq $part) {
                   6218: 	    # only look at packages defaults for packages that this id is
1.738     albertel 6219: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   6220: 	}
                   6221:     }
                   6222:     # first look for a package that matches the requested part id
                   6223:     foreach my $package (@specifics) {
                   6224: 	my (undef,$pack_type,$pack_part)=@{$package};
                   6225: 	next if ($pack_part ne $part);
                   6226: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6227: 	    return $packagetab{"$pack_type&$name&default"};
                   6228: 	}
                   6229:     }
                   6230:     # look for any possible matching non extension_ package
                   6231:     foreach my $package (@specifics) {
                   6232: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 6233: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6234: 	    return $packagetab{"$pack_type&$name&default"};
                   6235: 	}
1.585     albertel 6236: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 6237: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   6238: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 6239: 	}
                   6240:     }
1.738     albertel 6241:     # look for any posible extension_ match
                   6242:     foreach my $package (@extension) {
                   6243: 	my ($package,$pack_type)=@{$package};
                   6244: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6245: 	    return $packagetab{"$pack_type&$name&default"};
                   6246: 	}
                   6247: 	if (defined($packagetab{$package."&$name&default"})) {
                   6248: 	    return $packagetab{$package."&$name&default"};
                   6249: 	}
                   6250:     }
                   6251:     # look for a global default setting
                   6252:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   6253: 	return $packagetab{"default&$name&default"};
                   6254:     }
1.395     albertel 6255:     return undef;
                   6256: }
                   6257: 
1.334     albertel 6258: sub add_prefix_and_part {
                   6259:     my ($prefix,$part)=@_;
                   6260:     my $keyroot;
                   6261:     if (defined($prefix) && $prefix !~ /^__/) {
                   6262: 	# prefix that has a part already
                   6263: 	$keyroot=$prefix;
                   6264:     } elsif (defined($prefix)) {
                   6265: 	# prefix that is missing a part
                   6266: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   6267:     } else {
                   6268: 	# no prefix at all
                   6269: 	if (defined($part)) { $keyroot='_'.$part; }
                   6270:     }
                   6271:     return $keyroot;
                   6272: }
                   6273: 
1.71      www      6274: # ---------------------------------------------------------------- Get metadata
                   6275: 
1.599     albertel 6276: my %metaentry;
1.71      www      6277: sub metadata {
1.176     www      6278:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      6279:     $uri=&declutter($uri);
1.288     albertel 6280:     # if it is a non metadata possible uri return quickly
1.529     albertel 6281:     if (($uri eq '') || 
                   6282: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 6283: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.423     albertel 6284:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
1.807     albertel 6285: 	($uri =~ m|home/$match_username/public_html/|)) {
1.468     albertel 6286: 	return undef;
1.288     albertel 6287:     }
1.73      www      6288:     my $filename=$uri;
                   6289:     $uri=~s/\.meta$//;
1.172     www      6290: #
                   6291: # Is the metadata already cached?
1.177     www      6292: # Look at timestamp of caching
1.172     www      6293: # Everything is cached by the main uri, libraries are never directly cached
                   6294: #
1.428     albertel 6295:     if (!defined($liburi)) {
1.599     albertel 6296: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 6297: 	if (defined($cached)) { return $result->{':'.$what}; }
                   6298:     }
                   6299:     {
1.172     www      6300: #
                   6301: # Is this a recursive call for a library?
                   6302: #
1.599     albertel 6303: #	if (! exists($metacache{$uri})) {
                   6304: #	    $metacache{$uri}={};
                   6305: #	}
1.171     www      6306:         if ($liburi) {
                   6307: 	    $liburi=&declutter($liburi);
                   6308:             $filename=$liburi;
1.401     bowersj2 6309:         } else {
1.599     albertel 6310: 	    &devalidate_cache_new('meta',$uri);
                   6311: 	    undef(%metaentry);
1.401     bowersj2 6312: 	}
1.140     www      6313:         my %metathesekeys=();
1.73      www      6314:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 6315: 	my $metastring;
1.768     albertel 6316: 	if ($uri !~ m -^(editupload)/-) {
1.543     albertel 6317: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 6318: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 6319: 	    $metastring=&getfile($file);
1.489     albertel 6320: 	}
1.208     albertel 6321:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      6322:         my $token;
1.140     www      6323:         undef %metathesekeys;
1.71      www      6324:         while ($token=$parser->get_token) {
1.339     albertel 6325: 	    if ($token->[0] eq 'S') {
                   6326: 		if (defined($token->[2]->{'package'})) {
1.172     www      6327: #
                   6328: # This is a package - get package info
                   6329: #
1.339     albertel 6330: 		    my $package=$token->[2]->{'package'};
                   6331: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6332: 		    if (defined($token->[2]->{'id'})) { 
                   6333: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   6334: 		    }
1.599     albertel 6335: 		    if ($metaentry{':packages'}) {
                   6336: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 6337: 		    } else {
1.599     albertel 6338: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 6339: 		    }
1.736     albertel 6340: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 6341: 			my $part=$keyroot;
                   6342: 			$part=~s/^\_//;
1.736     albertel 6343: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   6344: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   6345: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 6346: 			    # ignore package.tab specified default values
                   6347:                             # here &package_tab_default() will fetch those
                   6348: 			    if ($subp eq 'default') { next; }
1.736     albertel 6349: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 6350: 			    my $unikey;
                   6351: 			    if ($pack =~ /_0$/) {
                   6352: 				$unikey='parameter_0_'.$name;
                   6353: 				$part=0;
                   6354: 			    } else {
                   6355: 				$unikey='parameter'.$keyroot.'_'.$name;
                   6356: 			    }
1.339     albertel 6357: 			    if ($subp eq 'display') {
                   6358: 				$value.=' [Part: '.$part.']';
                   6359: 			    }
1.599     albertel 6360: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 6361: 			    $metathesekeys{$unikey}=1;
1.599     albertel 6362: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6363: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 6364: 			    }
1.599     albertel 6365: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   6366: 				$metaentry{':'.$unikey}=
                   6367: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 6368: 			    }
1.339     albertel 6369: 			}
                   6370: 		    }
                   6371: 		} else {
1.172     www      6372: #
                   6373: # This is not a package - some other kind of start tag
1.339     albertel 6374: #
                   6375: 		    my $entry=$token->[1];
                   6376: 		    my $unikey;
                   6377: 		    if ($entry eq 'import') {
                   6378: 			$unikey='';
                   6379: 		    } else {
                   6380: 			$unikey=$entry;
                   6381: 		    }
                   6382: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6383: 
                   6384: 		    if (defined($token->[2]->{'id'})) { 
                   6385: 			$unikey.='_'.$token->[2]->{'id'}; 
                   6386: 		    }
1.175     www      6387: 
1.339     albertel 6388: 		    if ($entry eq 'import') {
1.175     www      6389: #
                   6390: # Importing a library here
1.339     albertel 6391: #
                   6392: 			if ($depthcount<20) {
                   6393: 			    my $location=$parser->get_text('/import');
                   6394: 			    my $dir=$filename;
                   6395: 			    $dir=~s|[^/]*$||;
                   6396: 			    $location=&filelocation($dir,$location);
1.736     albertel 6397: 			    my $metadata = 
                   6398: 				&metadata($uri,'keys', $location,$unikey,
                   6399: 					  $depthcount+1);
                   6400: 			    foreach my $meta (split(',',$metadata)) {
                   6401: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   6402: 				$metathesekeys{$meta}=1;
1.339     albertel 6403: 			    }
                   6404: 			}
                   6405: 		    } else { 
                   6406: 			
                   6407: 			if (defined($token->[2]->{'name'})) { 
                   6408: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   6409: 			}
                   6410: 			$metathesekeys{$unikey}=1;
1.736     albertel 6411: 			foreach my $param (@{$token->[3]}) {
                   6412: 			    $metaentry{':'.$unikey.'.'.$param} =
                   6413: 				$token->[2]->{$param};
1.339     albertel 6414: 			}
                   6415: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 6416: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 6417: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   6418: 		 # only ws inside the tag, and not in default, so use default
                   6419: 		 # as value
1.599     albertel 6420: 			    $metaentry{':'.$unikey}=$default;
1.339     albertel 6421: 			} else {
1.321     albertel 6422: 		  # either something interesting inside the tag or default
                   6423:                   # uninteresting
1.599     albertel 6424: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 6425: 			}
1.172     www      6426: # end of not-a-package not-a-library import
1.339     albertel 6427: 		    }
1.172     www      6428: # end of not-a-package start tag
1.339     albertel 6429: 		}
1.172     www      6430: # the next is the end of "start tag"
1.339     albertel 6431: 	    }
                   6432: 	}
1.483     albertel 6433: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.737     albertel 6434: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 6435: 	    #no specific packages #how's our extension
                   6436: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 6437: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 6438: 					 \%metathesekeys);
                   6439: 	}
1.599     albertel 6440: 	if (!exists($metaentry{':packages'})) {
1.737     albertel 6441: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 6442: 		#no specific packages well let's get default then
                   6443: 		if ($key!~/^default&/) { next; }
1.488     albertel 6444: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 6445: 					     \%metathesekeys);
                   6446: 	    }
                   6447: 	}
1.338     www      6448: # are there custom rights to evaluate
1.599     albertel 6449: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 6450: 
1.338     www      6451:     #
                   6452:     # Importing a rights file here
1.339     albertel 6453:     #
                   6454: 	    unless ($depthcount) {
1.599     albertel 6455: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 6456: 		my $dir=$filename;
                   6457: 		$dir=~s|[^/]*$||;
                   6458: 		$location=&filelocation($dir,$location);
1.736     albertel 6459: 		my $rights_metadata =
                   6460: 		    &metadata($uri,'keys',$location,'_rights',
                   6461: 			      $depthcount+1);
                   6462: 		foreach my $rights (split(',',$rights_metadata)) {
                   6463: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   6464: 		    $metathesekeys{$rights}=1;
1.339     albertel 6465: 		}
                   6466: 	    }
                   6467: 	}
1.737     albertel 6468: 	# uniqifiy package listing
                   6469: 	my %seen;
                   6470: 	my @uniq_packages =
                   6471: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   6472: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   6473: 
                   6474: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 6475: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   6476: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.699     albertel 6477: 	&do_cache_new('meta',$uri,\%metaentry,60*60);
1.177     www      6478: # this is the end of "was not already recently cached
1.71      www      6479:     }
1.599     albertel 6480:     return $metaentry{':'.$what};
1.261     albertel 6481: }
                   6482: 
1.488     albertel 6483: sub metadata_create_package_def {
1.483     albertel 6484:     my ($uri,$key,$package,$metathesekeys)=@_;
                   6485:     my ($pack,$name,$subp)=split(/\&/,$key);
                   6486:     if ($subp eq 'default') { next; }
                   6487:     
1.599     albertel 6488:     if (defined($metaentry{':packages'})) {
                   6489: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 6490:     } else {
1.599     albertel 6491: 	$metaentry{':packages'}=$package;
1.483     albertel 6492:     }
                   6493:     my $value=$packagetab{$key};
                   6494:     my $unikey;
                   6495:     $unikey='parameter_0_'.$name;
1.599     albertel 6496:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 6497:     $$metathesekeys{$unikey}=1;
1.599     albertel 6498:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6499: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 6500:     }
1.599     albertel 6501:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   6502: 	$metaentry{':'.$unikey}=
                   6503: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 6504:     }
                   6505: }
                   6506: 
1.261     albertel 6507: sub metadata_generate_part0 {
                   6508:     my ($metadata,$metacache,$uri) = @_;
                   6509:     my %allnames;
1.737     albertel 6510:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 6511: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 6512: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   6513: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 6514: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 6515: 	    $allnames{$name}=$part;
                   6516: 	  }
                   6517: 	}
                   6518:     }
                   6519:     foreach my $name (keys(%allnames)) {
                   6520:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 6521:       my $key=":parameter_0_$name";
1.261     albertel 6522:       $$metacache{"$key.part"}='0';
                   6523:       $$metacache{"$key.name"}=$name;
1.428     albertel 6524:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 6525: 					   $allnames{$name}.'_'.$name.
                   6526: 					   '.type'};
1.428     albertel 6527:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 6528: 			     '.display'};
1.644     www      6529:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 6530:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 6531:       $$metacache{"$key.display"}=$olddis;
                   6532:     }
1.71      www      6533: }
                   6534: 
1.764     albertel 6535: # ------------------------------------------------------ Devalidate title cache
                   6536: 
                   6537: sub devalidate_title_cache {
                   6538:     my ($url)=@_;
                   6539:     if (!$env{'request.course.id'}) { return; }
                   6540:     my $symb=&symbread($url);
                   6541:     if (!$symb) { return; }
                   6542:     my $key=$env{'request.course.id'}."\0".$symb;
                   6543:     &devalidate_cache_new('title',$key);
                   6544: }
                   6545: 
1.301     www      6546: # ------------------------------------------------- Get the title of a resource
                   6547: 
                   6548: sub gettitle {
                   6549:     my $urlsymb=shift;
                   6550:     my $symb=&symbread($urlsymb);
1.534     albertel 6551:     if ($symb) {
1.620     albertel 6552: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 6553: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 6554: 	if (defined($cached)) { 
                   6555: 	    return $result;
                   6556: 	}
1.534     albertel 6557: 	my ($map,$resid,$url)=&decode_symb($symb);
                   6558: 	my $title='';
                   6559: 	my %bighash;
1.620     albertel 6560: 	if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.534     albertel 6561: 		&GDBM_READER(),0640)) {
                   6562: 	    my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   6563: 	    $title=$bighash{'title_'.$mapid.'.'.$resid};
                   6564: 	    untie %bighash;
                   6565: 	}
                   6566: 	$title=~s/\&colon\;/\:/gs;
                   6567: 	if ($title) {
1.599     albertel 6568: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 6569: 	}
                   6570: 	$urlsymb=$url;
                   6571:     }
                   6572:     my $title=&metadata($urlsymb,'title');
                   6573:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   6574:     return $title;
1.301     www      6575: }
1.613     albertel 6576: 
1.614     albertel 6577: sub get_slot {
                   6578:     my ($which,$cnum,$cdom)=@_;
                   6579:     if (!$cnum || !$cdom) {
1.790     albertel 6580: 	(undef,my $courseid)=&whichuser();
1.620     albertel 6581: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   6582: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 6583:     }
1.703     albertel 6584:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   6585:     my %slotinfo;
                   6586:     if (exists($remembered{$key})) {
                   6587: 	$slotinfo{$which} = $remembered{$key};
                   6588:     } else {
                   6589: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   6590: 	&Apache::lonhomework::showhash(%slotinfo);
                   6591: 	my ($tmp)=keys(%slotinfo);
                   6592: 	if ($tmp=~/^error:/) { return (); }
                   6593: 	$remembered{$key} = $slotinfo{$which};
                   6594:     }
1.616     albertel 6595:     if (ref($slotinfo{$which}) eq 'HASH') {
                   6596: 	return %{$slotinfo{$which}};
                   6597:     }
                   6598:     return $slotinfo{$which};
1.614     albertel 6599: }
1.31      www      6600: # ------------------------------------------------- Update symbolic store links
                   6601: 
                   6602: sub symblist {
                   6603:     my ($mapname,%newhash)=@_;
1.438     www      6604:     $mapname=&deversion(&declutter($mapname));
1.31      www      6605:     my %hash;
1.620     albertel 6606:     if (($env{'request.course.fn'}) && (%newhash)) {
                   6607:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6608:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 6609: 	    foreach my $url (keys %newhash) {
                   6610: 		next if ($url eq 'last_known'
                   6611: 			 && $env{'form.no_update_last_known'});
                   6612: 		$hash{declutter($url)}=&encode_symb($mapname,
                   6613: 						    $newhash{$url}->[1],
                   6614: 						    $newhash{$url}->[0]);
1.191     harris41 6615:             }
1.31      www      6616:             if (untie(%hash)) {
                   6617: 		return 'ok';
                   6618:             }
                   6619:         }
                   6620:     }
                   6621:     return 'error';
1.212     www      6622: }
                   6623: 
                   6624: # --------------------------------------------------------------- Verify a symb
                   6625: 
                   6626: sub symbverify {
1.510     www      6627:     my ($symb,$thisurl)=@_;
                   6628:     my $thisfn=$thisurl;
1.439     www      6629:     $thisfn=&declutter($thisfn);
1.215     www      6630: # direct jump to resource in page or to a sequence - will construct own symbs
                   6631:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   6632: # check URL part
1.409     www      6633:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      6634: 
1.431     www      6635:     unless ($url eq $thisfn) { return 0; }
1.213     www      6636: 
1.216     www      6637:     $symb=&symbclean($symb);
1.510     www      6638:     $thisurl=&deversion($thisurl);
1.439     www      6639:     $thisfn=&deversion($thisfn);
1.213     www      6640: 
                   6641:     my %bighash;
                   6642:     my $okay=0;
1.431     www      6643: 
1.620     albertel 6644:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6645:                             &GDBM_READER(),0640)) {
1.510     www      6646:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      6647:         unless ($ids) { 
1.510     www      6648:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      6649:         }
                   6650:         if ($ids) {
                   6651: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 6652: 	    foreach my $id (split(/\,/,$ids)) {
                   6653: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      6654:                if (
                   6655:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   6656:    eq $symb) { 
1.620     albertel 6657: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 6658: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 6659: 		       $okay=1; 
                   6660: 		   }
                   6661: 	       }
1.216     www      6662: 	   }
                   6663:         }
1.213     www      6664: 	untie(%bighash);
                   6665:     }
                   6666:     return $okay;
1.31      www      6667: }
                   6668: 
1.210     www      6669: # --------------------------------------------------------------- Clean-up symb
                   6670: 
                   6671: sub symbclean {
                   6672:     my $symb=shift;
1.568     albertel 6673:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      6674: # remove version from map
                   6675:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      6676: 
1.210     www      6677: # remove version from URL
                   6678:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      6679: 
1.507     www      6680: # remove wrapper
                   6681: 
1.510     www      6682:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 6683:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      6684:     return $symb;
1.409     www      6685: }
                   6686: 
                   6687: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 6688: 
                   6689: sub encode_symb {
                   6690:     my ($map,$resid,$url)=@_;
                   6691:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   6692: }
1.409     www      6693: 
                   6694: sub decode_symb {
1.568     albertel 6695:     my $symb=shift;
                   6696:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   6697:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      6698:     return (&fixversion($map),$resid,&fixversion($url));
                   6699: }
                   6700: 
                   6701: sub fixversion {
                   6702:     my $fn=shift;
1.609     banghart 6703:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      6704:     my %bighash;
                   6705:     my $uri=&clutter($fn);
1.620     albertel 6706:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      6707: # is this cached?
1.599     albertel 6708:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      6709:     if (defined($cached)) { return $result; }
                   6710: # unfortunately not cached, or expired
1.620     albertel 6711:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      6712: 	    &GDBM_READER(),0640)) {
                   6713:  	if ($bighash{'version_'.$uri}) {
                   6714:  	    my $version=$bighash{'version_'.$uri};
1.444     www      6715:  	    unless (($version eq 'mostrecent') || 
                   6716: 		    ($version==&getversion($uri))) {
1.440     www      6717:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   6718:  	    }
                   6719:  	}
                   6720:  	untie %bighash;
1.413     www      6721:     }
1.599     albertel 6722:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      6723: }
                   6724: 
                   6725: sub deversion {
                   6726:     my $url=shift;
                   6727:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   6728:     return $url;
1.210     www      6729: }
                   6730: 
1.31      www      6731: # ------------------------------------------------------ Return symb list entry
                   6732: 
                   6733: sub symbread {
1.249     www      6734:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 6735:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 6736:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      6737: # no filename provided? try from environment
1.44      www      6738:     unless ($thisfn) {
1.620     albertel 6739:         if ($env{'request.symb'}) {
                   6740: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 6741: 	}
1.620     albertel 6742: 	$thisfn=$env{'request.filename'};
1.44      www      6743:     }
1.569     albertel 6744:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      6745: # is that filename actually a symb? Verify, clean, and return
                   6746:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 6747: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 6748: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 6749: 	}
1.242     www      6750:     }
1.44      www      6751:     $thisfn=declutter($thisfn);
1.31      www      6752:     my %hash;
1.37      www      6753:     my %bighash;
                   6754:     my $syval='';
1.620     albertel 6755:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  6756:         my $targetfn = $thisfn;
1.609     banghart 6757:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  6758:             $targetfn = 'adm/wrapper/'.$thisfn;
                   6759:         }
1.687     albertel 6760: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   6761: 	    $targetfn=$1;
                   6762: 	}
1.620     albertel 6763:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6764:                       &GDBM_READER(),0640)) {
1.481     raeburn  6765: 	    $syval=$hash{$targetfn};
1.37      www      6766:             untie(%hash);
                   6767:         }
                   6768: # ---------------------------------------------------------- There was an entry
                   6769:         if ($syval) {
1.601     albertel 6770: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 6771: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.601     albertel 6772: 		    #&appenv('request.ambiguous' => $thisfn);
1.620     albertel 6773: 		    #return $env{$cache_str}='';
1.601     albertel 6774: 		#}    
                   6775: 		#$syval.=$1;
                   6776: 	    #}
1.37      www      6777:         } else {
                   6778: # ------------------------------------------------------- Was not in symb table
1.620     albertel 6779:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6780:                             &GDBM_READER(),0640)) {
1.37      www      6781: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      6782:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      6783:               unless ($ids) { 
                   6784:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      6785:               }
                   6786:               unless ($ids) {
                   6787: # alias?
                   6788: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      6789:               }
1.37      www      6790:               if ($ids) {
                   6791: # ------------------------------------------------------------------- Has ID(s)
                   6792:                  my @possibilities=split(/\,/,$ids);
1.39      www      6793:                  if ($#possibilities==0) {
                   6794: # ----------------------------------------------- There is only one possibility
1.37      www      6795: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 6796: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6797: 						    $resid,$thisfn);
1.249     www      6798:                  } elsif (!$donotrecurse) {
1.39      www      6799: # ------------------------------------------ There is more than one possibility
                   6800:                      my $realpossible=0;
1.800     albertel 6801:                      foreach my $id (@possibilities) {
                   6802: 			 my $file=$bighash{'src_'.$id};
1.39      www      6803:                          if (&allowed('bre',$file)) {
1.800     albertel 6804:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      6805:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   6806: 				$realpossible++;
1.626     albertel 6807:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6808: 						    $resid,$thisfn);
1.39      www      6809:                             }
                   6810: 			 }
1.191     harris41 6811:                      }
1.39      www      6812: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      6813:                  } else {
                   6814:                      $syval='';
1.37      www      6815:                  }
                   6816: 	      }
                   6817:               untie(%bighash)
1.481     raeburn  6818:            }
1.31      www      6819:         }
1.62      www      6820:         if ($syval) {
1.620     albertel 6821: 	    return $env{$cache_str}=$syval;
1.62      www      6822:         }
1.31      www      6823:     }
1.44      www      6824:     &appenv('request.ambiguous' => $thisfn);
1.620     albertel 6825:     return $env{$cache_str}='';
1.31      www      6826: }
                   6827: 
                   6828: # ---------------------------------------------------------- Return random seed
                   6829: 
1.32      www      6830: sub numval {
                   6831:     my $txt=shift;
                   6832:     $txt=~tr/A-J/0-9/;
                   6833:     $txt=~tr/a-j/0-9/;
                   6834:     $txt=~tr/K-T/0-9/;
                   6835:     $txt=~tr/k-t/0-9/;
                   6836:     $txt=~tr/U-Z/0-5/;
                   6837:     $txt=~tr/u-z/0-5/;
                   6838:     $txt=~s/\D//g;
1.564     albertel 6839:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      6840:     return int($txt);
1.368     albertel 6841: }
                   6842: 
1.484     albertel 6843: sub numval2 {
                   6844:     my $txt=shift;
                   6845:     $txt=~tr/A-J/0-9/;
                   6846:     $txt=~tr/a-j/0-9/;
                   6847:     $txt=~tr/K-T/0-9/;
                   6848:     $txt=~tr/k-t/0-9/;
                   6849:     $txt=~tr/U-Z/0-5/;
                   6850:     $txt=~tr/u-z/0-5/;
                   6851:     $txt=~s/\D//g;
                   6852:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   6853:     my $total;
                   6854:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 6855:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 6856:     return int($total);
                   6857: }
                   6858: 
1.575     albertel 6859: sub numval3 {
                   6860:     use integer;
                   6861:     my $txt=shift;
                   6862:     $txt=~tr/A-J/0-9/;
                   6863:     $txt=~tr/a-j/0-9/;
                   6864:     $txt=~tr/K-T/0-9/;
                   6865:     $txt=~tr/k-t/0-9/;
                   6866:     $txt=~tr/U-Z/0-5/;
                   6867:     $txt=~tr/u-z/0-5/;
                   6868:     $txt=~s/\D//g;
                   6869:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   6870:     my $total;
                   6871:     foreach my $val (@txts) { $total+=$val; }
                   6872:     if ($_64bit) { $total=(($total<<32)>>32); }
                   6873:     return $total;
                   6874: }
                   6875: 
1.675     albertel 6876: sub digest {
                   6877:     my ($data)=@_;
                   6878:     my $digest=&Digest::MD5::md5($data);
                   6879:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   6880:     my ($e,$f);
                   6881:     {
                   6882:         use integer;
                   6883:         $e=($a+$b);
                   6884:         $f=($c+$d);
                   6885:         if ($_64bit) {
                   6886:             $e=(($e<<32)>>32);
                   6887:             $f=(($f<<32)>>32);
                   6888:         }
                   6889:     }
                   6890:     if (wantarray) {
                   6891: 	return ($e,$f);
                   6892:     } else {
                   6893: 	my $g;
                   6894: 	{
                   6895: 	    use integer;
                   6896: 	    $g=($e+$f);
                   6897: 	    if ($_64bit) {
                   6898: 		$g=(($g<<32)>>32);
                   6899: 	    }
                   6900: 	}
                   6901: 	return $g;
                   6902:     }
                   6903: }
                   6904: 
1.368     albertel 6905: sub latest_rnd_algorithm_id {
1.675     albertel 6906:     return '64bit5';
1.366     albertel 6907: }
1.32      www      6908: 
1.503     albertel 6909: sub get_rand_alg {
                   6910:     my ($courseid)=@_;
1.790     albertel 6911:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 6912:     if ($courseid) {
1.620     albertel 6913: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 6914:     }
                   6915:     return &latest_rnd_algorithm_id();
                   6916: }
                   6917: 
1.562     albertel 6918: sub validCODE {
                   6919:     my ($CODE)=@_;
                   6920:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   6921:     return 0;
                   6922: }
                   6923: 
1.491     albertel 6924: sub getCODE {
1.620     albertel 6925:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 6926:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   6927: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   6928: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 6929: 	return $Apache::lonhomework::history{'resource.CODE'};
                   6930:     }
                   6931:     return undef;
                   6932: }
                   6933: 
1.31      www      6934: sub rndseed {
1.155     albertel 6935:     my ($symb,$courseid,$domain,$username)=@_;
1.790     albertel 6936:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.155     albertel 6937:     if (!$symb) {
1.366     albertel 6938: 	unless ($symb=$wsymb) { return time; }
                   6939:     }
                   6940:     if (!$courseid) { $courseid=$wcourseid; }
                   6941:     if (!$domain) { $domain=$wdomain; }
                   6942:     if (!$username) { $username=$wusername }
1.503     albertel 6943:     my $which=&get_rand_alg();
1.803     albertel 6944: 
1.491     albertel 6945:     if (defined(&getCODE())) {
1.675     albertel 6946: 	if ($which eq '64bit5') {
                   6947: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   6948: 	} elsif ($which eq '64bit4') {
1.575     albertel 6949: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   6950: 	} else {
                   6951: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   6952: 	}
1.675     albertel 6953:     } elsif ($which eq '64bit5') {
                   6954: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 6955:     } elsif ($which eq '64bit4') {
                   6956: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 6957:     } elsif ($which eq '64bit3') {
                   6958: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 6959:     } elsif ($which eq '64bit2') {
                   6960: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 6961:     } elsif ($which eq '64bit') {
                   6962: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   6963:     }
                   6964:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   6965: }
                   6966: 
                   6967: sub rndseed_32bit {
                   6968:     my ($symb,$courseid,$domain,$username)=@_;
                   6969:     {
                   6970: 	use integer;
                   6971: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   6972: 	my $symbseed=numval($symb) << 22;
                   6973: 	my $namechck=unpack("%32C*",$username) << 17;
                   6974: 	my $nameseed=numval($username) << 12;
                   6975: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   6976: 	my $courseseed=unpack("%32C*",$courseid);
                   6977: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 6978: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6979: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 6980: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 6981: 	return $num;
                   6982:     }
                   6983: }
                   6984: 
                   6985: sub rndseed_64bit {
                   6986:     my ($symb,$courseid,$domain,$username)=@_;
                   6987:     {
                   6988: 	use integer;
                   6989: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   6990: 	my $symbseed=numval($symb) << 10;
                   6991: 	my $namechck=unpack("%32S*",$username);
                   6992: 	
                   6993: 	my $nameseed=numval($username) << 21;
                   6994: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   6995: 	my $courseseed=unpack("%32S*",$courseid);
                   6996: 	
                   6997: 	my $num1=$symbchck+$symbseed+$namechck;
                   6998: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6999: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7000: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 7001: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 7002: 	return "$num1,$num2";
1.155     albertel 7003:     }
1.366     albertel 7004: }
                   7005: 
1.443     albertel 7006: sub rndseed_64bit2 {
                   7007:     my ($symb,$courseid,$domain,$username)=@_;
                   7008:     {
                   7009: 	use integer;
                   7010: 	# strings need to be an even # of cahracters long, it it is odd the
                   7011:         # last characters gets thrown away
                   7012: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7013: 	my $symbseed=numval($symb) << 10;
                   7014: 	my $namechck=unpack("%32S*",$username.' ');
                   7015: 	
                   7016: 	my $nameseed=numval($username) << 21;
1.501     albertel 7017: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7018: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7019: 	
                   7020: 	my $num1=$symbchck+$symbseed+$namechck;
                   7021: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7022: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7023: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 7024: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 7025: 	return "$num1,$num2";
                   7026:     }
                   7027: }
                   7028: 
                   7029: sub rndseed_64bit3 {
                   7030:     my ($symb,$courseid,$domain,$username)=@_;
                   7031:     {
                   7032: 	use integer;
                   7033: 	# strings need to be an even # of cahracters long, it it is odd the
                   7034:         # last characters gets thrown away
                   7035: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7036: 	my $symbseed=numval2($symb) << 10;
                   7037: 	my $namechck=unpack("%32S*",$username.' ');
                   7038: 	
                   7039: 	my $nameseed=numval2($username) << 21;
1.443     albertel 7040: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7041: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7042: 	
                   7043: 	my $num1=$symbchck+$symbseed+$namechck;
                   7044: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7045: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7046: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 7047: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   7048: 	
1.503     albertel 7049: 	return "$num1:$num2";
1.443     albertel 7050:     }
                   7051: }
                   7052: 
1.575     albertel 7053: sub rndseed_64bit4 {
                   7054:     my ($symb,$courseid,$domain,$username)=@_;
                   7055:     {
                   7056: 	use integer;
                   7057: 	# strings need to be an even # of cahracters long, it it is odd the
                   7058:         # last characters gets thrown away
                   7059: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7060: 	my $symbseed=numval3($symb) << 10;
                   7061: 	my $namechck=unpack("%32S*",$username.' ');
                   7062: 	
                   7063: 	my $nameseed=numval3($username) << 21;
                   7064: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7065: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7066: 	
                   7067: 	my $num1=$symbchck+$symbseed+$namechck;
                   7068: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7069: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7070: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 7071: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   7072: 	
                   7073: 	return "$num1:$num2";
                   7074:     }
                   7075: }
                   7076: 
1.675     albertel 7077: sub rndseed_64bit5 {
                   7078:     my ($symb,$courseid,$domain,$username)=@_;
                   7079:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   7080:     return "$num1:$num2";
                   7081: }
                   7082: 
1.366     albertel 7083: sub rndseed_CODE_64bit {
                   7084:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 7085:     {
1.366     albertel 7086: 	use integer;
1.443     albertel 7087: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 7088: 	my $symbseed=numval2($symb);
1.491     albertel 7089: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   7090: 	my $CODEseed=numval(&getCODE());
1.443     albertel 7091: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 7092: 	my $num1=$symbseed+$CODEchck;
                   7093: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 7094: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   7095: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 7096: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   7097: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 7098: 	return "$num1:$num2";
1.366     albertel 7099:     }
                   7100: }
                   7101: 
1.575     albertel 7102: sub rndseed_CODE_64bit4 {
                   7103:     my ($symb,$courseid,$domain,$username)=@_;
                   7104:     {
                   7105: 	use integer;
                   7106: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   7107: 	my $symbseed=numval3($symb);
                   7108: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   7109: 	my $CODEseed=numval3(&getCODE());
                   7110: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7111: 	my $num1=$symbseed+$CODEchck;
                   7112: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 7113: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   7114: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 7115: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   7116: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   7117: 	return "$num1:$num2";
                   7118:     }
                   7119: }
                   7120: 
1.675     albertel 7121: sub rndseed_CODE_64bit5 {
                   7122:     my ($symb,$courseid,$domain,$username)=@_;
                   7123:     my $code = &getCODE();
                   7124:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   7125:     return "$num1:$num2";
                   7126: }
                   7127: 
1.366     albertel 7128: sub setup_random_from_rndseed {
                   7129:     my ($rndseed)=@_;
1.503     albertel 7130:     if ($rndseed =~/([,:])/) {
                   7131: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 7132: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   7133:     } else {
                   7134: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 7135:     }
1.36      albertel 7136: }
                   7137: 
1.474     albertel 7138: sub latest_receipt_algorithm_id {
1.835     albertel 7139:     return 'receipt3';
1.474     albertel 7140: }
                   7141: 
1.480     www      7142: sub recunique {
                   7143:     my $fucourseid=shift;
                   7144:     my $unique;
1.835     albertel 7145:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   7146: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 7147: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      7148:     } else {
                   7149: 	$unique=$perlvar{'lonReceipt'};
                   7150:     }
                   7151:     return unpack("%32C*",$unique);
                   7152: }
                   7153: 
                   7154: sub recprefix {
                   7155:     my $fucourseid=shift;
                   7156:     my $prefix;
1.835     albertel 7157:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   7158: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 7159: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      7160:     } else {
                   7161: 	$prefix=$perlvar{'lonHostID'};
                   7162:     }
                   7163:     return unpack("%32C*",$prefix);
                   7164: }
                   7165: 
1.76      www      7166: sub ireceipt {
1.474     albertel 7167:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 7168: 
                   7169:     my $return =&recprefix($fucourseid).'-';
                   7170: 
                   7171:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   7172: 	$env{'request.state'} eq 'construct') {
                   7173: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   7174: 	return $return;
                   7175:     }
                   7176: 
1.76      www      7177:     my $cuname=unpack("%32C*",$funame);
                   7178:     my $cudom=unpack("%32C*",$fudom);
                   7179:     my $cucourseid=unpack("%32C*",$fucourseid);
                   7180:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      7181:     my $cunique=&recunique($fucourseid);
1.474     albertel 7182:     my $cpart=unpack("%32S*",$part);
1.835     albertel 7183:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   7184: 
1.790     albertel 7185: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 7186: 			       
                   7187: 	$return.= ($cunique%$cuname+
                   7188: 		   $cunique%$cudom+
                   7189: 		   $cusymb%$cuname+
                   7190: 		   $cusymb%$cudom+
                   7191: 		   $cucourseid%$cuname+
                   7192: 		   $cucourseid%$cudom+
                   7193: 		   $cpart%$cuname+
                   7194: 		   $cpart%$cudom);
                   7195:     } else {
                   7196: 	$return.= ($cunique%$cuname+
                   7197: 		   $cunique%$cudom+
                   7198: 		   $cusymb%$cuname+
                   7199: 		   $cusymb%$cudom+
                   7200: 		   $cucourseid%$cuname+
                   7201: 		   $cucourseid%$cudom);
                   7202:     }
                   7203:     return $return;
1.76      www      7204: }
                   7205: 
                   7206: sub receipt {
1.474     albertel 7207:     my ($part)=@_;
1.790     albertel 7208:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 7209:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      7210: }
1.260     ng       7211: 
1.790     albertel 7212: sub whichuser {
                   7213:     my ($passedsymb)=@_;
                   7214:     my ($symb,$courseid,$domain,$name,$publicuser);
                   7215:     if (defined($env{'form.grade_symb'})) {
                   7216: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   7217: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   7218: 	if (!$allowed &&
                   7219: 	    exists($env{'request.course.sec'}) &&
                   7220: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   7221: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   7222: 			      '/'.$env{'request.course.sec'});
                   7223: 	}
                   7224: 	if ($allowed) {
                   7225: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   7226: 	    $courseid=$tmp_courseid;
                   7227: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   7228: 	    ($name)=&get_env_multiple('form.grade_username');
                   7229: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   7230: 	}
                   7231:     }
                   7232:     if (!$passedsymb) {
                   7233: 	$symb=&symbread();
                   7234:     } else {
                   7235: 	$symb=$passedsymb;
                   7236:     }
                   7237:     $courseid=$env{'request.course.id'};
                   7238:     $domain=$env{'user.domain'};
                   7239:     $name=$env{'user.name'};
                   7240:     if ($name eq 'public' && $domain eq 'public') {
                   7241: 	if (!defined($env{'form.username'})) {
                   7242: 	    $env{'form.username'}.=time.rand(10000000);
                   7243: 	}
                   7244: 	$name.=$env{'form.username'};
                   7245:     }
                   7246:     return ($symb,$courseid,$domain,$name,$publicuser);
                   7247: 
                   7248: }
                   7249: 
1.36      albertel 7250: # ------------------------------------------------------------ Serves up a file
1.472     albertel 7251: # returns either the contents of the file or 
                   7252: # -1 if the file doesn't exist
1.481     raeburn  7253: #
                   7254: # if the target is a file that was uploaded via DOCS, 
                   7255: # a check will be made to see if a current copy exists on the local server,
                   7256: # if it does this will be served, otherwise a copy will be retrieved from
                   7257: # the home server for the course and stored in /home/httpd/html/userfiles on
                   7258: # the local server.   
1.472     albertel 7259: 
1.36      albertel 7260: sub getfile {
1.538     albertel 7261:     my ($file) = @_;
1.609     banghart 7262:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 7263:     &repcopy($file);
                   7264:     return &readfile($file);
                   7265: }
                   7266: 
                   7267: sub repcopy_userfile {
                   7268:     my ($file)=@_;
1.609     banghart 7269:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 7270:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 7271:     my ($cdom,$cnum,$filename) = 
1.811     albertel 7272: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 7273:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   7274:     if (-e "$file") {
1.828     www      7275: # we already have a local copy, check it out
1.538     albertel 7276: 	my @fileinfo = stat($file);
1.828     www      7277: 	my $rtncode;
                   7278: 	my $info;
1.538     albertel 7279: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 7280: 	if ($lwpresp ne 'ok') {
1.828     www      7281: # there is no such file anymore, even though we had a local copy
1.482     albertel 7282: 	    if ($rtncode eq '404') {
1.538     albertel 7283: 		unlink($file);
1.482     albertel 7284: 	    }
                   7285: 	    return -1;
                   7286: 	}
                   7287: 	if ($info < $fileinfo[9]) {
1.828     www      7288: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  7289: 	    return 'ok';
1.828     www      7290: 	} else {
                   7291: # the file is outdated, get rid of it
                   7292: 	    unlink($file);
1.482     albertel 7293: 	}
1.828     www      7294:     }
                   7295: # one way or the other, at this point, we don't have the file
                   7296: # construct the correct path for the file
                   7297:     my @parts = ($cdom,$cnum); 
                   7298:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   7299: 	push @parts, split(/\//,$1);
                   7300:     }
                   7301:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   7302:     foreach my $part (@parts) {
                   7303: 	$path .= '/'.$part;
                   7304: 	if (!-e $path) {
                   7305: 	    mkdir($path,0770);
1.482     albertel 7306: 	}
                   7307:     }
1.828     www      7308: # now the path exists for sure
                   7309: # get a user agent
                   7310:     my $ua=new LWP::UserAgent;
                   7311:     my $transferfile=$file.'.in.transfer';
                   7312: # FIXME: this should flock
                   7313:     if (-e $transferfile) { return 'ok'; }
                   7314:     my $request;
                   7315:     $uri=~s/^\///;
1.838     albertel 7316:     $request=new HTTP::Request('GET','http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri);
1.828     www      7317:     my $response=$ua->request($request,$transferfile);
                   7318: # did it work?
                   7319:     if ($response->is_error()) {
                   7320: 	unlink($transferfile);
                   7321: 	&logthis("Userfile repcopy failed for $uri");
                   7322: 	return -1;
                   7323:     }
                   7324: # worked, rename the transfer file
                   7325:     rename($transferfile,$file);
1.607     raeburn  7326:     return 'ok';
1.481     raeburn  7327: }
                   7328: 
1.517     albertel 7329: sub tokenwrapper {
                   7330:     my $uri=shift;
1.552     albertel 7331:     $uri=~s|^http\://([^/]+)||;
                   7332:     $uri=~s|^/||;
1.620     albertel 7333:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 7334:     my $token=$1;
1.552     albertel 7335:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   7336:     if ($udom && $uname && $file) {
                   7337: 	$file=~s|(\?\.*)*$||;
1.620     albertel 7338:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
1.838     albertel 7339:         return 'http://'.&hostname(&homeserver($uname,$udom)).'/'.$uri.
1.517     albertel 7340:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   7341:                                '&tokenissued='.$perlvar{'lonHostID'};
                   7342:     } else {
                   7343:         return '/adm/notfound.html';
                   7344:     }
                   7345: }
                   7346: 
1.828     www      7347: # call with reqtype HEAD: get last modification time
                   7348: # call with reqtype GET: get the file contents
                   7349: # Do not call this with reqtype GET for large files! It loads everything into memory
                   7350: #
1.481     raeburn  7351: sub getuploaded {
                   7352:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   7353:     $uri=~s/^\///;
1.838     albertel 7354:     $uri = 'http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri;
1.481     raeburn  7355:     my $ua=new LWP::UserAgent;
                   7356:     my $request=new HTTP::Request($reqtype,$uri);
                   7357:     my $response=$ua->request($request);
                   7358:     $$rtncode = $response->code;
1.482     albertel 7359:     if (! $response->is_success()) {
                   7360: 	return 'failed';
                   7361:     }      
                   7362:     if ($reqtype eq 'HEAD') {
1.486     www      7363: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 7364:     } elsif ($reqtype eq 'GET') {
                   7365: 	$$info = $response->content;
1.472     albertel 7366:     }
1.482     albertel 7367:     return 'ok';
1.36      albertel 7368: }
                   7369: 
1.481     raeburn  7370: sub readfile {
                   7371:     my $file = shift;
                   7372:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   7373:     my $fh;
                   7374:     open($fh,"<$file");
                   7375:     my $a='';
1.800     albertel 7376:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  7377:     return $a;
                   7378: }
                   7379: 
1.36      albertel 7380: sub filelocation {
1.590     banghart 7381:     my ($dir,$file) = @_;
                   7382:     my $location;
                   7383:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 7384: 
                   7385:     if ($file =~ m-^/adm/-) {
                   7386: 	$file=~s-^/adm/wrapper/-/-;
                   7387: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   7388:     }
1.590     banghart 7389:     if ($file=~m:^/~:) { # is a contruction space reference
                   7390:         $location = $file;
                   7391:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 7392:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 7393: 	# is a correct contruction space reference
                   7394:         $location = $file;
1.609     banghart 7395:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 7396:         my ($udom,$uname,$filename)=
1.811     albertel 7397:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 7398:         my $home=&homeserver($uname,$udom);
                   7399:         my $is_me=0;
                   7400:         my @ids=&current_machine_ids();
                   7401:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   7402:         if ($is_me) {
1.740     www      7403:   	    $location=&propath($udom,$uname).
1.590     banghart 7404:   	      '/userfiles/'.$filename;
                   7405:         } else {
                   7406:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   7407:   	      $udom.'/'.$uname.'/'.$filename;
                   7408:         }
                   7409:     } else {
                   7410:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   7411:         $file=~s:^/res/:/:;
                   7412:         if ( !( $file =~ m:^/:) ) {
                   7413:             $location = $dir. '/'.$file;
                   7414:         } else {
                   7415:             $location = '/home/httpd/html/res'.$file;
                   7416:         }
1.59      albertel 7417:     }
1.590     banghart 7418:     $location=~s://+:/:g; # remove duplicate /
                   7419:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
                   7420:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   7421:     return $location;
1.46      www      7422: }
1.36      albertel 7423: 
1.46      www      7424: sub hreflocation {
                   7425:     my ($dir,$file)=@_;
1.460     albertel 7426:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666     albertel 7427: 	$file=filelocation($dir,$file);
1.700     albertel 7428:     } elsif ($file=~m-^/adm/-) {
                   7429: 	$file=~s-^/adm/wrapper/-/-;
                   7430: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 7431:     }
                   7432:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   7433: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 7434:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   7435: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 7436:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 7437: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 7438: 	    -/uploaded/$1/$2/-x;
1.46      www      7439:     }
1.462     albertel 7440:     return $file;
1.465     albertel 7441: }
                   7442: 
                   7443: sub current_machine_domains {
1.853     albertel 7444:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   7445: }
                   7446: 
                   7447: sub machine_domains {
                   7448:     my ($hostname) = @_;
1.465     albertel 7449:     my @domains;
1.838     albertel 7450:     my %hostname = &all_hostnames();
1.465     albertel 7451:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  7452: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 7453: 	if ($hostname eq $name) {
1.844     albertel 7454: 	    push(@domains,&host_domain($id));
1.465     albertel 7455: 	}
                   7456:     }
                   7457:     return @domains;
                   7458: }
                   7459: 
                   7460: sub current_machine_ids {
1.853     albertel 7461:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   7462: }
                   7463: 
                   7464: sub machine_ids {
                   7465:     my ($hostname) = @_;
                   7466:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 7467:     my @ids;
1.838     albertel 7468:     my %hostname = &all_hostnames();
1.465     albertel 7469:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  7470: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 7471: 	if ($hostname eq $name) {
                   7472: 	    push(@ids,$id);
                   7473: 	}
                   7474:     }
                   7475:     return @ids;
1.31      www      7476: }
                   7477: 
1.824     raeburn  7478: sub additional_machine_domains {
                   7479:     my @domains;
                   7480:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   7481:     while( my $line = <$fh>) {
                   7482:         $line =~ s/\s//g;
                   7483:         push(@domains,$line);
                   7484:     }
                   7485:     return @domains;
                   7486: }
                   7487: 
                   7488: sub default_login_domain {
                   7489:     my $domain = $perlvar{'lonDefDomain'};
                   7490:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   7491:     foreach my $posdom (&current_machine_domains(),
                   7492:                         &additional_machine_domains()) {
                   7493:         if (lc($posdom) eq lc($testdomain)) {
                   7494:             $domain=$posdom;
                   7495:             last;
                   7496:         }
                   7497:     }
                   7498:     return $domain;
                   7499: }
                   7500: 
1.31      www      7501: # ------------------------------------------------------------- Declutters URLs
                   7502: 
                   7503: sub declutter {
                   7504:     my $thisfn=shift;
1.569     albertel 7505:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 7506:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      7507:     $thisfn=~s/^\///;
1.697     albertel 7508:     $thisfn=~s|^adm/wrapper/||;
                   7509:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      7510:     $thisfn=~s/^res\///;
1.235     www      7511:     $thisfn=~s/\?.+$//;
1.268     www      7512:     return $thisfn;
                   7513: }
                   7514: 
                   7515: # ------------------------------------------------------------- Clutter up URLs
                   7516: 
                   7517: sub clutter {
                   7518:     my $thisfn='/'.&declutter(shift);
1.609     banghart 7519:     unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) { 
1.270     www      7520:        $thisfn='/res'.$thisfn; 
                   7521:     }
1.694     albertel 7522:     if ($thisfn !~m|/adm|) {
1.695     albertel 7523: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 7524: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 7525: 	} else {
                   7526: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   7527: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 7528: 	    if ($embstyle eq 'ssi'
                   7529: 		|| ($embstyle eq 'hdn')
                   7530: 		|| ($embstyle eq 'rat')
                   7531: 		|| ($embstyle eq 'prv')
                   7532: 		|| ($embstyle eq 'ign')) {
                   7533: 		#do nothing with these
                   7534: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 7535: 		|| ($embstyle eq 'emb')
                   7536: 		|| ($embstyle eq 'wrp')) {
                   7537: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 7538: 	    } elsif ($embstyle eq 'unk'
                   7539: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 7540: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 7541: 	    } else {
1.718     www      7542: #		&logthis("Got a blank emb style");
1.695     albertel 7543: 	    }
1.694     albertel 7544: 	}
                   7545:     }
1.31      www      7546:     return $thisfn;
1.12      www      7547: }
                   7548: 
1.787     albertel 7549: sub clutter_with_no_wrapper {
                   7550:     my $uri = &clutter(shift);
                   7551:     if ($uri =~ m-^/adm/-) {
                   7552: 	$uri =~ s-^/adm/wrapper/-/-;
                   7553: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   7554:     }
                   7555:     return $uri;
                   7556: }
                   7557: 
1.557     albertel 7558: sub freeze_escape {
                   7559:     my ($value)=@_;
                   7560:     if (ref($value)) {
                   7561: 	$value=&nfreeze($value);
                   7562: 	return '__FROZEN__'.&escape($value);
                   7563:     }
                   7564:     return &escape($value);
                   7565: }
                   7566: 
1.11      www      7567: 
1.557     albertel 7568: sub thaw_unescape {
                   7569:     my ($value)=@_;
                   7570:     if ($value =~ /^__FROZEN__/) {
                   7571: 	substr($value,0,10,undef);
                   7572: 	$value=&unescape($value);
                   7573: 	return &thaw($value);
                   7574:     }
                   7575:     return &unescape($value);
                   7576: }
                   7577: 
1.436     albertel 7578: sub correct_line_ends {
                   7579:     my ($result)=@_;
                   7580:     $$result =~s/\r\n/\n/mg;
                   7581:     $$result =~s/\r/\n/mg;
1.415     albertel 7582: }
1.1       albertel 7583: # ================================================================ Main Program
                   7584: 
1.184     www      7585: sub goodbye {
1.204     albertel 7586:    &logthis("Starting Shut down");
1.443     albertel 7587: #not converted to using infrastruture and probably shouldn't be
1.599     albertel 7588:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&freeze(\%badServerCache))));
1.443     albertel 7589: #converted
1.599     albertel 7590: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
                   7591:    &logthis(sprintf("%-20s is %s",'%homecache',length(&freeze(\%homecache))));
                   7592: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&freeze(\%titlecache))));
                   7593: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&freeze(\%courseresdatacache))));
1.425     albertel 7594: #1.1 only
1.599     albertel 7595: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&freeze(\%userresdatacache))));
                   7596: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&freeze(\%getsectioncache))));
                   7597: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&freeze(\%courseresversioncache))));
                   7598: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&freeze(\%resversioncache))));
                   7599:    &logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
                   7600:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   7601:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      7602:    &flushcourselogs();
                   7603:    &logthis("Shutting down");
                   7604: }
                   7605: 
1.179     www      7606: BEGIN {
1.856     albertel 7607: 
1.228     harris41 7608: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
1.195     www      7609:     unless ($readit) {
1.217     harris41 7610: {
1.781     raeburn  7611:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   7612:     %perlvar = (%perlvar,%{$configvars});
1.227     harris41 7613: }
1.1       albertel 7614: 
1.852     albertel 7615: sub get_dns {
                   7616:     my ($url,$func) = @_;
                   7617:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   7618:     foreach my $dns (<$config>) {
                   7619: 	next if ($dns !~ /^\^(\S*)/x);
                   7620: 	$dns = $1;
                   7621: 	my $ua=new LWP::UserAgent;
                   7622: 	my $request=new HTTP::Request('GET',"http://$dns$url");
                   7623: 	my $response=$ua->request($request);
                   7624: 	next if ($response->is_error());
                   7625: 	my @content = split("\n",$response->content);
                   7626: 	&$func(\@content);
                   7627:     }
                   7628:     close($config);
                   7629: }
1.327     albertel 7630: # ------------------------------------------------------------ Read domain file
                   7631: {
1.852     albertel 7632:     my $loaded;
1.846     albertel 7633:     my %domain;
                   7634: 
1.852     albertel 7635:     sub parse_domain_tab {
                   7636: 	my ($lines) = @_;
                   7637: 	foreach my $line (@$lines) {
                   7638: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      7639: 
1.846     albertel 7640: 	    chomp($line);
1.852     albertel 7641: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 7642: 	    my %this_domain;
                   7643: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   7644: 			       'lang_def', 'city', 'longi', 'lati',
                   7645: 			       'primary') {
                   7646: 		$this_domain{$field} = shift(@elements);
                   7647: 	    }
                   7648: 	    $domain{$name} = \%this_domain;
1.852     albertel 7649: 	    &logthis("Domain.tab: $name ".$domain{$name}{'description'} );
                   7650: 	}
                   7651:     }
                   7652:     
                   7653:     sub load_domain_tab {
                   7654: 	&get_dns('/adm/dns/domain',\&parse_domain_tab);
                   7655: 	my $fh;
                   7656: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   7657: 	    my @lines = <$fh>;
                   7658: 	    &parse_domain_tab(\@lines);
1.448     albertel 7659: 	}
1.852     albertel 7660: 	close($fh);
                   7661: 	$loaded = 1;
1.327     albertel 7662:     }
1.846     albertel 7663: 
                   7664:     sub domain {
1.852     albertel 7665: 	&load_domain_tab() if (!$loaded);
                   7666: 
1.846     albertel 7667: 	my ($name,$what) = @_;
                   7668: 	return if ( !exists($domain{$name}) );
                   7669: 
                   7670: 	if (!$what) {
                   7671: 	    return $domain{$name}{'description'};
                   7672: 	}
                   7673: 	return $domain{$name}{$what};
                   7674:     }
1.327     albertel 7675: }
                   7676: 
                   7677: 
1.1       albertel 7678: # ------------------------------------------------------------- Read hosts file
                   7679: {
1.838     albertel 7680:     my %hostname;
1.844     albertel 7681:     my %hostdom;
1.845     albertel 7682:     my %libserv;
1.852     albertel 7683:     my $loaded;
                   7684: 
                   7685:     sub parse_hosts_tab {
                   7686: 	my ($file) = @_;
                   7687: 	foreach my $configline (@$file) {
                   7688: 	    next if ($configline =~ /^(\#|\s*$ )/x);
                   7689: 	    next if ($configline =~ /^\^/);
                   7690: 	    chomp($configline);
                   7691: 	    my ($id,$domain,$role,$name)=split(/:/,$configline);
                   7692: 	    $name=~s/\s//g;
                   7693: 	    if ($id && $domain && $role && $name) {
                   7694: 		$hostname{$id}=$name;
                   7695: 		$hostdom{$id}=$domain;
                   7696: 		if ($role eq 'library') { $libserv{$id}=$name; }
                   7697: 	    }
                   7698: 	    &logthis("Hosts.tab: $name ".$id );
                   7699: 	}
                   7700:     }
1.1       albertel 7701: 
1.852     albertel 7702:     sub load_hosts_tab {
                   7703: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab);
                   7704: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   7705: 	my @config = <$config>;
                   7706: 	&parse_hosts_tab(\@config);
                   7707: 	close($config);
                   7708: 	$loaded=1;
1.1       albertel 7709:     }
1.852     albertel 7710: 
1.619     albertel 7711:     # FIXME: dev server don't want this, production servers _do_ want this
1.654     albertel 7712:     #&get_iphost();
1.838     albertel 7713: 
                   7714:     sub hostname {
1.852     albertel 7715: 	&load_hosts_tab() if (!$loaded);
                   7716: 
1.838     albertel 7717: 	my ($lonid) = @_;
                   7718: 	return $hostname{$lonid};
                   7719:     }
1.845     albertel 7720: 
1.838     albertel 7721:     sub all_hostnames {
1.852     albertel 7722: 	&load_hosts_tab() if (!$loaded);
                   7723: 
1.838     albertel 7724: 	return %hostname;
                   7725:     }
1.845     albertel 7726: 
                   7727:     sub is_library {
1.852     albertel 7728: 	&load_hosts_tab() if (!$loaded);
                   7729: 
1.845     albertel 7730: 	return exists($libserv{$_[0]});
                   7731:     }
                   7732: 
                   7733:     sub all_library {
1.852     albertel 7734: 	&load_hosts_tab() if (!$loaded);
                   7735: 
1.845     albertel 7736: 	return %libserv;
                   7737:     }
                   7738: 
1.841     albertel 7739:     sub get_servers {
1.852     albertel 7740: 	&load_hosts_tab() if (!$loaded);
                   7741: 
1.841     albertel 7742: 	my ($domain,$type) = @_;
                   7743: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   7744: 	                                          : %hostname;
                   7745: 	my %result;
1.842     albertel 7746: 	if (ref($domain) eq 'ARRAY') {
                   7747: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 7748: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 7749: 		    $result{$host} = $hostname;
                   7750: 		}
                   7751: 	    }
                   7752: 	} else {
                   7753: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   7754: 		if ($hostdom{$host} eq $domain) {
                   7755: 		    $result{$host} = $hostname;
                   7756: 		}
1.841     albertel 7757: 	    }
                   7758: 	}
                   7759: 	return %result;
                   7760:     }
1.845     albertel 7761: 
1.844     albertel 7762:     sub host_domain {
1.852     albertel 7763: 	&load_hosts_tab() if (!$loaded);
                   7764: 
1.844     albertel 7765: 	my ($lonid) = @_;
                   7766: 	return $hostdom{$lonid};
                   7767:     }
                   7768: 
1.841     albertel 7769:     sub all_domains {
1.852     albertel 7770: 	&load_hosts_tab() if (!$loaded);
                   7771: 
1.841     albertel 7772: 	my %seen;
                   7773: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   7774: 	return @uniq;
                   7775:     }
1.1       albertel 7776: }
                   7777: 
1.847     albertel 7778: { 
                   7779:     my %iphost;
1.856     albertel 7780:     my %name_to_ip;
                   7781:     my %lonid_to_ip;
1.847     albertel 7782:     sub get_hosts_from_ip {
                   7783: 	my ($ip) = @_;
                   7784: 	my %iphosts = &get_iphost();
                   7785: 	if (ref($iphosts{$ip})) {
                   7786: 	    return @{$iphosts{$ip}};
                   7787: 	}
                   7788: 	return;
1.839     albertel 7789:     }
1.856     albertel 7790: 
                   7791:     sub get_host_ip {
                   7792: 	my ($lonid) = @_;
                   7793: 	if (exists($lonid_to_ip{$lonid})) {
                   7794: 	    return $lonid_to_ip{$lonid};
                   7795: 	}
                   7796: 	my $name=&hostname($lonid);
                   7797:    	my $ip = gethostbyname($name);
                   7798: 	return if (!$ip || length($ip) ne 4);
                   7799: 	$ip=inet_ntoa($ip);
                   7800: 	$name_to_ip{$name}   = $ip;
                   7801: 	$lonid_to_ip{$lonid} = $ip;
                   7802: 	return $ip;
                   7803:     }
1.847     albertel 7804:     
                   7805:     sub get_iphost {
                   7806: 	if (%iphost) { return %iphost; }
                   7807: 	my %hostname = &all_hostnames();
                   7808: 	foreach my $id (keys(%hostname)) {
                   7809: 	    my $name=$hostname{$id};
                   7810: 	    my $ip;
                   7811: 	    if (!exists($name_to_ip{$name})) {
                   7812: 		$ip = gethostbyname($name);
                   7813: 		if (!$ip || length($ip) ne 4) {
                   7814: 		    &logthis("Skipping host $id name $name no IP found");
                   7815: 		    next;
                   7816: 		}
                   7817: 		$ip=inet_ntoa($ip);
                   7818: 		$name_to_ip{$name} = $ip;
                   7819: 	    } else {
                   7820: 		$ip = $name_to_ip{$name};
1.653     albertel 7821: 	    }
1.856     albertel 7822: 	    $lonid_to_ip{$id} = $ip;
1.847     albertel 7823: 	    push(@{$iphost{$ip}},$id);
1.598     albertel 7824: 	}
1.847     albertel 7825: 	return %iphost;
1.598     albertel 7826:     }
                   7827: }
                   7828: 
1.1       albertel 7829: # ------------------------------------------------------ Read spare server file
                   7830: {
1.448     albertel 7831:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 7832: 
                   7833:     while (my $configline=<$config>) {
                   7834:        chomp($configline);
1.284     matthew  7835:        if ($configline) {
1.784     albertel 7836: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 7837: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 7838: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 7839:        }
                   7840:     }
1.448     albertel 7841:     close($config);
1.1       albertel 7842: }
1.11      www      7843: # ------------------------------------------------------------ Read permissions
                   7844: {
1.448     albertel 7845:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      7846: 
                   7847:     while (my $configline=<$config>) {
1.448     albertel 7848: 	chomp($configline);
                   7849: 	if ($configline) {
                   7850: 	    my ($role,$perm)=split(/ /,$configline);
                   7851: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   7852: 	}
1.11      www      7853:     }
1.448     albertel 7854:     close($config);
1.11      www      7855: }
                   7856: 
                   7857: # -------------------------------------------- Read plain texts for permissions
                   7858: {
1.448     albertel 7859:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      7860: 
                   7861:     while (my $configline=<$config>) {
1.448     albertel 7862: 	chomp($configline);
                   7863: 	if ($configline) {
1.742     raeburn  7864: 	    my ($short,@plain)=split(/:/,$configline);
                   7865:             %{$prp{$short}} = ();
                   7866: 	    if (@plain > 0) {
                   7867:                 $prp{$short}{'std'} = $plain[0];
                   7868:                 for (my $i=1; $i<@plain; $i++) {
                   7869:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   7870:                 }
                   7871:             }
1.448     albertel 7872: 	}
1.135     www      7873:     }
1.448     albertel 7874:     close($config);
1.135     www      7875: }
                   7876: 
                   7877: # ---------------------------------------------------------- Read package table
                   7878: {
1.448     albertel 7879:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      7880: 
                   7881:     while (my $configline=<$config>) {
1.483     albertel 7882: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 7883: 	chomp($configline);
                   7884: 	my ($short,$plain)=split(/:/,$configline);
                   7885: 	my ($pack,$name)=split(/\&/,$short);
                   7886: 	if ($plain ne '') {
                   7887: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   7888: 	    $packagetab{$short}=$plain; 
                   7889: 	}
1.11      www      7890:     }
1.448     albertel 7891:     close($config);
1.329     matthew  7892: }
                   7893: 
                   7894: # ------------- set up temporary directory
                   7895: {
                   7896:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   7897: 
1.11      www      7898: }
                   7899: 
1.794     albertel 7900: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   7901: 				'compress_threshold'=> 20_000,
                   7902:  			        });
1.185     www      7903: 
1.281     www      7904: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      7905: $dumpcount=0;
1.22      www      7906: 
1.163     harris41 7907: &logtouch();
1.672     albertel 7908: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      7909: $readit=1;
1.564     albertel 7910:     {
                   7911: 	use integer;
                   7912: 	my $test=(2**32)+1;
1.568     albertel 7913: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 7914: 	&logthis(" Detected 64bit platform ($_64bit)");
                   7915:     }
1.195     www      7916: }
1.1       albertel 7917: }
1.179     www      7918: 
1.1       albertel 7919: 1;
1.191     harris41 7920: __END__
                   7921: 
1.243     albertel 7922: =pod
                   7923: 
1.191     harris41 7924: =head1 NAME
                   7925: 
1.243     albertel 7926: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 7927: 
                   7928: =head1 SYNOPSIS
                   7929: 
1.243     albertel 7930: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 7931: 
                   7932:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   7933: 
1.243     albertel 7934: Common parameters:
                   7935: 
                   7936: =over 4
                   7937: 
                   7938: =item *
                   7939: 
                   7940: $uname : an internal username (if $cname expecting a course Id specifically)
                   7941: 
                   7942: =item *
                   7943: 
                   7944: $udom : a domain (if $cdom expecting a course's domain specifically)
                   7945: 
                   7946: =item *
                   7947: 
                   7948: $symb : a resource instance identifier
                   7949: 
                   7950: =item *
                   7951: 
                   7952: $namespace : the name of a .db file that contains the data needed or
                   7953: being set.
                   7954: 
                   7955: =back
                   7956: 
1.394     bowersj2 7957: =head1 OVERVIEW
1.191     harris41 7958: 
1.394     bowersj2 7959: lonnet provides subroutines which interact with the
                   7960: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   7961: about classes, users, and resources.
1.243     albertel 7962: 
                   7963: For many of these objects you can also use this to store data about
                   7964: them or modify them in various ways.
1.191     harris41 7965: 
1.394     bowersj2 7966: =head2 Symbs
1.191     harris41 7967: 
1.394     bowersj2 7968: To identify a specific instance of a resource, LON-CAPA uses symbols
                   7969: or "symbs"X<symb>. These identifiers are built from the URL of the
                   7970: map, the resource number of the resource in the map, and the URL of
                   7971: the resource itself. The latter is somewhat redundant, but might help
                   7972: if maps change.
                   7973: 
                   7974: An example is
                   7975: 
                   7976:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   7977: 
                   7978: The respective map entry is
                   7979: 
                   7980:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   7981:   title="Problem 2">
                   7982:  </resource>
                   7983: 
                   7984: Symbs are used by the random number generator, as well as to store and
                   7985: restore data specific to a certain instance of for example a problem.
                   7986: 
                   7987: =head2 Storing And Retrieving Data
                   7988: 
                   7989: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   7990: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   7991: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   7992: is is the non-critical message twin of cstore. These functions are for
                   7993: handlers to store a perl hash to a user's permanent data space in an
                   7994: easy manner, and to retrieve it again on another call. It is expected
                   7995: that a handler would use this once at the beginning to retrieve data,
                   7996: and then again once at the end to send only the new data back.
                   7997: 
                   7998: The data is stored in the user's data directory on the user's
                   7999: homeserver under the ID of the course.
                   8000: 
                   8001: The hash that is returned by restore will have all of the previous
                   8002: value for all of the elements of the hash.
                   8003: 
                   8004: Example:
                   8005: 
                   8006:  #creating a hash
                   8007:  my %hash;
                   8008:  $hash{'foo'}='bar';
                   8009: 
                   8010:  #storing it
                   8011:  &Apache::lonnet::cstore(\%hash);
                   8012: 
                   8013:  #changing a value
                   8014:  $hash{'foo'}='notbar';
                   8015: 
                   8016:  #adding a new value
                   8017:  $hash{'bar'}='foo';
                   8018:  &Apache::lonnet::cstore(\%hash);
                   8019: 
                   8020:  #retrieving the hash
                   8021:  my %history=&Apache::lonnet::restore();
                   8022: 
                   8023:  #print the hash
                   8024:  foreach my $key (sort(keys(%history))) {
                   8025:    print("\%history{$key} = $history{$key}");
                   8026:  }
                   8027: 
                   8028: Will print out:
1.191     harris41 8029: 
1.394     bowersj2 8030:  %history{1:foo} = bar
                   8031:  %history{1:keys} = foo:timestamp
                   8032:  %history{1:timestamp} = 990455579
                   8033:  %history{2:bar} = foo
                   8034:  %history{2:foo} = notbar
                   8035:  %history{2:keys} = foo:bar:timestamp
                   8036:  %history{2:timestamp} = 990455580
                   8037:  %history{bar} = foo
                   8038:  %history{foo} = notbar
                   8039:  %history{timestamp} = 990455580
                   8040:  %history{version} = 2
                   8041: 
                   8042: Note that the special hash entries C<keys>, C<version> and
                   8043: C<timestamp> were added to the hash. C<version> will be equal to the
                   8044: total number of versions of the data that have been stored. The
                   8045: C<timestamp> attribute will be the UNIX time the hash was
                   8046: stored. C<keys> is available in every historical section to list which
                   8047: keys were added or changed at a specific historical revision of a
                   8048: hash.
                   8049: 
                   8050: B<Warning>: do not store the hash that restore returns directly. This
                   8051: will cause a mess since it will restore the historical keys as if the
                   8052: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 8053: 
1.394     bowersj2 8054: Calling convention:
1.191     harris41 8055: 
1.394     bowersj2 8056:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   8057:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 8058: 
1.394     bowersj2 8059: For more detailed information, see lonnet specific documentation.
1.191     harris41 8060: 
1.394     bowersj2 8061: =head1 RETURN MESSAGES
1.191     harris41 8062: 
1.394     bowersj2 8063: =over 4
1.191     harris41 8064: 
1.394     bowersj2 8065: =item * B<con_lost>: unable to contact remote host
1.191     harris41 8066: 
1.394     bowersj2 8067: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   8068: when the connection is brought back up
1.191     harris41 8069: 
1.394     bowersj2 8070: =item * B<con_failed>: unable to contact remote host and unable to save message
                   8071: for later delivery
1.191     harris41 8072: 
1.394     bowersj2 8073: =item * B<error:>: an error a occured, a description of the error follows the :
1.191     harris41 8074: 
1.394     bowersj2 8075: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 8076: that was requested
1.191     harris41 8077: 
1.243     albertel 8078: =back
1.191     harris41 8079: 
1.243     albertel 8080: =head1 PUBLIC SUBROUTINES
1.191     harris41 8081: 
1.243     albertel 8082: =head2 Session Environment Functions
1.191     harris41 8083: 
1.243     albertel 8084: =over 4
1.191     harris41 8085: 
1.394     bowersj2 8086: =item * 
                   8087: X<appenv()>
                   8088: B<appenv(%hash)>: the value of %hash is written to
                   8089: the user envirnoment file, and will be restored for each access this
1.620     albertel 8090: user makes during this session, also modifies the %env for the current
1.394     bowersj2 8091: process
1.191     harris41 8092: 
                   8093: =item *
1.394     bowersj2 8094: X<delenv()>
                   8095: B<delenv($regexp)>: removes all items from the session
                   8096: environment file that matches the regular expression in $regexp. The
1.620     albertel 8097: values are also delted from the current processes %env.
1.191     harris41 8098: 
1.795     albertel 8099: =item * get_env_multiple($name) 
                   8100: 
                   8101: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   8102: values may be defined and end up as an array ref.
                   8103: 
                   8104: returns an array of values
                   8105: 
1.243     albertel 8106: =back
                   8107: 
                   8108: =head2 User Information
1.191     harris41 8109: 
1.243     albertel 8110: =over 4
1.191     harris41 8111: 
                   8112: =item *
1.394     bowersj2 8113: X<queryauthenticate()>
                   8114: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 8115: authentication scheme
                   8116: 
                   8117: =item *
1.394     bowersj2 8118: X<authenticate()>
                   8119: B<authenticate($uname,$upass,$udom)>: try to
                   8120: authenticate user from domain's lib servers (first use the current
                   8121: one). C<$upass> should be the users password.
1.191     harris41 8122: 
                   8123: =item *
1.394     bowersj2 8124: X<homeserver()>
                   8125: B<homeserver($uname,$udom)>: find the server which has
                   8126: the user's directory and files (there must be only one), this caches
                   8127: the answer, and also caches if there is a borken connection.
1.191     harris41 8128: 
                   8129: =item *
1.394     bowersj2 8130: X<idget()>
                   8131: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   8132: (IDs are a unique resource in a domain, there must be only 1 ID per
                   8133: username, and only 1 username per ID in a specific domain) (returns
                   8134: hash: id=>name,id=>name)
1.191     harris41 8135: 
                   8136: =item *
1.394     bowersj2 8137: X<idrget()>
                   8138: B<idrget($udom,@unames)>: find the IDs behind a list of
                   8139: usernames (returns hash: name=>id,name=>id)
1.191     harris41 8140: 
                   8141: =item *
1.394     bowersj2 8142: X<idput()>
                   8143: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 8144: 
                   8145: =item *
1.394     bowersj2 8146: X<rolesinit()>
                   8147: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 8148: 
                   8149: =item *
1.551     albertel 8150: X<getsection()>
                   8151: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 8152: course $cname, return section name/number or '' for "not in course"
                   8153: and '-1' for "no section"
                   8154: 
                   8155: =item *
1.394     bowersj2 8156: X<userenvironment()>
                   8157: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 8158: passed in @what from the requested user's environment, returns a hash
                   8159: 
1.858     raeburn  8160: =item * 
                   8161: X<userlog_query()>
1.859   ! albertel 8162: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
        !          8163: activity.log file. %filters defines filters applied when parsing the
        !          8164: log file. These can be start or end timestamps, or the type of action
        !          8165: - log to look for Login or Logout events, check for Checkin or
        !          8166: Checkout, role for role selection. The response is in the form
        !          8167: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
        !          8168: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  8169: 
1.243     albertel 8170: =back
                   8171: 
                   8172: =head2 User Roles
                   8173: 
                   8174: =over 4
                   8175: 
                   8176: =item *
                   8177: 
1.810     raeburn  8178: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 8179:  F: full access
                   8180:  U,I,K: authentication modes (cxx only)
                   8181:  '': forbidden
                   8182:  1: user needs to choose course
                   8183:  2: browse allowed
1.766     albertel 8184:  A: passphrase authentication needed
1.243     albertel 8185: 
                   8186: =item *
                   8187: 
                   8188: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   8189: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   8190: and course level
                   8191: 
                   8192: =item *
                   8193: 
                   8194: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   8195: explanation of a user role term
                   8196: 
1.832     raeburn  8197: =item *
                   8198: 
1.858     raeburn  8199: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms) :
                   8200: All arguments are optional. Returns a hash of a roles, either for
                   8201: co-author/assistant author roles for a user's Construction Space
                   8202: (default), or if $context is 'user', roles for the user himself,
                   8203: In the hash, keys are set to colon-sparated $uname,$udom,and $role,
                   8204: and value is set to colon-separated start and end times for the role.
                   8205: If no username and domain are specified, will default to current
                   8206: user/domain. Types, roles, and roledoms are references to arrays,
                   8207: of role statuses (active, future or previous), roles 
                   8208: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   8209: to restrict the list of roles reported. If no array ref is 
                   8210: provided for types, will default to return only active roles.
1.834     albertel 8211: 
1.243     albertel 8212: =back
                   8213: 
                   8214: =head2 User Modification
                   8215: 
                   8216: =over 4
                   8217: 
                   8218: =item *
                   8219: 
                   8220: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
                   8221: user for the level given by URL.  Optional start and end dates (leave empty
                   8222: string or zero for "no date")
1.191     harris41 8223: 
                   8224: =item *
                   8225: 
1.243     albertel 8226: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   8227: change a users, password, possible return values are: ok,
                   8228: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   8229: refused
1.191     harris41 8230: 
                   8231: =item *
                   8232: 
1.243     albertel 8233: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 8234: 
                   8235: =item *
                   8236: 
1.243     albertel 8237: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
                   8238: modify user
1.191     harris41 8239: 
                   8240: =item *
                   8241: 
1.286     matthew  8242: modifystudent
                   8243: 
                   8244: modify a students enrollment and identification information.
                   8245: The course id is resolved based on the current users environment.  
                   8246: This means the envoking user must be a course coordinator or otherwise
                   8247: associated with a course.
                   8248: 
1.297     matthew  8249: This call is essentially a wrapper for lonnet::modifyuser and
                   8250: lonnet::modify_student_enrollment
1.286     matthew  8251: 
                   8252: Inputs: 
                   8253: 
                   8254: =over 4
                   8255: 
                   8256: =item B<$udom> Students loncapa domain
                   8257: 
                   8258: =item B<$uname> Students loncapa login name
                   8259: 
                   8260: =item B<$uid> Students id/student number
                   8261: 
                   8262: =item B<$umode> Students authentication mode
                   8263: 
                   8264: =item B<$upass> Students password
                   8265: 
                   8266: =item B<$first> Students first name
                   8267: 
                   8268: =item B<$middle> Students middle name
                   8269: 
                   8270: =item B<$last> Students last name
                   8271: 
                   8272: =item B<$gene> Students generation
                   8273: 
                   8274: =item B<$usec> Students section in course
                   8275: 
                   8276: =item B<$end> Unix time of the roles expiration
                   8277: 
                   8278: =item B<$start> Unix time of the roles start date
                   8279: 
                   8280: =item B<$forceid> If defined, allow $uid to be changed
                   8281: 
                   8282: =item B<$desiredhome> server to use as home server for student
                   8283: 
                   8284: =back
1.297     matthew  8285: 
                   8286: =item *
                   8287: 
                   8288: modify_student_enrollment
                   8289: 
                   8290: Change a students enrollment status in a class.  The environment variable
                   8291: 'role.request.course' must be defined for this function to proceed.
                   8292: 
                   8293: Inputs:
                   8294: 
                   8295: =over 4
                   8296: 
                   8297: =item $udom, students domain
                   8298: 
                   8299: =item $uname, students name
                   8300: 
                   8301: =item $uid, students user id
                   8302: 
                   8303: =item $first, students first name
                   8304: 
                   8305: =item $middle
                   8306: 
                   8307: =item $last
                   8308: 
                   8309: =item $gene
                   8310: 
                   8311: =item $usec
                   8312: 
                   8313: =item $end
                   8314: 
                   8315: =item $start
                   8316: 
                   8317: =back
                   8318: 
1.191     harris41 8319: 
                   8320: =item *
                   8321: 
1.243     albertel 8322: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   8323: custom role; give a custom role to a user for the level given by URL.  Specify
                   8324: name and domain of role author, and role name
1.191     harris41 8325: 
                   8326: =item *
                   8327: 
1.243     albertel 8328: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 8329: 
                   8330: =item *
                   8331: 
1.243     albertel 8332: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   8333: 
                   8334: =back
                   8335: 
                   8336: =head2 Course Infomation
                   8337: 
                   8338: =over 4
1.191     harris41 8339: 
                   8340: =item *
                   8341: 
1.631     albertel 8342: coursedescription($courseid) : returns a hash of information about the
                   8343: specified course id, including all environment settings for the
                   8344: course, the description of the course will be in the hash under the
                   8345: key 'description'
1.191     harris41 8346: 
                   8347: =item *
                   8348: 
1.624     albertel 8349: resdata($name,$domain,$type,@which) : request for current parameter
                   8350: setting for a specific $type, where $type is either 'course' or 'user',
                   8351: @what should be a list of parameters to ask about. This routine caches
                   8352: answers for 5 minutes.
1.243     albertel 8353: 
                   8354: =back
                   8355: 
                   8356: =head2 Course Modification
                   8357: 
                   8358: =over 4
1.191     harris41 8359: 
                   8360: =item *
                   8361: 
1.243     albertel 8362: writecoursepref($courseid,%prefs) : write preferences (environment
                   8363: database) for a course
1.191     harris41 8364: 
                   8365: =item *
                   8366: 
1.243     albertel 8367: createcourse($udom,$description,$url) : make/modify course
                   8368: 
                   8369: =back
                   8370: 
                   8371: =head2 Resource Subroutines
                   8372: 
                   8373: =over 4
1.191     harris41 8374: 
                   8375: =item *
                   8376: 
1.243     albertel 8377: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 8378: 
                   8379: =item *
                   8380: 
1.243     albertel 8381: repcopy($filename) : subscribes to the requested file, and attempts to
                   8382: replicate from the owning library server, Might return
1.607     raeburn  8383: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   8384: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 8385: resource. Expects the local filesystem pathname
                   8386: (/home/httpd/html/res/....)
                   8387: 
                   8388: =back
                   8389: 
                   8390: =head2 Resource Information
                   8391: 
                   8392: =over 4
1.191     harris41 8393: 
                   8394: =item *
                   8395: 
1.243     albertel 8396: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   8397: a vairety of different possible values, $varname should be a request
                   8398: string, and the other parameters can be used to specify who and what
                   8399: one is asking about.
                   8400: 
                   8401: Possible values for $varname are environment.lastname (or other item
                   8402: from the envirnment hash), user.name (or someother aspect about the
                   8403: user), resource.0.maxtries (or some other part and parameter of a
                   8404: resource)
1.204     albertel 8405: 
                   8406: =item *
                   8407: 
1.243     albertel 8408: directcondval($number) : get current value of a condition; reads from a state
                   8409: string
1.204     albertel 8410: 
                   8411: =item *
                   8412: 
1.243     albertel 8413: condval($condidx) : value of condition index based on state
1.204     albertel 8414: 
                   8415: =item *
                   8416: 
1.243     albertel 8417: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   8418: resource's metadata, $what should be either a specific key, or either
                   8419: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   8420: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   8421: 
                   8422: this function automatically caches all requests
1.191     harris41 8423: 
                   8424: =item *
                   8425: 
1.243     albertel 8426: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   8427: network of library servers; returns file handle of where SQL and regex results
                   8428: will be stored for query
1.191     harris41 8429: 
                   8430: =item *
                   8431: 
1.243     albertel 8432: symbread($filename) : return symbolic list entry (filename argument optional);
                   8433: returns the data handle
1.191     harris41 8434: 
                   8435: =item *
                   8436: 
1.243     albertel 8437: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 8438: a possible symb for the URL in $thisfn, and if is an encryypted
                   8439: resource that the user accessed using /enc/ returns a 1 on success, 0
                   8440: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 8441: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 8442: 
1.191     harris41 8443: 
                   8444: =item *
                   8445: 
1.243     albertel 8446: symbclean($symb) : removes versions numbers from a symb, returns the
                   8447: cleaned symb
1.191     harris41 8448: 
                   8449: =item *
                   8450: 
1.243     albertel 8451: is_on_map($uri) : checks if the $uri is somewhere on the current
                   8452: course map, user must be in a course for it to work.
1.191     harris41 8453: 
                   8454: =item *
                   8455: 
1.243     albertel 8456: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 8457: 
                   8458: =item *
                   8459: 
1.243     albertel 8460: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   8461: a random seed, all arguments are optional, if they aren't sent it uses the
                   8462: environment to derive them. Note: if symb isn't sent and it can't get one
                   8463: from &symbread it will use the current time as its return value
1.191     harris41 8464: 
                   8465: =item *
                   8466: 
1.243     albertel 8467: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   8468: unfakeable, receipt
1.191     harris41 8469: 
                   8470: =item *
                   8471: 
1.620     albertel 8472: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 8473: 
                   8474: =item *
                   8475: 
1.243     albertel 8476: countacc($url) : count the number of accesses to a given URL
1.191     harris41 8477: 
                   8478: =item *
                   8479: 
1.243     albertel 8480: 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 8481: 
                   8482: =item *
                   8483: 
1.243     albertel 8484: 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 8485: 
                   8486: =item *
                   8487: 
1.243     albertel 8488: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 8489: 
                   8490: =item *
                   8491: 
1.243     albertel 8492: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   8493: forcing spreadsheet to reevaluate the resource scores next time.
                   8494: 
                   8495: =back
                   8496: 
                   8497: =head2 Storing/Retreiving Data
                   8498: 
                   8499: =over 4
1.191     harris41 8500: 
                   8501: =item *
                   8502: 
1.243     albertel 8503: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   8504: for this url; hashref needs to be given and should be a \%hashname; the
                   8505: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 8506: be derived from the env
1.191     harris41 8507: 
                   8508: =item *
                   8509: 
1.243     albertel 8510: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   8511: uses critical subroutine
1.191     harris41 8512: 
                   8513: =item *
                   8514: 
1.243     albertel 8515: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   8516: all args are optional
1.191     harris41 8517: 
                   8518: =item *
                   8519: 
1.717     albertel 8520: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   8521: dumps the complete (or key matching regexp) namespace into a hash
                   8522: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   8523: normally &store()ed into
                   8524: 
                   8525: $range should be either an integer '100' (give me the first 100
                   8526:                                            matching records)
                   8527:               or be  two integers sperated by a - with no spaces
                   8528:                  '30-50' (give me the 30th through the 50th matching
                   8529:                           records)
                   8530: 
                   8531: 
                   8532: =item *
                   8533: 
                   8534: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   8535: replaces a &store() version of data with a replacement set of data
                   8536: for a particular resource in a namespace passed in the $storehash hash 
                   8537: reference
                   8538: 
                   8539: =item *
                   8540: 
1.243     albertel 8541: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   8542: works very similar to store/cstore, but all data is stored in a
                   8543: temporary location and can be reset using tmpreset, $storehash should
                   8544: be a hash reference, returns nothing on success
1.191     harris41 8545: 
                   8546: =item *
                   8547: 
1.243     albertel 8548: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   8549: similar to restore, but all data is stored in a temporary location and
                   8550: can be reset using tmpreset. Returns a hash of values on success,
                   8551: error string otherwise.
1.191     harris41 8552: 
                   8553: =item *
                   8554: 
1.243     albertel 8555: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   8556: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 8557: 
                   8558: =item *
                   8559: 
1.243     albertel 8560: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   8561: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 8562: 
                   8563: =item *
                   8564: 
1.243     albertel 8565: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   8566: namesp ($udom and $uname are optional)
1.191     harris41 8567: 
                   8568: =item *
                   8569: 
1.702     albertel 8570: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 8571: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 8572: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  8573: 
1.702     albertel 8574: $range should be either an integer '100' (give me the first 100
                   8575:                                            matching records)
                   8576:               or be  two integers sperated by a - with no spaces
                   8577:                  '30-50' (give me the 30th through the 50th matching
                   8578:                           records)
1.449     matthew  8579: =item *
                   8580: 
                   8581: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   8582: $store can be a scalar, an array reference, or if the amount to be 
                   8583: incremented is > 1, a hash reference.
                   8584: 
                   8585: ($udom and $uname are optional)
1.191     harris41 8586: 
                   8587: =item *
                   8588: 
1.243     albertel 8589: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   8590: ($udom and $uname are optional)
1.191     harris41 8591: 
                   8592: =item *
                   8593: 
1.243     albertel 8594: cput($namespace,$storehash,$udom,$uname) : critical put
                   8595: ($udom and $uname are optional)
1.191     harris41 8596: 
                   8597: =item *
                   8598: 
1.748     albertel 8599: newput($namespace,$storehash,$udom,$uname) :
                   8600: 
                   8601: Attempts to store the items in the $storehash, but only if they don't
                   8602: currently exist, if this succeeds you can be certain that you have 
                   8603: successfully created a new key value pair in the $namespace db.
                   8604: 
                   8605: 
                   8606: Args:
                   8607:  $namespace: name of database to store values to
                   8608:  $storehash: hashref to store to the db
                   8609:  $udom: (optional) domain of user containing the db
                   8610:  $uname: (optional) name of user caontaining the db
                   8611: 
                   8612: Returns:
                   8613:  'ok' -> succeeded in storing all keys of $storehash
                   8614:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   8615:                         least <key> already existed in the db (other
                   8616:                         requested keys may also already exist)
                   8617:  'error: <msg>' -> unable to tie the DB or other erorr occured
                   8618:  'con_lost' -> unable to contact request server
                   8619:  'refused' -> action was not allowed by remote machine
                   8620: 
                   8621: 
                   8622: =item *
                   8623: 
1.243     albertel 8624: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   8625: reference filled in from namesp (encrypts the return communication)
                   8626: ($udom and $uname are optional)
1.191     harris41 8627: 
                   8628: =item *
                   8629: 
1.243     albertel 8630: log($udom,$name,$home,$message) : write to permanent log for user; use
                   8631: critical subroutine
                   8632: 
1.806     raeburn  8633: =item *
                   8634: 
                   8635: get_dom($namespace,$storearr,$udomain) : returns hash with keys from array
                   8636: reference filled in from namespace found in domain level on primary domain server ($udomain is optional)
                   8637: 
                   8638: =item *
                   8639: 
                   8640: put_dom($namespace,$storehash,$udomain) :  stores hash in namespace at domain level on primary domain server ($udomain is optional)
                   8641: 
1.243     albertel 8642: =back
                   8643: 
                   8644: =head2 Network Status Functions
                   8645: 
                   8646: =over 4
1.191     harris41 8647: 
                   8648: =item *
                   8649: 
                   8650: dirlist($uri) : return directory list based on URI
                   8651: 
                   8652: =item *
                   8653: 
1.243     albertel 8654: spareserver() : find server with least workload from spare.tab
                   8655: 
                   8656: =back
                   8657: 
                   8658: =head2 Apache Request
                   8659: 
                   8660: =over 4
1.191     harris41 8661: 
                   8662: =item *
                   8663: 
1.243     albertel 8664: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   8665: localhost, posts hash
                   8666: 
                   8667: =back
                   8668: 
                   8669: =head2 Data to String to Data
                   8670: 
                   8671: =over 4
1.191     harris41 8672: 
                   8673: =item *
                   8674: 
1.243     albertel 8675: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   8676: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 8677: 
                   8678: =item *
                   8679: 
1.243     albertel 8680: hashref2str($hashref) : convert a hashref into a string complete with
                   8681: escaping and '=' and '&' separators, supports elements that are
                   8682: arrayrefs and hashrefs
1.191     harris41 8683: 
                   8684: =item *
                   8685: 
1.243     albertel 8686: arrayref2str($arrayref) : convert an arrayref into a string complete
                   8687: with escaping and '&' separators, supports elements that are arrayrefs
                   8688: and hashrefs
1.191     harris41 8689: 
                   8690: =item *
                   8691: 
1.243     albertel 8692: str2hash($string) : convert string to hash using unescaping and
                   8693: splitting on '=' and '&', supports elements that are arrayrefs and
                   8694: hashrefs
1.191     harris41 8695: 
                   8696: =item *
                   8697: 
1.243     albertel 8698: str2array($string) : convert string to hash using unescaping and
                   8699: splitting on '&', supports elements that are arrayrefs and hashrefs
                   8700: 
                   8701: =back
                   8702: 
                   8703: =head2 Logging Routines
                   8704: 
                   8705: =over 4
                   8706: 
                   8707: These routines allow one to make log messages in the lonnet.log and
                   8708: lonnet.perm logfiles.
1.191     harris41 8709: 
                   8710: =item *
                   8711: 
1.243     albertel 8712: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 8713: 
                   8714: =item *
                   8715: 
1.243     albertel 8716: logthis() : append message to the normal lonnet.log file, it gets
                   8717: preiodically rolled over and deleted.
1.191     harris41 8718: 
                   8719: =item *
                   8720: 
1.243     albertel 8721: logperm() : append a permanent message to lonnet.perm.log, this log
                   8722: file never gets deleted by any automated portion of the system, only
                   8723: messages of critical importance should go in here.
                   8724: 
                   8725: =back
                   8726: 
                   8727: =head2 General File Helper Routines
                   8728: 
                   8729: =over 4
1.191     harris41 8730: 
                   8731: =item *
                   8732: 
1.481     raeburn  8733: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   8734: (a) files in /uploaded
                   8735:   (i) If a local copy of the file exists - 
                   8736:       compares modification date of local copy with last-modified date for 
                   8737:       definitive version stored on home server for course. If local copy is 
                   8738:       stale, requests a new version from the home server and stores it. 
                   8739:       If the original has been removed from the home server, then local copy 
                   8740:       is unlinked.
                   8741:   (ii) If local copy does not exist -
                   8742:       requests the file from the home server and stores it. 
                   8743:   
                   8744:   If $caller is 'uploadrep':  
                   8745:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   8746:     for request for files originally uploaded via DOCS. 
                   8747:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   8748:   
                   8749:   Otherwise:
                   8750:      This indicates a call from the content generation phase of the request.
                   8751:      -  returns the entire contents of the file or -1.
                   8752:      
                   8753: (b) files in /res
                   8754:    - returns the entire contents of a file or -1; 
                   8755:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 8756: 
1.712     albertel 8757: 
                   8758: =item *
                   8759: 
                   8760: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   8761:                   reference
                   8762: 
                   8763: returns either a stat() list of data about the file or an empty list
                   8764: if the file doesn't exist or couldn't find out about it (connection
                   8765: problems or user unknown)
                   8766: 
1.191     harris41 8767: =item *
                   8768: 
1.243     albertel 8769: filelocation($dir,$file) : returns file system location of a file
                   8770: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   8771: directory that relative $file lookups are to looked in ($dir of /a/dir
                   8772: and a file of ../bob will become /a/bob)
1.191     harris41 8773: 
                   8774: =item *
                   8775: 
                   8776: hreflocation($dir,$file) : returns file system location or a URL; same as
                   8777: filelocation except for hrefs
                   8778: 
                   8779: =item *
                   8780: 
                   8781: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   8782: 
1.243     albertel 8783: =back
                   8784: 
1.608     albertel 8785: =head2 Usererfile file routines (/uploaded*)
                   8786: 
                   8787: =over 4
                   8788: 
                   8789: =item *
                   8790: 
                   8791: userfileupload(): main rotine for putting a file in a user or course's
                   8792:                   filespace, arguments are,
                   8793: 
1.620     albertel 8794:  formname - required - this is the name of the element in $env where the
1.608     albertel 8795:            filename, and the contents of the file to create/modifed exist
1.620     albertel 8796:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   8797:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 8798:  coursedoc - if true, store the file in the course of the active role
                   8799:              of the current user
                   8800:  subdir - required - subdirectory to put the file in under ../userfiles/
                   8801:          if undefined, it will be placed in "unknown"
                   8802: 
                   8803:  (This routine calls clean_filename() to remove any dangerous
                   8804:  characters from the filename, and then calls finuserfileupload() to
                   8805:  complete the transaction)
                   8806: 
                   8807:  returns either the url of the uploaded file (/uploaded/....) if successful
                   8808:  and /adm/notfound.html if unsuccessful
                   8809: 
                   8810: =item *
                   8811: 
                   8812: clean_filename(): routine for cleaing a filename up for storage in
                   8813:                  userfile space, argument is:
                   8814: 
                   8815:  filename - proposed filename
                   8816: 
                   8817: returns: the new clean filename
                   8818: 
                   8819: =item *
                   8820: 
                   8821: finishuserfileupload(): routine that creaes and sends the file to
                   8822: userspace, probably shouldn't be called directly
                   8823: 
                   8824:   docuname: username or courseid of destination for the file
                   8825:   docudom: domain of user/course of destination for the file
                   8826:   formname: same as for userfileupload()
                   8827:   fname: filename (inculding subdirectories) for the file
                   8828: 
                   8829:  returns either the url of the uploaded file (/uploaded/....) if successful
                   8830:  and /adm/notfound.html if unsuccessful
                   8831: 
                   8832: =item *
                   8833: 
                   8834: renameuserfile(): renames an existing userfile to a new name
                   8835: 
                   8836:   Args:
                   8837:    docuname: username or courseid of destination for the file
                   8838:    docudom: domain of user/course of destination for the file
                   8839:    old: current file name (including any subdirs under userfiles)
                   8840:    new: desired file name (including any subdirs under userfiles)
                   8841: 
                   8842: =item *
                   8843: 
                   8844: mkdiruserfile(): creates a directory is a userfiles dir
                   8845: 
                   8846:   Args:
                   8847:    docuname: username or courseid of destination for the file
                   8848:    docudom: domain of user/course of destination for the file
                   8849:    dir: dir to create (including any subdirs under userfiles)
                   8850: 
                   8851: =item *
                   8852: 
                   8853: removeuserfile(): removes a file that exists in userfiles
                   8854: 
                   8855:   Args:
                   8856:    docuname: username or courseid of destination for the file
                   8857:    docudom: domain of user/course of destination for the file
                   8858:    fname: filname to delete (including any subdirs under userfiles)
                   8859: 
                   8860: =item *
                   8861: 
                   8862: removeuploadedurl(): convience function for removeuserfile()
                   8863: 
                   8864:   Args:
                   8865:    url:  a full /uploaded/... url to delete
                   8866: 
1.747     albertel 8867: =item * 
                   8868: 
                   8869: get_portfile_permissions():
                   8870:   Args:
                   8871:     domain: domain of user or course contain the portfolio files
                   8872:     user: name of user or num of course contain the portfolio files
                   8873:   Returns:
                   8874:     hashref of a dump of the proper file_permissions.db
                   8875:    
                   8876: 
                   8877: =item * 
                   8878: 
                   8879: get_access_controls():
                   8880: 
                   8881: Args:
                   8882:   current_permissions: the hash ref returned from get_portfile_permissions()
                   8883:   group: (optional) the group you want the files associated with
                   8884:   file: (optional) the file you want access info on
                   8885: 
                   8886: Returns:
1.749     raeburn  8887:     a hash (keys are file names) of hashes containing
                   8888:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   8889:         values are XML containing access control settings (see below) 
1.747     albertel 8890: 
                   8891: Internal notes:
                   8892: 
1.749     raeburn  8893:  access controls are stored in file_permissions.db as key=value pairs.
                   8894:     key -> path to file/file_name\0uniqueID:scope_end_start
                   8895:         where scope -> public,guest,course,group,domains or users.
                   8896:               end -> UNIX time for end of access (0 -> no end date)
                   8897:               start -> UNIX time for start of access
                   8898: 
                   8899:     value -> XML description of access control
                   8900:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   8901:             <start></start>
                   8902:             <end></end>
                   8903: 
                   8904:             <password></password>  for scope type = guest
                   8905: 
                   8906:             <domain></domain>     for scope type = course or group
                   8907:             <number></number>
                   8908:             <roles id="">
                   8909:              <role></role>
                   8910:              <access></access>
                   8911:              <section></section>
                   8912:              <group></group>
                   8913:             </roles>
                   8914: 
                   8915:             <dom></dom>         for scope type = domains
                   8916: 
                   8917:             <users>             for scope type = users
                   8918:              <user>
                   8919:               <uname></uname>
                   8920:               <udom></udom>
                   8921:              </user>
                   8922:             </users>
                   8923:            </scope> 
                   8924:               
                   8925:  Access data is also aggregated for each file in an additional key=value pair:
                   8926:  key -> path to file/file_name\0accesscontrol 
                   8927:  value -> reference to hash
                   8928:           hash contains key = value pairs
                   8929:           where key = uniqueID:scope_end_start
                   8930:                 value = UNIX time record was last updated
                   8931: 
                   8932:           Used to improve speed of look-ups of access controls for each file.  
                   8933:  
                   8934:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   8935: 
                   8936: modify_access_controls():
                   8937: 
                   8938: Modifies access controls for a portfolio file
                   8939: Args
                   8940: 1. file name
                   8941: 2. reference to hash of required changes,
                   8942: 3. domain
                   8943: 4. username
                   8944:   where domain,username are the domain of the portfolio owner 
                   8945:   (either a user or a course) 
                   8946: 
                   8947: Returns:
                   8948: 1. result of additions or updates ('ok' or 'error', with error message). 
                   8949: 2. result of deletions ('ok' or 'error', with error message).
                   8950: 3. reference to hash of any new or updated access controls.
                   8951: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   8952:    key = integer (inbound ID)
                   8953:    value = uniqueID  
1.747     albertel 8954: 
1.608     albertel 8955: =back
                   8956: 
1.243     albertel 8957: =head2 HTTP Helper Routines
                   8958: 
                   8959: =over 4
                   8960: 
1.191     harris41 8961: =item *
                   8962: 
                   8963: escape() : unpack non-word characters into CGI-compatible hex codes
                   8964: 
                   8965: =item *
                   8966: 
                   8967: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   8968: 
1.243     albertel 8969: =back
                   8970: 
                   8971: =head1 PRIVATE SUBROUTINES
                   8972: 
                   8973: =head2 Underlying communication routines (Shouldn't call)
                   8974: 
                   8975: =over 4
                   8976: 
                   8977: =item *
                   8978: 
                   8979: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   8980: 
                   8981: =item *
                   8982: 
                   8983: reply() : uses subreply to send a message to remote machine, logs all failures
                   8984: 
                   8985: =item *
                   8986: 
                   8987: critical() : passes a critical message to another server; if cannot
                   8988: get through then place message in connection buffer directory and
                   8989: returns con_delayed, if incapable of saving message, returns
                   8990: con_failed
                   8991: 
                   8992: =item *
                   8993: 
                   8994: reconlonc() : tries to reconnect lonc client processes.
                   8995: 
                   8996: =back
                   8997: 
                   8998: =head2 Resource Access Logging
                   8999: 
                   9000: =over 4
                   9001: 
                   9002: =item *
                   9003: 
                   9004: flushcourselogs() : flush (save) buffer logs and access logs
                   9005: 
                   9006: =item *
                   9007: 
                   9008: courselog($what) : save message for course in hash
                   9009: 
                   9010: =item *
                   9011: 
                   9012: courseacclog($what) : save message for course using &courselog().  Perform
                   9013: special processing for specific resource types (problems, exams, quizzes, etc).
                   9014: 
1.191     harris41 9015: =item *
                   9016: 
                   9017: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   9018: as a PerlChildExitHandler
1.243     albertel 9019: 
                   9020: =back
                   9021: 
                   9022: =head2 Other
                   9023: 
                   9024: =over 4
                   9025: 
                   9026: =item *
                   9027: 
                   9028: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 9029: 
                   9030: =back
                   9031: 
                   9032: =cut

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