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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.872   ! albertel    4: # $Id: lonnet.pm,v 1.871 2007/04/20 21:48:09 albertel Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.1       albertel   30: package Apache::lonnet;
                     31: 
                     32: use strict;
1.8       www        33: use LWP::UserAgent();
1.486     www        34: use HTTP::Date;
                     35: # use Date::Parse;
1.871     albertel   36: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
                     37:             $_64bit %env);
                     38: 
                     39: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     40:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     41:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
                     42:     %courseownerbuf, %coursetypebuf);
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.88      www        47: use Fcntl qw(:flock);
1.870     albertel   48: use Storable qw(thaw nfreeze);
1.539     albertel   49: use Time::HiRes qw( gettimeofday tv_interval );
1.599     albertel   50: use Cache::Memcached;
1.676     albertel   51: use Digest::MD5;
1.790     albertel   52: use Math::Random;
1.807     albertel   53: use LONCAPA qw(:DEFAULT :match);
1.740     www        54: use LONCAPA::Configuration;
1.676     albertel   55: 
1.195     www        56: my $readit;
1.550     foxr       57: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel   58: 
1.619     albertel   59: require Exporter;
                     60: 
                     61: our @ISA = qw (Exporter);
                     62: our @EXPORT = qw(%env);
                     63: 
1.449     matthew    64: =pod
                     65: 
                     66: =head1 Package Variables
                     67: 
                     68: These are largely undocumented, so if you decipher one please note it here.
                     69: 
                     70: =over 4
                     71: 
                     72: =item $processmarker
                     73: 
                     74: Contains the time this process was started and this servers host id.
                     75: 
                     76: =item $dumpcount
                     77: 
                     78: Counts the number of times a message log flush has been attempted (regardless
                     79: of success) by this process.  Used as part of the filename when messages are
                     80: delayed.
                     81: 
                     82: =back
                     83: 
                     84: =cut
                     85: 
                     86: 
1.1       albertel   87: # --------------------------------------------------------------------- Logging
1.729     www        88: {
                     89:     my $logid;
                     90:     sub instructor_log {
                     91: 	my ($hash_name,$storehash,$delflag,$uname,$udom)=@_;
                     92: 	$logid++;
                     93: 	my $id=time().'00000'.$$.'00000'.$logid;
                     94: 	return &Apache::lonnet::put('nohist_'.$hash_name,
1.730     www        95: 				    { $id => {
                     96: 					'exe_uname' => $env{'user.name'},
                     97: 					'exe_udom'  => $env{'user.domain'},
                     98: 					'exe_time'  => time(),
                     99: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    100: 					'delflag'   => $delflag,
                    101: 					'logentry'  => $storehash,
                    102: 					'uname'     => $uname,
                    103: 					'udom'      => $udom,
                    104: 				    }
                    105: 				  },
1.729     www       106: 				    $env{'course.'.$env{'request.course.id'}.'.domain'},
                    107: 				    $env{'course.'.$env{'request.course.id'}.'.num'}
                    108: 				    );
                    109:     }
                    110: }
1.1       albertel  111: 
1.163     harris41  112: sub logtouch {
                    113:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  114:     unless (-e "$execdir/logs/lonnet.log") {	
                    115: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  116: 	close $fh;
                    117:     }
                    118:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    119:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    120: }
                    121: 
1.1       albertel  122: sub logthis {
                    123:     my $message=shift;
                    124:     my $execdir=$perlvar{'lonDaemons'};
                    125:     my $now=time;
                    126:     my $local=localtime($now);
1.448     albertel  127:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
                    128: 	print $fh "$local ($$): $message\n";
                    129: 	close($fh);
                    130:     }
1.1       albertel  131:     return 1;
                    132: }
                    133: 
                    134: sub logperm {
                    135:     my $message=shift;
                    136:     my $execdir=$perlvar{'lonDaemons'};
                    137:     my $now=time;
                    138:     my $local=localtime($now);
1.448     albertel  139:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    140: 	print $fh "$now:$message:$local\n";
                    141: 	close($fh);
                    142:     }
1.1       albertel  143:     return 1;
                    144: }
                    145: 
1.850     albertel  146: sub create_connection {
1.853     albertel  147:     my ($hostname,$lonid) = @_;
1.851     albertel  148:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  149: 				     Type    => SOCK_STREAM,
                    150: 				     Timeout => 10);
                    151:     return 0 if (!$client);
1.854     albertel  152:     print $client (join(':',$hostname,$lonid,&machine_ids($lonid))."\n");
1.850     albertel  153:     my $result = <$client>;
                    154:     chomp($result);
                    155:     return 1 if ($result eq 'done');
                    156:     return 0;
                    157: }
                    158: 
                    159: 
1.1       albertel  160: # -------------------------------------------------- Non-critical communication
                    161: sub subreply {
                    162:     my ($cmd,$server)=@_;
1.838     albertel  163:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      164:     #
                    165:     #  With loncnew process trimming, there's a timing hole between lonc server
                    166:     #  process exit and the master server picking up the listen on the AF_UNIX
                    167:     #  socket.  In that time interval, a lock file will exist:
                    168: 
                    169:     my $lockfile=$peerfile.".lock";
                    170:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    171: 	sleep(1);
                    172:     }
                    173:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      174:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      175:     #
1.550     foxr      176:     #   We'll give the connection a few tries before abandoning it.  If
                    177:     #   connection is not possible, we'll con_lost back to the client.
                    178:     #   
                    179:     my $client;
                    180:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    181: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    182: 				      Type    => SOCK_STREAM,
                    183: 				      Timeout => 10);
1.869     albertel  184: 	if ($client) {
1.550     foxr      185: 	    last;		# Connected!
1.850     albertel  186: 	} else {
1.853     albertel  187: 	    &create_connection(&hostname($server),$server);
1.550     foxr      188: 	}
1.850     albertel  189:         sleep(1);		# Try again later if failed connection.
1.550     foxr      190:     }
                    191:     my $answer;
                    192:     if ($client) {
1.704     albertel  193: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      194: 	$answer=<$client>;
                    195: 	if (!$answer) { $answer="con_lost"; }
                    196: 	chomp($answer);
                    197:     } else {
                    198: 	$answer = 'con_lost';	# Failed connection.
                    199:     }
1.1       albertel  200:     return $answer;
                    201: }
                    202: 
                    203: sub reply {
                    204:     my ($cmd,$server)=@_;
1.838     albertel  205:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  206:     my $answer=subreply($cmd,$server);
1.65      www       207:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  208:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       209:                 " $cmd to $server returned $answer</font>");
                    210:     }
1.1       albertel  211:     return $answer;
                    212: }
                    213: 
                    214: # ----------------------------------------------------------- Send USR1 to lonc
                    215: 
                    216: sub reconlonc {
1.836     www       217:     &logthis("Trying to reconnect lonc");
1.1       albertel  218:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  219:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  220: 	my $loncpid=<$fh>;
                    221:         chomp($loncpid);
                    222:         if (kill 0 => $loncpid) {
                    223: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    224:             kill USR1 => $loncpid;
                    225:             sleep 1;
1.836     www       226:          } else {
1.12      www       227: 	    &logthis(
1.672     albertel  228:                "<font color=\"blue\">WARNING:".
1.12      www       229:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  230:         }
                    231:     } else {
1.836     www       232: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  233:     }
                    234: }
                    235: 
                    236: # ------------------------------------------------------ Critical communication
1.12      www       237: 
1.1       albertel  238: sub critical {
                    239:     my ($cmd,$server)=@_;
1.838     albertel  240:     unless (&hostname($server)) {
1.672     albertel  241:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       242:                " Critical message to unknown server ($server)</font>");
                    243:         return 'no_such_host';
                    244:     }
1.1       albertel  245:     my $answer=reply($cmd,$server);
                    246:     if ($answer eq 'con_lost') {
                    247: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  248: 	my $answer=reply($cmd,$server);
1.1       albertel  249:         if ($answer eq 'con_lost') {
                    250:             my $now=time;
                    251:             my $middlename=$cmd;
1.5       www       252:             $middlename=substr($middlename,0,16);
1.1       albertel  253:             $middlename=~s/\W//g;
                    254:             my $dfilename=
1.305     www       255:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    256:             $dumpcount++;
1.1       albertel  257:             {
1.448     albertel  258: 		my $dfh;
                    259: 		if (open($dfh,">$dfilename")) {
                    260: 		    print $dfh "$cmd\n"; 
                    261: 		    close($dfh);
                    262: 		}
1.1       albertel  263:             }
                    264:             sleep 2;
                    265:             my $wcmd='';
                    266:             {
1.448     albertel  267: 		my $dfh;
                    268: 		if (open($dfh,"<$dfilename")) {
                    269: 		    $wcmd=<$dfh>; 
                    270: 		    close($dfh);
                    271: 		}
1.1       albertel  272:             }
                    273:             chomp($wcmd);
1.7       www       274:             if ($wcmd eq $cmd) {
1.672     albertel  275: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       276:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  277:                 &logperm("D:$server:$cmd");
                    278: 	        return 'con_delayed';
                    279:             } else {
1.672     albertel  280:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       281:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  282:                 &logperm("F:$server:$cmd");
                    283:                 return 'con_failed';
                    284:             }
                    285:         }
                    286:     }
                    287:     return $answer;
1.405     albertel  288: }
                    289: 
1.755     albertel  290: # ------------------------------------------- check if return value is an error
                    291: 
                    292: sub error {
                    293:     my ($result) = @_;
1.756     albertel  294:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  295: 	if ($2 == 2) { return undef; }
                    296: 	return $1;
                    297:     }
                    298:     return undef;
                    299: }
                    300: 
1.783     albertel  301: sub convert_and_load_session_env {
                    302:     my ($lonidsdir,$handle)=@_;
                    303:     my @profile;
                    304:     {
                    305: 	open(my $idf,"$lonidsdir/$handle.id");
                    306: 	flock($idf,LOCK_SH);
                    307: 	@profile=<$idf>;
                    308: 	close($idf);
                    309:     }
                    310:     my %temp_env;
                    311:     foreach my $line (@profile) {
1.786     albertel  312: 	if ($line !~ m/=/) {
                    313: 	    return 0;
                    314: 	}
1.783     albertel  315: 	chomp($line);
                    316: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    317: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    318:     }
                    319:     unlink("$lonidsdir/$handle.id");
                    320:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    321: 	    0640)) {
                    322: 	%disk_env = %temp_env;
                    323: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    324: 	untie(%disk_env);
                    325:     }
1.786     albertel  326:     return 1;
1.783     albertel  327: }
                    328: 
1.374     www       329: # ------------------------------------------- Transfer profile into environment
1.780     albertel  330: my $env_loaded;
                    331: sub transfer_profile_to_env {
1.788     albertel  332:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    333:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       334: 
1.720     albertel  335:     if (!defined($lonidsdir)) {
                    336: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    337:     }
                    338:     if (!defined($handle)) {
                    339:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    340:     }
                    341: 
1.786     albertel  342:     my $convert;
                    343:     {
                    344:     	open(my $idf,"$lonidsdir/$handle.id");
                    345: 	flock($idf,LOCK_SH);
                    346: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    347: 		&GDBM_READER(),0640)) {
                    348: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    349: 	    untie(%disk_env);
                    350: 	} else {
                    351: 	    $convert = 1;
                    352: 	}
                    353:     }
                    354:     if ($convert) {
                    355: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    356: 	    &logthis("Failed to load session, or convert session.");
                    357: 	}
1.374     www       358:     }
1.783     albertel  359: 
1.786     albertel  360:     my %remove;
1.783     albertel  361:     while ( my $envname = each(%env) ) {
1.433     matthew   362:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    363:             if ($time < time-300) {
1.783     albertel  364:                 $remove{$key}++;
1.433     matthew   365:             }
                    366:         }
                    367:     }
1.783     albertel  368: 
1.619     albertel  369:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  370:     $env_loaded=1;
1.783     albertel  371:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   372:         &delenv($expired_key);
1.374     www       373:     }
1.1       albertel  374: }
                    375: 
1.830     albertel  376: sub timed_flock {
                    377:     my ($file,$lock_type) = @_;
                    378:     my $failed=0;
                    379:     eval {
                    380: 	local $SIG{__DIE__}='DEFAULT';
                    381: 	local $SIG{ALRM}=sub {
                    382: 	    $failed=1;
                    383: 	    die("failed lock");
                    384: 	};
                    385: 	alarm(13);
                    386: 	flock($file,$lock_type);
                    387: 	alarm(0);
                    388:     };
                    389:     if ($failed) {
                    390: 	return undef;
                    391:     } else {
                    392: 	return 1;
                    393:     }
                    394: }
                    395: 
1.5       www       396: # ---------------------------------------------------------- Append Environment
                    397: 
                    398: sub appenv {
1.6       www       399:     my %newenv=@_;
1.692     albertel  400:     foreach my $key (keys(%newenv)) {
                    401: 	if (($newenv{$key}=~/^user\.role/) || ($newenv{$key}=~/^user\.priv/)) {
1.672     albertel  402:             &logthis("<font color=\"blue\">WARNING: ".
1.692     albertel  403:                 "Attempt to modify environment ".$key." to ".$newenv{$key}
1.151     www       404:                 .'</font>');
1.692     albertel  405: 	    delete($newenv{$key});
1.35      www       406:         } else {
1.692     albertel  407:             $env{$key}=$newenv{$key};
1.35      www       408:         }
1.191     harris41  409:     }
1.830     albertel  410:     open(my $env_file,$env{'user.environment'});
                    411:     if (&timed_flock($env_file,LOCK_EX)
                    412: 	&&
                    413: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    414: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  415: 	while (my ($key,$value) = each(%newenv)) {
                    416: 	    $disk_env{$key} = $value;
1.448     albertel  417: 	}
1.783     albertel  418: 	untie(%disk_env);
1.56      www       419:     }
                    420:     return 'ok';
                    421: }
                    422: # ----------------------------------------------------- Delete from Environment
                    423: 
                    424: sub delenv {
                    425:     my $delthis=shift;
                    426:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672     albertel  427:         &logthis("<font color=\"blue\">WARNING: ".
1.56      www       428:                 "Attempt to delete from environment ".$delthis);
                    429:         return 'error';
                    430:     }
1.830     albertel  431:     open(my $env_file,$env{'user.environment'});
                    432:     if (&timed_flock($env_file,LOCK_EX)
                    433: 	&&
                    434: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    435: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  436: 	foreach my $key (keys(%disk_env)) {
                    437: 	    if ($key=~/^$delthis/) { 
1.619     albertel  438:                 delete($env{$key});
1.783     albertel  439:                 delete($disk_env{$key});
1.473     matthew   440:             }
1.448     albertel  441: 	}
1.783     albertel  442: 	untie(%disk_env);
1.5       www       443:     }
                    444:     return 'ok';
1.369     albertel  445: }
                    446: 
1.790     albertel  447: sub get_env_multiple {
                    448:     my ($name) = @_;
                    449:     my @values;
                    450:     if (defined($env{$name})) {
                    451:         # exists is it an array
                    452:         if (ref($env{$name})) {
                    453:             @values=@{ $env{$name} };
                    454:         } else {
                    455:             $values[0]=$env{$name};
                    456:         }
                    457:     }
                    458:     return(@values);
                    459: }
                    460: 
1.369     albertel  461: # ------------------------------------------ Find out current server userload
                    462: # there is a copy in lond
                    463: sub userload {
                    464:     my $numusers=0;
                    465:     {
                    466: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    467: 	my $filename;
                    468: 	my $curtime=time;
                    469: 	while ($filename=readdir(LONIDS)) {
                    470: 	    if ($filename eq '.' || $filename eq '..') {next;}
1.404     albertel  471: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  472: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  473: 	}
                    474: 	closedir(LONIDS);
                    475:     }
                    476:     my $userloadpercent=0;
                    477:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    478:     if ($maxuserload) {
1.371     albertel  479: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  480:     }
1.372     albertel  481:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  482:     return $userloadpercent;
1.283     www       483: }
                    484: 
                    485: # ------------------------------------------ Fight off request when overloaded
                    486: 
                    487: sub overloaderror {
                    488:     my ($r,$checkserver)=@_;
                    489:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
                    490:     my $loadavg;
                    491:     if ($checkserver eq $perlvar{'lonHostID'}) {
1.448     albertel  492:        open(my $loadfile,'/proc/loadavg');
1.283     www       493:        $loadavg=<$loadfile>;
                    494:        $loadavg =~ s/\s.*//g;
1.285     matthew   495:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448     albertel  496:        close($loadfile);
1.283     www       497:     } else {
                    498:        $loadavg=&reply('load',$checkserver);
                    499:     }
1.285     matthew   500:     my $overload=$loadavg-100;
1.283     www       501:     if ($overload>0) {
1.285     matthew   502: 	$r->err_headers_out->{'Retry-After'}=$overload;
1.283     www       503:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554     www       504:         return 413;
1.283     www       505:     }    
                    506:     return '';
1.5       www       507: }
1.1       albertel  508: 
                    509: # ------------------------------ Find server with least workload from spare.tab
1.11      www       510: 
1.1       albertel  511: sub spareserver {
1.670     albertel  512:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.784     albertel  513:     my $spare_server;
1.370     albertel  514:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  515:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    516:                                                      :  $userloadpercent;
                    517:     
                    518:     foreach my $try_server (@{ $spareid{'primary'} }) {
                    519: 	($spare_server, $lowest_load) =
                    520: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
                    521:     }
                    522: 
                    523:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    524: 
                    525:     if (!$found_server) {
                    526: 	foreach my $try_server (@{ $spareid{'default'} }) {
                    527: 	    ($spare_server, $lowest_load) =
                    528: 		&compare_server_load($try_server, $spare_server, $lowest_load);
                    529: 	}
                    530:     }
                    531: 
                    532:     if (!$want_server_name) {
1.838     albertel  533: 	$spare_server="http://".&hostname($spare_server);
1.784     albertel  534:     }
                    535:     return $spare_server;
                    536: }
                    537: 
                    538: sub compare_server_load {
                    539:     my ($try_server, $spare_server, $lowest_load) = @_;
                    540: 
                    541:     my $loadans     = &reply('load',    $try_server);
                    542:     my $userloadans = &reply('userload',$try_server);
                    543: 
                    544:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
                    545: 	next; #didn't get a number from the server
                    546:     }
                    547: 
                    548:     my $load;
                    549:     if ($loadans =~ /\d/) {
                    550: 	if ($userloadans =~ /\d/) {
                    551: 	    #both are numbers, pick the bigger one
                    552: 	    $load = ($loadans > $userloadans) ? $loadans 
                    553: 		                              : $userloadans;
1.411     albertel  554: 	} else {
1.784     albertel  555: 	    $load = $loadans;
1.411     albertel  556: 	}
1.784     albertel  557:     } else {
                    558: 	$load = $userloadans;
                    559:     }
                    560: 
                    561:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    562: 	$spare_server = $try_server;
                    563: 	$lowest_load  = $load;
1.370     albertel  564:     }
1.784     albertel  565:     return ($spare_server,$lowest_load);
1.202     matthew   566: }
                    567: # --------------------------------------------- Try to change a user's password
                    568: 
                    569: sub changepass {
1.799     raeburn   570:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   571:     $currentpass = &escape($currentpass);
                    572:     $newpass     = &escape($newpass);
1.799     raeburn   573:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
1.202     matthew   574: 		       $server);
                    575:     if (! $answer) {
                    576: 	&logthis("No reply on password change request to $server ".
                    577: 		 "by $uname in domain $udom.");
                    578:     } elsif ($answer =~ "^ok") {
                    579:         &logthis("$uname in $udom successfully changed their password ".
                    580: 		 "on $server.");
                    581:     } elsif ($answer =~ "^pwchange_failure") {
                    582: 	&logthis("$uname in $udom was unable to change their password ".
                    583: 		 "on $server.  The action was blocked by either lcpasswd ".
                    584: 		 "or pwchange");
                    585:     } elsif ($answer =~ "^non_authorized") {
                    586:         &logthis("$uname in $udom did not get their password correct when ".
                    587: 		 "attempting to change it on $server.");
                    588:     } elsif ($answer =~ "^auth_mode_error") {
                    589:         &logthis("$uname in $udom attempted to change their password despite ".
                    590: 		 "not being locally or internally authenticated on $server.");
                    591:     } elsif ($answer =~ "^unknown_user") {
                    592:         &logthis("$uname in $udom attempted to change their password ".
                    593: 		 "on $server but were unable to because $server is not ".
                    594: 		 "their home server.");
                    595:     } elsif ($answer =~ "^refused") {
                    596: 	&logthis("$server refused to change $uname in $udom password because ".
                    597: 		 "it was sent an unencrypted request to change the password.");
                    598:     }
                    599:     return $answer;
1.1       albertel  600: }
                    601: 
1.169     harris41  602: # ----------------------- Try to determine user's current authentication scheme
                    603: 
                    604: sub queryauthenticate {
                    605:     my ($uname,$udom)=@_;
1.456     albertel  606:     my $uhome=&homeserver($uname,$udom);
                    607:     if (!$uhome) {
                    608: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                    609: 	return 'no_host';
                    610:     }
                    611:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                    612:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                    613: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41  614:     }
1.456     albertel  615:     return $answer;
1.169     harris41  616: }
                    617: 
1.1       albertel  618: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       619: 
1.1       albertel  620: sub authenticate {
                    621:     my ($uname,$upass,$udom)=@_;
1.807     albertel  622:     $upass=&escape($upass);
                    623:     $uname= &LONCAPA::clean_username($uname);
1.836     www       624:     my $uhome=&homeserver($uname,$udom,1);
                    625:     if ((!$uhome) || ($uhome eq 'no_host')) {
                    626: # Maybe the machine was offline and only re-appeared again recently?
                    627:         &reconlonc();
                    628: # One more
                    629: 	my $uhome=&homeserver($uname,$udom,1);
                    630: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                    631: 	    &logthis("User $uname at $udom is unknown in authenticate");
                    632: 	}
1.471     albertel  633: 	return 'no_host';
1.1       albertel  634:     }
1.471     albertel  635:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
                    636:     if ($answer eq 'authorized') {
                    637: 	&logthis("User $uname at $udom authorized by $uhome"); 
                    638: 	return $uhome; 
                    639:     }
                    640:     if ($answer eq 'non_authorized') {
                    641: 	&logthis("User $uname at $udom rejected by $uhome");
                    642: 	return 'no_host'; 
1.9       www       643:     }
1.471     albertel  644:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel  645:     return 'no_host';
                    646: }
                    647: 
                    648: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www       649: 
1.599     albertel  650: my %homecache;
1.1       albertel  651: sub homeserver {
1.230     stredwic  652:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel  653:     my $index="$uname:$udom";
1.426     albertel  654: 
1.599     albertel  655:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel  656: 
                    657:     my %servers = &get_servers($udom,'library');
                    658:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic  659:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic  660: 		 exists($badServerCache{$tryserver}));
1.841     albertel  661: 
                    662: 	my $answer=reply("home:$udom:$uname",$tryserver);
                    663: 	if ($answer eq 'found') {
                    664: 	    delete($badServerCache{$tryserver}); 
                    665: 	    return $homecache{$index}=$tryserver;
                    666: 	} elsif ($answer eq 'no_host') {
                    667: 	    $badServerCache{$tryserver}=1;
                    668: 	}
1.1       albertel  669:     }    
                    670:     return 'no_host';
1.70      www       671: }
                    672: 
                    673: # ------------------------------------- Find the usernames behind a list of IDs
                    674: 
                    675: sub idget {
                    676:     my ($udom,@ids)=@_;
                    677:     my %returnhash=();
                    678:     
1.841     albertel  679:     my %servers = &get_servers($udom,'library');
                    680:     foreach my $tryserver (keys(%servers)) {
                    681: 	my $idlist=join('&',@ids);
                    682: 	$idlist=~tr/A-Z/a-z/; 
                    683: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                    684: 	my @answer=();
                    685: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                    686: 	    @answer=split(/\&/,$reply);
                    687: 	}                    ;
                    688: 	my $i;
                    689: 	for ($i=0;$i<=$#ids;$i++) {
                    690: 	    if ($answer[$i]) {
                    691: 		$returnhash{$ids[$i]}=$answer[$i];
                    692: 	    } 
                    693: 	}
                    694:     } 
1.70      www       695:     return %returnhash;
                    696: }
                    697: 
                    698: # ------------------------------------- Find the IDs behind a list of usernames
                    699: 
                    700: sub idrget {
                    701:     my ($udom,@unames)=@_;
                    702:     my %returnhash=();
1.800     albertel  703:     foreach my $uname (@unames) {
                    704:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41  705:     }
1.70      www       706:     return %returnhash;
                    707: }
                    708: 
                    709: # ------------------------------- Store away a list of names and associated IDs
                    710: 
                    711: sub idput {
                    712:     my ($udom,%ids)=@_;
                    713:     my %servers=();
1.800     albertel  714:     foreach my $uname (keys(%ids)) {
                    715: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                    716:         my $uhom=&homeserver($uname,$udom);
1.70      www       717:         if ($uhom ne 'no_host') {
1.800     albertel  718:             my $id=&escape($ids{$uname});
1.70      www       719:             $id=~tr/A-Z/a-z/;
1.800     albertel  720:             my $esc_unam=&escape($uname);
1.70      www       721: 	    if ($servers{$uhom}) {
1.800     albertel  722: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www       723:             } else {
1.800     albertel  724:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www       725:             }
                    726:         }
1.191     harris41  727:     }
1.800     albertel  728:     foreach my $server (keys(%servers)) {
                    729:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41  730:     }
1.344     www       731: }
                    732: 
1.806     raeburn   733: # ------------------------------------------- get items from domain db files   
                    734: 
                    735: sub get_dom {
1.860     raeburn   736:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn   737:     my $items='';
                    738:     foreach my $item (@$storearr) {
                    739:         $items.=&escape($item).'&';
                    740:     }
                    741:     $items=~s/\&$//;
1.860     raeburn   742:     if (!$udom) {
                    743:         $udom=$env{'user.domain'};
                    744:         if (defined(&domain($udom,'primary'))) {
                    745:             $uhome=&domain($udom,'primary');
                    746:         } else {
                    747:             $uhome eq '';
                    748:         }
                    749:     } else {
                    750:         if (!$uhome) {
                    751:             if (defined(&domain($udom,'primary'))) {
                    752:                 $uhome=&domain($udom,'primary');
                    753:             }
                    754:         }
                    755:     }
                    756:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn   757:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn   758:         my %returnhash;
                    759:         if ($rep =~ /^error: 2 /) {
                    760:             return %returnhash;
                    761:         }
1.806     raeburn   762:         my @pairs=split(/\&/,$rep);
                    763:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                    764:             return @pairs;
                    765:         }
                    766:         my %returnhash=();
                    767:         my $i=0;
                    768:         foreach my $item (@$storearr) {
                    769:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                    770:             $i++;
                    771:         }
                    772:         return %returnhash;
                    773:     } else {
1.860     raeburn   774:         &logthis("get_dom failed - no homeserver and/or domain");
1.806     raeburn   775:     }
                    776: }
                    777: 
                    778: # -------------------------------------------- put items in domain db files 
                    779: 
                    780: sub put_dom {
1.860     raeburn   781:     my ($namespace,$storehash,$udom,$uhome)=@_;
                    782:     if (!$udom) {
                    783:         $udom=$env{'user.domain'};
                    784:         if (defined(&domain($udom,'primary'))) {
                    785:             $uhome=&domain($udom,'primary');
                    786:         } else {
                    787:             $uhome eq '';
                    788:         }
                    789:     } else {
                    790:         if (!$uhome) {
                    791:             if (defined(&domain($udom,'primary'))) {
                    792:                 $uhome=&domain($udom,'primary');
                    793:             }
                    794:         }
                    795:     } 
                    796:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn   797:         my $items='';
                    798:         foreach my $item (keys(%$storehash)) {
                    799:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                    800:         }
                    801:         $items=~s/\&$//;
                    802:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                    803:     } else {
1.860     raeburn   804:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn   805:     }
                    806: }
                    807: 
1.837     raeburn   808: sub retrieve_inst_usertypes {
                    809:     my ($udom) = @_;
                    810:     my (%returnhash,@order);
1.846     albertel  811:     if (defined(&domain($udom,'primary'))) {
                    812:         my $uhome=&domain($udom,'primary');
1.837     raeburn   813:         my $rep=&reply("inst_usertypes:$udom",$uhome);
                    814:         my ($hashitems,$orderitems) = split(/:/,$rep); 
                    815:         my @pairs=split(/\&/,$hashitems);
                    816:         foreach my $item (@pairs) {
                    817:             my ($key,$value)=split(/=/,$item,2);
                    818:             $key = &unescape($key);
                    819:             next if ($key =~ /^error: 2 /);
                    820:             $returnhash{$key}=&thaw_unescape($value);
                    821:         }
                    822:         my @esc_order = split(/\&/,$orderitems);
                    823:         foreach my $item (@esc_order) {
                    824:             push(@order,&unescape($item));
                    825:         }
                    826:     } else {
                    827:         &logthis("get_dom failed - no primary domain server for $udom");
                    828:     }
                    829:     return (\%returnhash,\@order);
                    830: }
                    831: 
1.868     raeburn   832: sub is_domainimage {
                    833:     my ($url) = @_;
                    834:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                    835:         if (&domain($1) ne '') {
                    836:             return '1';
                    837:         }
                    838:     }
                    839:     return;
                    840: }
                    841: 
1.344     www       842: # --------------------------------------------------- Assign a key to a student
                    843: 
                    844: sub assign_access_key {
1.364     www       845: #
                    846: # a valid key looks like uname:udom#comments
                    847: # comments are being appended
                    848: #
1.498     www       849:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                    850:     $kdom=
1.620     albertel  851:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www       852:     $knum=
1.620     albertel  853:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www       854:     $cdom=
1.620     albertel  855:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       856:     $cnum=
1.620     albertel  857:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    858:     $udom=$env{'user.name'} unless (defined($udom));
                    859:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www       860:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www       861:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel  862:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www       863:                                                   # assigned to this person
                    864:                                                   # - this should not happen,
1.345     www       865:                                                   # unless something went wrong
                    866:                                                   # the first time around
                    867: # ready to assign
1.364     www       868:         $logentry=$1.'; '.$logentry;
1.496     www       869:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www       870:                                                  $kdom,$knum) eq 'ok') {
1.345     www       871: # key now belongs to user
1.346     www       872: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www       873:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
                    874:                 &appenv('environment.'.$envkey => $ckey);
                    875:                 return 'ok';
                    876:             } else {
                    877:                 return 
                    878:   'error: Count not permanently assign key, will need to be re-entered later.';
                    879: 	    }
                    880:         } else {
                    881:             return 'error: Could not assign key, try again later.';
                    882:         }
1.364     www       883:     } elsif (!$existing{$ckey}) {
1.345     www       884: # the key does not exist
                    885: 	return 'error: The key does not exist';
                    886:     } else {
                    887: # the key is somebody else's
                    888: 	return 'error: The key is already in use';
                    889:     }
1.344     www       890: }
                    891: 
1.364     www       892: # ------------------------------------------ put an additional comment on a key
                    893: 
                    894: sub comment_access_key {
                    895: #
                    896: # a valid key looks like uname:udom#comments
                    897: # comments are being appended
                    898: #
                    899:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                    900:     $cdom=
1.620     albertel  901:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www       902:     $cnum=
1.620     albertel  903:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www       904:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                    905:     if ($existing{$ckey}) {
                    906:         $existing{$ckey}.='; '.$logentry;
                    907: # ready to assign
1.367     www       908:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www       909:                                                  $cdom,$cnum) eq 'ok') {
                    910: 	    return 'ok';
                    911:         } else {
                    912: 	    return 'error: Count not store comment.';
                    913:         }
                    914:     } else {
                    915: # the key does not exist
                    916: 	return 'error: The key does not exist';
                    917:     }
                    918: }
                    919: 
1.344     www       920: # ------------------------------------------------------ Generate a set of keys
                    921: 
                    922: sub generate_access_keys {
1.364     www       923:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www       924:     $cdom=
1.620     albertel  925:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       926:     $cnum=
1.620     albertel  927:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www       928:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www       929:     unless (($cdom) && ($cnum)) { return 0; }
                    930:     if ($number>10000) { return 0; }
                    931:     sleep(2); # make sure don't get same seed twice
                    932:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                    933:     my $total=0;
                    934:     for (my $i=1;$i<=$number;$i++) {
                    935:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                    936:                   sprintf("%lx",int(100000*rand)).'-'.
                    937:                   sprintf("%lx",int(100000*rand));
                    938:        $newkey=~s/1/g/g; # folks mix up 1 and l
                    939:        $newkey=~s/0/h/g; # and also 0 and O
                    940:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                    941:        if ($existing{$newkey}) {
                    942:            $i--;
                    943:        } else {
1.364     www       944: 	  if (&put('accesskeys',
                    945:               { $newkey => '# generated '.localtime().
1.620     albertel  946:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www       947:                            '; '.$logentry },
                    948: 		   $cdom,$cnum) eq 'ok') {
1.344     www       949:               $total++;
                    950: 	  }
                    951:        }
                    952:     }
1.620     albertel  953:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www       954:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                    955:     return $total;
                    956: }
                    957: 
                    958: # ------------------------------------------------------- Validate an accesskey
                    959: 
                    960: sub validate_access_key {
                    961:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                    962:     $cdom=
1.620     albertel  963:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       964:     $cnum=
1.620     albertel  965:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    966:     $udom=$env{'user.domain'} unless (defined($udom));
                    967:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www       968:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel  969:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www       970: }
                    971: 
                    972: # ------------------------------------- Find the section of student in a course
1.652     albertel  973: sub devalidate_getsection_cache {
                    974:     my ($udom,$unam,$courseid)=@_;
                    975:     my $hashid="$udom:$unam:$courseid";
                    976:     &devalidate_cache_new('getsection',$hashid);
                    977: }
1.298     matthew   978: 
1.815     albertel  979: sub courseid_to_courseurl {
                    980:     my ($courseid) = @_;
                    981:     #already url style courseid
                    982:     return $courseid if ($courseid =~ m{^/});
                    983: 
                    984:     if (exists($env{'course.'.$courseid.'.num'})) {
                    985: 	my $cnum = $env{'course.'.$courseid.'.num'};
                    986: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                    987: 	return "/$cdom/$cnum";
                    988:     }
                    989: 
                    990:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                    991:     if (exists($courseinfo{'num'})) {
                    992: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                    993:     }
                    994: 
                    995:     return undef;
                    996: }
                    997: 
1.298     matthew   998: sub getsection {
                    999:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 1000:     my $cachetime=1800;
1.551     albertel 1001: 
                   1002:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 1003:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 1004:     if (defined($cached)) { return $result; }
                   1005: 
1.298     matthew  1006:     my %Pending; 
                   1007:     my %Expired;
                   1008:     #
                   1009:     # Each role can either have not started yet (pending), be active, 
                   1010:     #    or have expired.
                   1011:     #
                   1012:     # If there is an active role, we are done.
                   1013:     #
                   1014:     # If there is more than one role which has not started yet, 
                   1015:     #     choose the one which will start sooner
                   1016:     # If there is one role which has not started yet, return it.
                   1017:     #
                   1018:     # If there is more than one expired role, choose the one which ended last.
                   1019:     # If there is a role which has expired, return it.
                   1020:     #
1.815     albertel 1021:     $courseid = &courseid_to_courseurl($courseid);
1.817     raeburn  1022:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
                   1023:     foreach my $key (keys(%roleshash)) {
1.479     albertel 1024:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  1025:         my $section=$1;
                   1026:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  1027:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  1028:         my $now=time;
1.548     albertel 1029:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  1030:             $Expired{$end}=$section;
                   1031:             next;
                   1032:         }
1.548     albertel 1033:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  1034:             $Pending{$start}=$section;
                   1035:             next;
                   1036:         }
1.599     albertel 1037:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  1038:     }
                   1039:     #
                   1040:     # Presumedly there will be few matching roles from the above
                   1041:     # loop and the sorting time will be negligible.
                   1042:     if (scalar(keys(%Pending))) {
                   1043:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 1044:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  1045:     } 
                   1046:     if (scalar(keys(%Expired))) {
                   1047:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   1048:         my $time = pop(@sorted);
1.599     albertel 1049:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  1050:     }
1.599     albertel 1051:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  1052: }
1.70      www      1053: 
1.599     albertel 1054: sub save_cache {
                   1055:     &purge_remembered();
1.722     albertel 1056:     #&Apache::loncommon::validate_page();
1.620     albertel 1057:     undef(%env);
1.780     albertel 1058:     undef($env_loaded);
1.599     albertel 1059: }
1.452     albertel 1060: 
1.599     albertel 1061: my $to_remember=-1;
                   1062: my %remembered;
                   1063: my %accessed;
                   1064: my $kicks=0;
                   1065: my $hits=0;
1.849     albertel 1066: sub make_key {
                   1067:     my ($name,$id) = @_;
1.872   ! albertel 1068:     if (length($id) > 65 
        !          1069: 	&& length(&escape($id)) > 200) {
        !          1070: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
        !          1071:     }
1.849     albertel 1072:     return &escape($name.':'.$id);
                   1073: }
                   1074: 
1.599     albertel 1075: sub devalidate_cache_new {
                   1076:     my ($name,$id,$debug) = @_;
                   1077:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 1078:     $id=&make_key($name,$id);
1.599     albertel 1079:     $memcache->delete($id);
                   1080:     delete($remembered{$id});
                   1081:     delete($accessed{$id});
                   1082: }
                   1083: 
                   1084: sub is_cached_new {
                   1085:     my ($name,$id,$debug) = @_;
1.849     albertel 1086:     $id=&make_key($name,$id);
1.599     albertel 1087:     if (exists($remembered{$id})) {
                   1088: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                   1089: 	$accessed{$id}=[&gettimeofday()];
                   1090: 	$hits++;
                   1091: 	return ($remembered{$id},1);
                   1092:     }
                   1093:     my $value = $memcache->get($id);
                   1094:     if (!(defined($value))) {
                   1095: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 1096: 	return (undef,undef);
1.416     albertel 1097:     }
1.599     albertel 1098:     if ($value eq '__undef__') {
                   1099: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   1100: 	$value=undef;
                   1101:     }
                   1102:     &make_room($id,$value,$debug);
                   1103:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   1104:     return ($value,1);
                   1105: }
                   1106: 
                   1107: sub do_cache_new {
                   1108:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 1109:     $id=&make_key($name,$id);
1.599     albertel 1110:     my $setvalue=$value;
                   1111:     if (!defined($setvalue)) {
                   1112: 	$setvalue='__undef__';
                   1113:     }
1.623     albertel 1114:     if (!defined($time) ) {
                   1115: 	$time=600;
                   1116:     }
1.599     albertel 1117:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.872   ! albertel 1118:     if (!($memcache->set($id,$setvalue,$time))) {
        !          1119: 	&logthis("caching of id -> $id  failed");
        !          1120:     }
1.600     albertel 1121:     # need to make a copy of $value
                   1122:     #&make_room($id,$value,$debug);
1.599     albertel 1123:     return $value;
                   1124: }
                   1125: 
                   1126: sub make_room {
                   1127:     my ($id,$value,$debug)=@_;
                   1128:     $remembered{$id}=$value;
                   1129:     if ($to_remember<0) { return; }
                   1130:     $accessed{$id}=[&gettimeofday()];
                   1131:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   1132:     my $to_kick;
                   1133:     my $max_time=0;
                   1134:     foreach my $other (keys(%accessed)) {
                   1135: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   1136: 	    $to_kick=$other;
                   1137: 	    $max_time=&tv_interval($accessed{$other});
                   1138: 	}
                   1139:     }
                   1140:     delete($remembered{$to_kick});
                   1141:     delete($accessed{$to_kick});
                   1142:     $kicks++;
                   1143:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 1144:     return;
                   1145: }
                   1146: 
1.599     albertel 1147: sub purge_remembered {
1.604     albertel 1148:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   1149:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 1150:     undef(%remembered);
                   1151:     undef(%accessed);
1.428     albertel 1152: }
1.70      www      1153: # ------------------------------------- Read an entry from a user's environment
                   1154: 
                   1155: sub userenvironment {
                   1156:     my ($udom,$unam,@what)=@_;
                   1157:     my %returnhash=();
                   1158:     my @answer=split(/\&/,
                   1159:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
                   1160:                       &homeserver($unam,$udom)));
                   1161:     my $i;
                   1162:     for ($i=0;$i<=$#what;$i++) {
                   1163: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                   1164:     }
                   1165:     return %returnhash;
1.1       albertel 1166: }
                   1167: 
1.617     albertel 1168: # ---------------------------------------------------------- Get a studentphoto
                   1169: sub studentphoto {
                   1170:     my ($udom,$unam,$ext) = @_;
                   1171:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1172:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1173:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1174:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1175:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1176:             } else {
                   1177:                 my ($result,$perm_reqd)=
1.707     albertel 1178: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1179:                 if ($result eq 'ok') {
                   1180:                     if (!($perm_reqd eq 'yes')) {
                   1181:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1182:                     }
                   1183:                 }
                   1184:             }
                   1185:         }
                   1186:     } else {
                   1187:         my ($result,$perm_reqd) = 
1.707     albertel 1188: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1189:         if ($result eq 'ok') {
                   1190:             if (!($perm_reqd eq 'yes')) {
                   1191:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1192:             }
                   1193:         }
                   1194:     }
                   1195:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1196: }
                   1197: 
                   1198: sub retrievestudentphoto {
                   1199:     my ($udom,$unam,$ext,$type) = @_;
                   1200:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1201:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1202:     if ($ret eq 'ok') {
                   1203:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1204:         if ($type eq 'thumbnail') {
                   1205:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1206:         }
                   1207:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1208:         return $tokenurl;
                   1209:     } else {
                   1210:         if ($type eq 'thumbnail') {
                   1211:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1212:         } else { 
                   1213:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1214:         }
1.617     albertel 1215:     }
                   1216: }
                   1217: 
1.263     www      1218: # -------------------------------------------------------------------- New chat
                   1219: 
                   1220: sub chatsend {
1.724     raeburn  1221:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1222:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1223:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1224:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1225:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1226: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1227: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1228: }
                   1229: 
                   1230: # ------------------------------------------ Find current version of a resource
                   1231: 
                   1232: sub getversion {
                   1233:     my $fname=&clutter(shift);
                   1234:     unless ($fname=~/^\/res\//) { return -1; }
                   1235:     return &currentversion(&filelocation('',$fname));
                   1236: }
                   1237: 
                   1238: sub currentversion {
                   1239:     my $fname=shift;
1.599     albertel 1240:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1241:     if (defined($cached)) { return $result; }
1.292     www      1242:     my $author=$fname;
                   1243:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1244:     my ($udom,$uname)=split(/\//,$author);
                   1245:     my $home=homeserver($uname,$udom);
                   1246:     if ($home eq 'no_host') { 
                   1247:         return -1; 
                   1248:     }
                   1249:     my $answer=reply("currentversion:$fname",$home);
                   1250:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1251: 	return -1;
                   1252:     }
1.599     albertel 1253:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1254: }
                   1255: 
1.1       albertel 1256: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1257: 
1.1       albertel 1258: sub subscribe {
                   1259:     my $fname=shift;
1.761     raeburn  1260:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1261:     $fname=~s/[\n\r]//g;
1.1       albertel 1262:     my $author=$fname;
                   1263:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1264:     my ($udom,$uname)=split(/\//,$author);
                   1265:     my $home=homeserver($uname,$udom);
1.335     albertel 1266:     if ($home eq 'no_host') {
                   1267:         return 'not_found';
1.1       albertel 1268:     }
                   1269:     my $answer=reply("sub:$fname",$home);
1.64      www      1270:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1271: 	$answer.=' by '.$home;
                   1272:     }
1.1       albertel 1273:     return $answer;
                   1274: }
                   1275:     
1.8       www      1276: # -------------------------------------------------------------- Replicate file
                   1277: 
                   1278: sub repcopy {
                   1279:     my $filename=shift;
1.23      www      1280:     $filename=~s/\/+/\//g;
1.607     raeburn  1281:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1282:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1283:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1284: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1285: 	return &repcopy_userfile($filename);
                   1286:     }
1.532     albertel 1287:     $filename=~s/[\n\r]//g;
1.8       www      1288:     my $transname="$filename.in.transfer";
1.828     www      1289: # FIXME: this should flock
1.607     raeburn  1290:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1291:     my $remoteurl=subscribe($filename);
1.64      www      1292:     if ($remoteurl =~ /^con_lost by/) {
                   1293: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1294:            return 'unavailable';
1.8       www      1295:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1296: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1297: 	   return 'not_found';
1.64      www      1298:     } elsif ($remoteurl =~ /^rejected by/) {
                   1299: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1300:            return 'forbidden';
1.20      www      1301:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1302:            return 'ok';
1.8       www      1303:     } else {
1.290     www      1304:         my $author=$filename;
                   1305:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1306:         my ($udom,$uname)=split(/\//,$author);
                   1307:         my $home=homeserver($uname,$udom);
                   1308:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1309:            my @parts=split(/\//,$filename);
                   1310:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1311:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1312:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1313: 	       return 'bad_request';
1.8       www      1314:            }
                   1315:            my $count;
                   1316:            for ($count=5;$count<$#parts;$count++) {
                   1317:                $path.="/$parts[$count]";
                   1318:                if ((-e $path)!=1) {
                   1319: 		   mkdir($path,0777);
                   1320:                }
                   1321:            }
                   1322:            my $ua=new LWP::UserAgent;
                   1323:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1324:            my $response=$ua->request($request,$transname);
                   1325:            if ($response->is_error()) {
                   1326: 	       unlink($transname);
                   1327:                my $message=$response->status_line;
1.672     albertel 1328:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      1329:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1330:                return 'unavailable';
1.8       www      1331:            } else {
1.16      www      1332: 	       if ($remoteurl!~/\.meta$/) {
                   1333:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1334:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1335:                   if ($mresponse->is_error()) {
                   1336: 		      unlink($filename.'.meta');
                   1337:                       &logthis(
1.672     albertel 1338:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      1339:                   }
                   1340: 	       }
1.8       www      1341:                rename($transname,$filename);
1.607     raeburn  1342:                return 'ok';
1.8       www      1343:            }
1.290     www      1344:        }
1.8       www      1345:     }
1.330     www      1346: }
                   1347: 
                   1348: # ------------------------------------------------ Get server side include body
                   1349: sub ssi_body {
1.381     albertel 1350:     my ($filelink,%form)=@_;
1.606     matthew  1351:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1352:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1353:     }
1.330     www      1354:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
1.381     albertel 1355:                                      &ssi($filelink,%form));
1.778     albertel 1356:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1357:     $output=~s/^.*?\<body[^\>]*\>//si;
                   1358:     $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
1.330     www      1359:     return $output;
1.8       www      1360: }
                   1361: 
1.15      www      1362: # --------------------------------------------------------- Server Side Include
                   1363: 
1.782     albertel 1364: sub absolute_url {
                   1365:     my ($host_name) = @_;
                   1366:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   1367:     if ($host_name eq '') {
                   1368: 	$host_name = $ENV{'SERVER_NAME'};
                   1369:     }
                   1370:     return $protocol.$host_name;
                   1371: }
                   1372: 
1.15      www      1373: sub ssi {
                   1374: 
1.23      www      1375:     my ($fn,%form)=@_;
1.15      www      1376: 
                   1377:     my $ua=new LWP::UserAgent;
1.23      www      1378:     
                   1379:     my $request;
1.711     albertel 1380: 
                   1381:     $form{'no_update_last_known'}=1;
                   1382: 
1.23      www      1383:     if (%form) {
1.782     albertel 1384:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.201     albertel 1385:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www      1386:     } else {
1.782     albertel 1387:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      1388:     }
                   1389: 
1.15      www      1390:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1391:     my $response=$ua->request($request);
                   1392: 
1.324     www      1393:     return $response->content;
                   1394: }
                   1395: 
                   1396: sub externalssi {
                   1397:     my ($url)=@_;
                   1398:     my $ua=new LWP::UserAgent;
                   1399:     my $request=new HTTP::Request('GET',$url);
                   1400:     my $response=$ua->request($request);
1.15      www      1401:     return $response->content;
                   1402: }
1.254     www      1403: 
1.492     albertel 1404: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1405: 
                   1406: sub allowuploaded {
                   1407:     my ($srcurl,$url)=@_;
                   1408:     $url=&clutter(&declutter($url));
                   1409:     my $dir=$url;
                   1410:     $dir=~s/\/[^\/]+$//;
                   1411:     my %httpref=();
                   1412:     my $httpurl=&hreflocation('',$url);
                   1413:     $httpref{'httpref.'.$httpurl}=$srcurl;
                   1414:     &Apache::lonnet::appenv(%httpref);
1.254     www      1415: }
1.477     raeburn  1416: 
1.478     albertel 1417: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 1418: # input: action, courseID, current domain, intended
1.637     raeburn  1419: #        path to file, source of file, instruction to parse file for objects,
                   1420: #        ref to hash for embedded objects,
                   1421: #        ref to hash for codebase of java objects.
                   1422: #
1.485     raeburn  1423: # output: url to file (if action was uploaddoc), 
                   1424: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  1425: #
1.478     albertel 1426: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   1427: # course.
1.477     raeburn  1428: #
1.478     albertel 1429: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1430: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   1431: #          course's home server.
1.477     raeburn  1432: #
1.478     albertel 1433: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   1434: #          be copied from $source (current location) to 
                   1435: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1436: #         and will then be copied to
                   1437: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   1438: #         course's home server.
1.485     raeburn  1439: #
1.481     raeburn  1440: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 1441: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  1442: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1443: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   1444: #         in course's home server.
1.637     raeburn  1445: #
1.477     raeburn  1446: 
                   1447: sub process_coursefile {
1.638     albertel 1448:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  1449:     my $fetchresult;
1.638     albertel 1450:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  1451:     if ($action eq 'propagate') {
1.638     albertel 1452:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1453: 			     $home);
1.481     raeburn  1454:     } else {
1.477     raeburn  1455:         my $fpath = '';
                   1456:         my $fname = $file;
1.478     albertel 1457:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  1458:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  1459:         my $filepath = &build_filepath($fpath);
1.481     raeburn  1460:         if ($action eq 'copy') {
                   1461:             if ($source eq '') {
                   1462:                 $fetchresult = 'no source file';
                   1463:                 return $fetchresult;
                   1464:             } else {
                   1465:                 my $destination = $filepath.'/'.$fname;
                   1466:                 rename($source,$destination);
                   1467:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1468:                                  $home);
1.481     raeburn  1469:             }
                   1470:         } elsif ($action eq 'uploaddoc') {
                   1471:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 1472:             print $fh $env{'form.'.$source};
1.481     raeburn  1473:             close($fh);
1.637     raeburn  1474:             if ($parser eq 'parse') {
                   1475:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
                   1476:                 unless ($parse_result eq 'ok') {
                   1477:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   1478:                 }
                   1479:             }
1.477     raeburn  1480:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1481:                                  $home);
1.481     raeburn  1482:             if ($fetchresult eq 'ok') {
                   1483:                 return '/uploaded/'.$fpath.'/'.$fname;
                   1484:             } else {
                   1485:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1486:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  1487:                 return '/adm/notfound.html';
                   1488:             }
1.477     raeburn  1489:         }
                   1490:     }
1.485     raeburn  1491:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  1492:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1493:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  1494:     }
                   1495:     return $fetchresult;
                   1496: }
                   1497: 
1.637     raeburn  1498: sub build_filepath {
                   1499:     my ($fpath) = @_;
                   1500:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   1501:     unless ($fpath eq '') {
                   1502:         my @parts=split('/',$fpath);
                   1503:         foreach my $part (@parts) {
                   1504:             $filepath.= '/'.$part;
                   1505:             if ((-e $filepath)!=1) {
                   1506:                 mkdir($filepath,0777);
                   1507:             }
                   1508:         }
                   1509:     }
                   1510:     return $filepath;
                   1511: }
                   1512: 
                   1513: sub store_edited_file {
1.638     albertel 1514:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  1515:     my $file = $primary_url;
                   1516:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   1517:     my $fpath = '';
                   1518:     my $fname = $file;
                   1519:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   1520:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   1521:     my $filepath = &build_filepath($fpath);
                   1522:     open(my $fh,'>'.$filepath.'/'.$fname);
                   1523:     print $fh $content;
                   1524:     close($fh);
1.638     albertel 1525:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  1526:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1527: 			  $home);
1.637     raeburn  1528:     if ($$fetchresult eq 'ok') {
                   1529:         return '/uploaded/'.$fpath.'/'.$fname;
                   1530:     } else {
1.638     albertel 1531:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   1532: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  1533:         return '/adm/notfound.html';
                   1534:     }
                   1535: }
                   1536: 
1.531     albertel 1537: sub clean_filename {
1.831     albertel 1538:     my ($fname,$args)=@_;
1.315     www      1539: # Replace Windows backslashes by forward slashes
1.257     www      1540:     $fname=~s/\\/\//g;
1.831     albertel 1541:     if (!$args->{'keep_path'}) {
                   1542:         # Get rid of everything but the actual filename
                   1543: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   1544:     }
1.315     www      1545: # Replace spaces by underscores
                   1546:     $fname=~s/\s+/\_/g;
                   1547: # Replace all other weird characters by nothing
1.831     albertel 1548:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 1549: # Replace all .\d. sequences with _\d. so they no longer look like version
                   1550: # numbers
                   1551:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 1552:     return $fname;
                   1553: }
                   1554: 
1.608     albertel 1555: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 1556: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 1557: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 1558: #        $coursedoc - if true up to the current course
                   1559: #                     if false
                   1560: #        $subdir - directory in userfile to store the file into
1.858     raeburn  1561: #        $parser - instruction to parse file for objects ($parser = parse)    
                   1562: #        $allfiles - reference to hash for embedded objects
                   1563: #        $codebase - reference to hash for codebase of java objects
                   1564: #        $desuname - username for permanent storage of uploaded file
                   1565: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  1566: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   1567: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.858     raeburn  1568: # 
1.686     albertel 1569: # output: url of file in userspace, or error: <message> 
                   1570: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 1571: 
                   1572: 
1.531     albertel 1573: sub userfileupload {
1.860     raeburn  1574:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
                   1575:         $destudom,$thumbwidth,$thumbheight)=@_;
1.531     albertel 1576:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 1577:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 1578:     $fname=&clean_filename($fname);
1.315     www      1579: # See if there is anything left
1.257     www      1580:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 1581:     chop($env{'form.'.$formname});
1.523     raeburn  1582:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   1583:         my $now = time;
                   1584:         my $filepath = 'tmp/helprequests/'.$now;
                   1585:         my @parts=split(/\//,$filepath);
                   1586:         my $fullpath = $perlvar{'lonDaemons'};
                   1587:         for (my $i=0;$i<@parts;$i++) {
                   1588:             $fullpath .= '/'.$parts[$i];
                   1589:             if ((-e $fullpath)!=1) {
                   1590:                 mkdir($fullpath,0777);
                   1591:             }
                   1592:         }
                   1593:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 1594:         print $fh $env{'form.'.$formname};
1.523     raeburn  1595:         close($fh);
1.741     raeburn  1596:         return $fullpath.'/'.$fname;
                   1597:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   1598:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   1599:                        '_'.$env{'user.domain'}.'/pending';
                   1600:         my @parts=split(/\//,$filepath);
                   1601:         my $fullpath = $perlvar{'lonDaemons'};
                   1602:         for (my $i=0;$i<@parts;$i++) {
                   1603:             $fullpath .= '/'.$parts[$i];
                   1604:             if ((-e $fullpath)!=1) {
                   1605:                 mkdir($fullpath,0777);
                   1606:             }
                   1607:         }
                   1608:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   1609:         print $fh $env{'form.'.$formname};
                   1610:         close($fh);
                   1611:         return $fullpath.'/'.$fname;
1.523     raeburn  1612:     }
1.719     banghart 1613:     
1.258     www      1614: # Create the directory if not present
1.493     albertel 1615:     $fname="$subdir/$fname";
1.259     www      1616:     if ($coursedoc) {
1.638     albertel 1617: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1618: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  1619:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 1620:             return &finishuserfileupload($docuname,$docudom,
                   1621: 					 $formname,$fname,$parser,$allfiles,
1.860     raeburn  1622: 					 $codebase,$thumbwidth,$thumbheight);
1.481     raeburn  1623:         } else {
1.620     albertel 1624:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 1625:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   1626: 				       $fname,$formname,$parser,
                   1627: 				       $allfiles,$codebase);
1.481     raeburn  1628:         }
1.719     banghart 1629:     } elsif (defined($destuname)) {
                   1630:         my $docuname=$destuname;
                   1631:         my $docudom=$destudom;
1.860     raeburn  1632: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   1633: 				     $parser,$allfiles,$codebase,
                   1634:                                      $thumbwidth,$thumbheight);
1.719     banghart 1635:         
1.259     www      1636:     } else {
1.638     albertel 1637:         my $docuname=$env{'user.name'};
                   1638:         my $docudom=$env{'user.domain'};
1.714     raeburn  1639:         if (exists($env{'form.group'})) {
                   1640:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1641:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1642:         }
1.860     raeburn  1643: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   1644: 				     $parser,$allfiles,$codebase,
                   1645:                                      $thumbwidth,$thumbheight);
1.259     www      1646:     }
1.271     www      1647: }
                   1648: 
                   1649: sub finishuserfileupload {
1.860     raeburn  1650:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
                   1651:         $thumbwidth,$thumbheight) = @_;
1.477     raeburn  1652:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      1653:     my $filepath=$perlvar{'lonDocRoot'};
1.860     raeburn  1654:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 1655:     $file=$fname;
                   1656:     if ($fname=~m|/|) {
                   1657:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   1658: 	$path.=$fnamepath.'/';
                   1659:     }
1.259     www      1660:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      1661:     my $count;
                   1662:     for ($count=4;$count<=$#parts;$count++) {
                   1663:         $filepath.="/$parts[$count]";
                   1664:         if ((-e $filepath)!=1) {
                   1665: 	    mkdir($filepath,0777);
                   1666:         }
                   1667:     }
                   1668: # Save the file
                   1669:     {
1.701     albertel 1670: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   1671: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   1672: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   1673: 	    return '/adm/notfound.html';
                   1674: 	}
                   1675: 	if (!print FH ($env{'form.'.$formname})) {
                   1676: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   1677: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   1678: 	    return '/adm/notfound.html';
                   1679: 	}
1.570     albertel 1680: 	close(FH);
1.258     www      1681:     }
1.637     raeburn  1682:     if ($parser eq 'parse') {
1.638     albertel 1683:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
                   1684: 						   $codebase);
1.637     raeburn  1685:         unless ($parse_result eq 'ok') {
1.638     albertel 1686:             &logthis('Failed to parse '.$filepath.$file.
                   1687: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  1688:         }
                   1689:     }
1.860     raeburn  1690:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   1691:         my $input = $filepath.'/'.$file;
                   1692:         my $output = $filepath.'/'.'tn-'.$file;
                   1693:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   1694:         system("convert -sample $thumbsize $input $output");
                   1695:         if (-e $filepath.'/'.'tn-'.$file) {
                   1696:             $fetchthumb  = 1; 
                   1697:         }
                   1698:     }
1.858     raeburn  1699:  
1.259     www      1700: # Notify homeserver to grep it
                   1701: #
1.638     albertel 1702:     my $docuhome=&homeserver($docuname,$docudom);
1.494     albertel 1703:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      1704:     if ($fetchresult eq 'ok') {
1.860     raeburn  1705:         if ($fetchthumb) {
                   1706:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   1707:             if ($thumbresult ne 'ok') {
                   1708:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   1709:                          $docuhome.': '.$thumbresult);
                   1710:             }
                   1711:         }
1.259     www      1712: #
1.258     www      1713: # Return the URL to it
1.494     albertel 1714:         return '/uploaded/'.$path.$file;
1.263     www      1715:     } else {
1.494     albertel 1716:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   1717: 		 ': '.$fetchresult);
1.263     www      1718:         return '/adm/notfound.html';
1.858     raeburn  1719:     }
1.493     albertel 1720: }
                   1721: 
1.637     raeburn  1722: sub extract_embedded_items {
1.648     raeburn  1723:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
1.637     raeburn  1724:     my @state = ();
                   1725:     my %javafiles = (
                   1726:                       codebase => '',
                   1727:                       code => '',
                   1728:                       archive => ''
                   1729:                     );
                   1730:     my %mediafiles = (
                   1731:                       src => '',
                   1732:                       movie => '',
                   1733:                      );
1.648     raeburn  1734:     my $p;
                   1735:     if ($content) {
                   1736:         $p = HTML::LCParser->new($content);
                   1737:     } else {
                   1738:         $p = HTML::LCParser->new($filepath.'/'.$file);
                   1739:     }
1.641     albertel 1740:     while (my $t=$p->get_token()) {
1.640     albertel 1741: 	if ($t->[0] eq 'S') {
                   1742: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
                   1743: 	    push (@state, $tagname);
1.648     raeburn  1744:             if (lc($tagname) eq 'allow') {
                   1745:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   1746:             }
1.640     albertel 1747: 	    if (lc($tagname) eq 'img') {
                   1748: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   1749: 	    }
1.645     raeburn  1750:             if (lc($tagname) eq 'script') {
                   1751:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   1752:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   1753:                 } else {
                   1754:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   1755:                 }
                   1756:             }
                   1757:             if (lc($tagname) eq 'link') {
                   1758:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   1759:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   1760:                 }
                   1761:             }
1.640     albertel 1762: 	    if (lc($tagname) eq 'object' ||
                   1763: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   1764: 		foreach my $item (keys(%javafiles)) {
                   1765: 		    $javafiles{$item} = '';
                   1766: 		}
                   1767: 	    }
                   1768: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   1769: 		my $name = lc($attr->{'name'});
                   1770: 		foreach my $item (keys(%javafiles)) {
                   1771: 		    if ($name eq $item) {
                   1772: 			$javafiles{$item} = $attr->{'value'};
                   1773: 			last;
                   1774: 		    }
                   1775: 		}
                   1776: 		foreach my $item (keys(%mediafiles)) {
                   1777: 		    if ($name eq $item) {
                   1778: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   1779: 			last;
                   1780: 		    }
                   1781: 		}
                   1782: 	    }
                   1783: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   1784: 		foreach my $item (keys(%javafiles)) {
                   1785: 		    if ($attr->{$item}) {
                   1786: 			$javafiles{$item} = $attr->{$item};
                   1787: 			last;
                   1788: 		    }
                   1789: 		}
                   1790: 		foreach my $item (keys(%mediafiles)) {
                   1791: 		    if ($attr->{$item}) {
                   1792: 			&add_filetype($allfiles,$attr->{$item},$item);
                   1793: 			last;
                   1794: 		    }
                   1795: 		}
                   1796: 	    }
                   1797: 	} elsif ($t->[0] eq 'E') {
                   1798: 	    my ($tagname) = ($t->[1]);
                   1799: 	    if ($javafiles{'codebase'} ne '') {
                   1800: 		$javafiles{'codebase'} .= '/';
                   1801: 	    }  
                   1802: 	    if (lc($tagname) eq 'applet' ||
                   1803: 		lc($tagname) eq 'object' ||
                   1804: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   1805: 		) {
                   1806: 		foreach my $item (keys(%javafiles)) {
                   1807: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   1808: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   1809: 			&add_filetype($allfiles,$file,$item);
                   1810: 		    }
                   1811: 		}
                   1812: 	    } 
                   1813: 	    pop @state;
                   1814: 	}
                   1815:     }
1.637     raeburn  1816:     return 'ok';
                   1817: }
                   1818: 
1.639     albertel 1819: sub add_filetype {
                   1820:     my ($allfiles,$file,$type)=@_;
                   1821:     if (exists($allfiles->{$file})) {
                   1822: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   1823: 	    push(@{$allfiles->{$file}}, &escape($type));
                   1824: 	}
                   1825:     } else {
                   1826: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  1827:     }
                   1828: }
                   1829: 
1.493     albertel 1830: sub removeuploadedurl {
                   1831:     my ($url)=@_;
                   1832:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613     albertel 1833:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 1834: }
                   1835: 
                   1836: sub removeuserfile {
                   1837:     my ($docuname,$docudom,$fname)=@_;
                   1838:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  1839:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
                   1840:     if ($result eq 'ok') {
                   1841:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   1842:             my $metafile = $fname.'.meta';
                   1843:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 1844: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
                   1845:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  1846:             my $sqlresult = 
1.823     albertel 1847:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  1848:                                         'portfolio_metadata',$group,
                   1849:                                         'delete');
1.798     raeburn  1850:         }
                   1851:     }
                   1852:     return $result;
1.257     www      1853: }
1.15      www      1854: 
1.530     albertel 1855: sub mkdiruserfile {
                   1856:     my ($docuname,$docudom,$dir)=@_;
                   1857:     my $home=&homeserver($docuname,$docudom);
                   1858:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   1859: }
                   1860: 
1.531     albertel 1861: sub renameuserfile {
                   1862:     my ($docuname,$docudom,$old,$new)=@_;
                   1863:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  1864:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   1865:                         &escape("$old").':'.&escape("$new"),$home);
                   1866:     if ($result eq 'ok') {
                   1867:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   1868:             my $oldmeta = $old.'.meta';
                   1869:             my $newmeta = $new.'.meta';
                   1870:             my $metaresult = 
                   1871:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 1872: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   1873:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  1874:             my $sqlresult = 
1.823     albertel 1875:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  1876:                                         'portfolio_metadata',$group,
                   1877:                                         'delete');
1.798     raeburn  1878:         }
                   1879:     }
                   1880:     return $result;
1.531     albertel 1881: }
                   1882: 
1.14      www      1883: # ------------------------------------------------------------------------- Log
                   1884: 
                   1885: sub log {
                   1886:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      1887:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      1888: }
                   1889: 
                   1890: # ------------------------------------------------------------------ Course Log
1.352     www      1891: #
                   1892: # This routine flushes several buffers of non-mission-critical nature
                   1893: #
1.157     www      1894: 
                   1895: sub flushcourselogs {
1.352     www      1896:     &logthis('Flushing log buffers');
                   1897: #
                   1898: # course logs
                   1899: # This is a log of all transactions in a course, which can be used
                   1900: # for data mining purposes
                   1901: #
                   1902: # It also collects the courseid database, which lists last transaction
                   1903: # times and course titles for all courseids
                   1904: #
                   1905:     my %courseidbuffer=();
1.800     albertel 1906:     foreach my $crsid (keys %courselogs) {
1.352     www      1907:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      1908: 		          &escape($courselogs{$crsid}),
                   1909: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      1910: 	    delete $courselogs{$crsid};
                   1911:         } else {
                   1912:             &logthis('Failed to flush log buffer for '.$crsid);
                   1913:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 1914:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      1915:                         " exceeded maximum size, deleting.</font>");
                   1916:                delete $courselogs{$crsid};
                   1917:             }
1.352     www      1918:         }
                   1919:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
                   1920:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
1.516     raeburn  1921: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  1922:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.352     www      1923:         } else {
                   1924:            $courseidbuffer{$coursehombuf{$crsid}}=
1.516     raeburn  1925: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  1926:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.571     raeburn  1927:         }
1.191     harris41 1928:     }
1.352     www      1929: #
                   1930: # Write course id database (reverse lookup) to homeserver of courses 
                   1931: # Is used in pickcourse
                   1932: #
1.840     albertel 1933:     foreach my $crs_home (keys(%courseidbuffer)) {
1.844     albertel 1934:         &courseidput(&host_domain($crs_home),$courseidbuffer{$crs_home},
1.840     albertel 1935: 		     $crs_home);
1.352     www      1936:     }
                   1937: #
                   1938: # File accesses
                   1939: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   1940: #
1.449     matthew  1941:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  1942:         if ($entry =~ /___count$/) {
                   1943:             my ($dom,$name);
1.807     albertel 1944:             ($dom,$name,undef)=
1.811     albertel 1945: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  1946:             if (! defined($dom) || $dom eq '' || 
                   1947:                 ! defined($name) || $name eq '') {
1.620     albertel 1948:                 my $cid = $env{'request.course.id'};
                   1949:                 $dom  = $env{'request.'.$cid.'.domain'};
                   1950:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  1951:             }
1.450     matthew  1952:             my $value = $accesshash{$entry};
                   1953:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   1954:             my %temphash=($url => $value);
1.449     matthew  1955:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   1956:             if ($result eq 'ok') {
                   1957:                 delete $accesshash{$entry};
                   1958:             } elsif ($result eq 'unknown_cmd') {
                   1959:                 # Target server has old code running on it.
1.450     matthew  1960:                 my %temphash=($entry => $value);
1.449     matthew  1961:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1962:                     delete $accesshash{$entry};
                   1963:                 }
                   1964:             }
                   1965:         } else {
1.811     albertel 1966:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  1967:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  1968:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1969:                 delete $accesshash{$entry};
                   1970:             }
1.185     www      1971:         }
1.191     harris41 1972:     }
1.352     www      1973: #
                   1974: # Roles
                   1975: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   1976: #
1.800     albertel 1977:     foreach my $entry (keys(%userrolehash)) {
1.351     www      1978:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      1979: 	    split(/\:/,$entry);
                   1980:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      1981:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      1982:                 $rudom,$runame) eq 'ok') {
                   1983: 	    delete $userrolehash{$entry};
                   1984:         }
                   1985:     }
1.662     raeburn  1986: #
                   1987: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   1988: #
                   1989:     my %domrolebuffer = ();
                   1990:     foreach my $entry (keys %domainrolehash) {
                   1991:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split/:/,$entry;
                   1992:         if ($domrolebuffer{$rudom}) {
                   1993:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   1994:                       '='.&escape($domainrolehash{$entry});
                   1995:         } else {
                   1996:             $domrolebuffer{$rudom}.=&escape($entry).
                   1997:                       '='.&escape($domainrolehash{$entry});
                   1998:         }
                   1999:         delete $domainrolehash{$entry};
                   2000:     }
                   2001:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 2002: 	my %servers = &get_servers($dom,'library');
                   2003: 	foreach my $tryserver (keys(%servers)) {
                   2004: 	    unless (&reply('domroleput:'.$dom.':'.
                   2005: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   2006: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   2007: 	    }
1.662     raeburn  2008:         }
                   2009:     }
1.186     www      2010:     $dumpcount++;
1.157     www      2011: }
                   2012: 
                   2013: sub courselog {
                   2014:     my $what=shift;
1.158     www      2015:     $what=time.':'.$what;
1.620     albertel 2016:     unless ($env{'request.course.id'}) { return ''; }
                   2017:     $coursedombuf{$env{'request.course.id'}}=
                   2018:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2019:     $coursenumbuf{$env{'request.course.id'}}=
                   2020:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   2021:     $coursehombuf{$env{'request.course.id'}}=
                   2022:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   2023:     $coursedescrbuf{$env{'request.course.id'}}=
                   2024:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   2025:     $courseinstcodebuf{$env{'request.course.id'}}=
                   2026:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   2027:     $courseownerbuf{$env{'request.course.id'}}=
                   2028:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  2029:     $coursetypebuf{$env{'request.course.id'}}=
                   2030:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 2031:     if (defined $courselogs{$env{'request.course.id'}}) {
                   2032: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      2033:     } else {
1.620     albertel 2034: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      2035:     }
1.620     albertel 2036:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      2037: 	&flushcourselogs();
                   2038:     }
1.158     www      2039: }
                   2040: 
                   2041: sub courseacclog {
                   2042:     my $fnsymb=shift;
1.620     albertel 2043:     unless ($env{'request.course.id'}) { return ''; }
                   2044:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 2045:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      2046:         $what.=':POST';
1.583     matthew  2047:         # FIXME: Probably ought to escape things....
1.800     albertel 2048: 	foreach my $key (keys(%env)) {
                   2049:             if ($key=~/^form\.(.*)/) {
                   2050: 		$what.=':'.$1.'='.$env{$key};
1.158     www      2051:             }
1.191     harris41 2052:         }
1.583     matthew  2053:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   2054:         # FIXME: We should not be depending on a form parameter that someone
                   2055:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 2056:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  2057:             $what.= ':POST';
                   2058:             # FIXME: Probably ought to escape things....
                   2059:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   2060:                                  'crsdiscuss') {
1.620     albertel 2061:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  2062:             }
                   2063:         }
1.158     www      2064:     }
                   2065:     &courselog($what);
1.149     www      2066: }
                   2067: 
1.185     www      2068: sub countacc {
                   2069:     my $url=&declutter(shift);
1.458     matthew  2070:     return if (! defined($url) || $url eq '');
1.620     albertel 2071:     unless ($env{'request.course.id'}) { return ''; }
                   2072:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      2073:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  2074:     $accesshash{$key}++;
1.185     www      2075: }
1.349     www      2076: 
1.361     www      2077: sub linklog {
                   2078:     my ($from,$to)=@_;
                   2079:     $from=&declutter($from);
                   2080:     $to=&declutter($to);
                   2081:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   2082:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   2083: }
                   2084:   
1.349     www      2085: sub userrolelog {
                   2086:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  2087:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  2088:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  2089:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   2090:         ($trole=~/^ta/)) {
1.350     www      2091:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2092:        $userrolehash
                   2093:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      2094:                     =$tend.':'.$tstart;
1.662     raeburn  2095:     }
                   2096:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   2097:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   2098:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   2099:         ($trole=~/^sc/)) {
                   2100:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2101:        $domainrolehash
                   2102:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   2103:                     = $tend.':'.$tstart;
                   2104:     }
1.351     www      2105: }
                   2106: 
                   2107: sub get_course_adv_roles {
                   2108:     my $cid=shift;
1.620     albertel 2109:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      2110:     my %coursehash=&coursedescription($cid);
1.470     www      2111:     my %nothide=();
1.800     albertel 2112:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2113: 	$nothide{join(':',split(/[\@\:]/,$user))}=1;
1.470     www      2114:     }
1.351     www      2115:     my %returnhash=();
                   2116:     my %dumphash=
                   2117:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   2118:     my $now=time;
1.800     albertel 2119:     foreach my $entry (keys %dumphash) {
                   2120: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      2121:         if (($tstart) && ($tstart<0)) { next; }
                   2122:         if (($tend) && ($tend<$now)) { next; }
                   2123:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 2124:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 2125: 	if ($username eq '' || $domain eq '') { next; }
1.470     www      2126: 	if ((&privileged($username,$domain)) && 
                   2127: 	    (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 2128: 	if ($role eq 'cr') { next; }
1.351     www      2129:         my $key=&plaintext($role);
                   2130:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
                   2131:         if ($returnhash{$key}) {
                   2132: 	    $returnhash{$key}.=','.$username.':'.$domain;
                   2133:         } else {
                   2134:             $returnhash{$key}=$username.':'.$domain;
                   2135:         }
1.400     www      2136:      }
                   2137:     return %returnhash;
                   2138: }
                   2139: 
                   2140: sub get_my_roles {
1.858     raeburn  2141:     my ($uname,$udom,$context,$types,$roles,$roledoms)=@_;
1.620     albertel 2142:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   2143:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.858     raeburn  2144:     my %dumphash;
                   2145:     if ($context eq 'userroles') { 
                   2146:         %dumphash = &dump('roles',$udom,$uname);
                   2147:     } else {
                   2148:         %dumphash=
1.400     www      2149:             &dump('nohist_userroles',$udom,$uname);
1.858     raeburn  2150:     }
1.400     www      2151:     my %returnhash=();
                   2152:     my $now=time;
1.800     albertel 2153:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  2154:         my ($role,$tend,$tstart);
                   2155:         if ($context eq 'userroles') {
                   2156: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   2157:         } else {
                   2158:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   2159:         }
1.400     www      2160:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  2161:         my $status = 'active';
                   2162:         if (($tend) && ($tend<$now)) {
                   2163:             $status = 'previous';
                   2164:         } 
                   2165:         if (($tstart) && ($now<$tstart)) {
                   2166:             $status = 'future';
                   2167:         }
                   2168:         if (ref($types) eq 'ARRAY') {
                   2169:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   2170:                 next;
                   2171:             } 
                   2172:         } else {
                   2173:             if ($status ne 'active') {
                   2174:                 next;
                   2175:             }
                   2176:         }
1.867     raeburn  2177:         my ($rolecode,$username,$domain,$section,$area);
                   2178:         if ($context eq 'userroles') {
                   2179:             ($area,$rolecode) = split(/_/,$entry);
                   2180:             (undef,$domain,$username,$section) = split(/\//,$area);
                   2181:         } else {
                   2182:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   2183:         }
1.832     raeburn  2184:         if (ref($roledoms) eq 'ARRAY') {
                   2185:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   2186:                 next;
                   2187:             }
                   2188:         }
                   2189:         if (ref($roles) eq 'ARRAY') {
                   2190:             if (!grep(/^\Q$role\E$/,@{$roles})) {
                   2191:                 next;
                   2192:             }
1.867     raeburn  2193:         }
1.400     www      2194: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
1.832     raeburn  2195:     }
1.373     www      2196:     return %returnhash;
1.399     www      2197: }
                   2198: 
                   2199: # ----------------------------------------------------- Frontpage Announcements
                   2200: #
                   2201: #
                   2202: 
                   2203: sub postannounce {
                   2204:     my ($server,$text)=@_;
1.844     albertel 2205:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      2206:     unless ($text=~/\w/) { $text=''; }
                   2207:     return &reply('setannounce:'.&escape($text),$server);
                   2208: }
                   2209: 
                   2210: sub getannounce {
1.448     albertel 2211: 
                   2212:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      2213: 	my $announcement='';
1.800     albertel 2214: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 2215: 	close($fh);
1.399     www      2216: 	if ($announcement=~/\w/) { 
                   2217: 	    return 
                   2218:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 2219:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      2220: 	} else {
                   2221: 	    return '';
                   2222: 	}
                   2223:     } else {
                   2224: 	return '';
                   2225:     }
1.351     www      2226: }
1.353     www      2227: 
                   2228: # ---------------------------------------------------------- Course ID routines
                   2229: # Deal with domain's nohist_courseid.db files
                   2230: #
                   2231: 
                   2232: sub courseidput {
                   2233:     my ($domain,$what,$coursehome)=@_;
                   2234:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   2235: }
                   2236: 
                   2237: sub courseiddump {
1.791     raeburn  2238:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok)=@_;
1.353     www      2239:     my %returnhash=();
1.355     www      2240:     unless ($domfilter) { $domfilter=''; }
1.845     albertel 2241:     my %libserv = &all_library();
                   2242:     foreach my $tryserver (keys(%libserv)) {
                   2243:         if ( (  $hostidflag == 1 
                   2244: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   2245: 	     || (!defined($hostidflag)) ) {
                   2246: 
                   2247: 	    if ($domfilter eq ''
                   2248: 		|| (&host_domain($tryserver) eq $domfilter)) {
1.800     albertel 2249: 	        foreach my $line (
1.844     albertel 2250:                  split(/\&/,&reply('courseiddump:'.&host_domain($tryserver).':'.
1.571     raeburn  2251: 			       $sincefilter.':'.&escape($descfilter).':'.
1.791     raeburn  2252:                                &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter).':'.&escape($typefilter).':'.&escape($regexp_ok),
1.354     www      2253:                                $tryserver))) {
1.800     albertel 2254: 		    my ($key,$value)=split(/\=/,$line,2);
1.506     raeburn  2255:                     if (($key) && ($value)) {
1.516     raeburn  2256: 		        $returnhash{&unescape($key)}=$value;
1.506     raeburn  2257:                     }
1.353     www      2258:                 }
                   2259:             }
                   2260:         }
                   2261:     }
                   2262:     return %returnhash;
                   2263: }
                   2264: 
1.658     raeburn  2265: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  2266: 
                   2267: sub dcmailput {
1.685     raeburn  2268:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  2269:     my $status = &Apache::lonnet::critical(
1.740     www      2270:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   2271:        &escape($message),$server);
1.662     raeburn  2272:     return $status;
                   2273: }
                   2274: 
1.658     raeburn  2275: sub dcmaildump {
                   2276:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  2277:     my %returnhash=();
1.846     albertel 2278: 
                   2279:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  2280:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   2281:                                                          &escape($enddate).':';
                   2282: 	my @esc_senders=map { &escape($_)} @$senders;
                   2283: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 2284: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 2285:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  2286:             if (($key) && ($value)) {
                   2287:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  2288:             }
                   2289:         }
                   2290:     }
                   2291:     return %returnhash;
                   2292: }
1.662     raeburn  2293: # ---------------------------------------------------------- Domain roles
                   2294: 
                   2295: sub get_domain_roles {
                   2296:     my ($dom,$roles,$startdate,$enddate)=@_;
                   2297:     if (undef($startdate) || $startdate eq '') {
                   2298:         $startdate = '.';
                   2299:     }
                   2300:     if (undef($enddate) || $enddate eq '') {
                   2301:         $enddate = '.';
                   2302:     }
                   2303:     my $rolelist = join(':',@{$roles});
                   2304:     my %personnel = ();
1.841     albertel 2305: 
                   2306:     my %servers = &get_servers($dom,'library');
                   2307:     foreach my $tryserver (keys(%servers)) {
                   2308: 	%{$personnel{$tryserver}}=();
                   2309: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   2310: 					    &escape($startdate).':'.
                   2311: 					    &escape($enddate).':'.
                   2312: 					    &escape($rolelist), $tryserver))) {
                   2313: 	    my ($key,$value) = split(/\=/,$line,2);
                   2314: 	    if (($key) && ($value)) {
                   2315: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   2316: 	    }
                   2317: 	}
1.662     raeburn  2318:     }
                   2319:     return %personnel;
                   2320: }
1.658     raeburn  2321: 
1.149     www      2322: # ----------------------------------------------------------- Check out an item
                   2323: 
1.504     albertel 2324: sub get_first_access {
                   2325:     my ($type,$argsymb)=@_;
1.790     albertel 2326:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2327:     if ($argsymb) { $symb=$argsymb; }
                   2328:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2329:     if ($type eq 'map') {
                   2330: 	$res=&symbread($map);
                   2331:     } else {
                   2332: 	$res=$symb;
                   2333:     }
                   2334:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   2335:     return $times{"$courseid\0$res"};
1.504     albertel 2336: }
                   2337: 
                   2338: sub set_first_access {
                   2339:     my ($type)=@_;
1.790     albertel 2340:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2341:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2342:     if ($type eq 'map') {
                   2343: 	$res=&symbread($map);
                   2344:     } else {
                   2345: 	$res=$symb;
                   2346:     }
                   2347:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 2348:     if (!$firstaccess) {
1.588     albertel 2349: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 2350:     }
                   2351:     return 'already_set';
1.504     albertel 2352: }
                   2353: 
1.149     www      2354: sub checkout {
                   2355:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   2356:     my $now=time;
                   2357:     my $lonhost=$perlvar{'lonHostID'};
                   2358:     my $infostr=&escape(
1.234     www      2359:                  'CHECKOUTTOKEN&'.
1.149     www      2360:                  $tuname.'&'.
                   2361:                  $tudom.'&'.
                   2362:                  $tcrsid.'&'.
                   2363:                  $symb.'&'.
                   2364: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   2365:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      2366:     if ($token=~/^error\:/) { 
1.672     albertel 2367:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2368:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2369:                  "</font>");
                   2370:         return ''; 
                   2371:     }
                   2372: 
1.149     www      2373:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   2374:     $token=~tr/a-z/A-Z/;
                   2375: 
1.153     www      2376:     my %infohash=('resource.0.outtoken' => $token,
                   2377:                   'resource.0.checkouttime' => $now,
                   2378:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      2379: 
                   2380:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2381:        return '';
1.151     www      2382:     } else {
1.672     albertel 2383:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2384:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2385:                  "</font>");
1.149     www      2386:     }    
                   2387: 
                   2388:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2389:                          &escape('Checkout '.$infostr.' - '.
                   2390:                                                  $token)) ne 'ok') {
                   2391: 	return '';
1.151     www      2392:     } else {
1.672     albertel 2393:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2394:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2395:                  "</font>");
1.149     www      2396:     }
1.151     www      2397:     return $token;
1.149     www      2398: }
                   2399: 
                   2400: # ------------------------------------------------------------ Check in an item
                   2401: 
                   2402: sub checkin {
                   2403:     my $token=shift;
1.150     www      2404:     my $now=time;
                   2405:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   2406:     $lonhost=~tr/A-Z/a-z/;
1.838     albertel 2407:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150     www      2408:     $dtoken=~s/\W/\_/g;
1.234     www      2409:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      2410:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   2411: 
1.154     www      2412:     unless (($tuname) && ($tudom)) {
                   2413:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   2414:         return '';
                   2415:     }
                   2416:     
                   2417:     unless (&allowed('mgr',$tcrsid)) {
                   2418:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 2419:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      2420:         return '';
                   2421:     }
                   2422: 
1.153     www      2423:     my %infohash=('resource.0.intoken' => $token,
                   2424:                   'resource.0.checkintime' => $now,
                   2425:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      2426: 
                   2427:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2428:        return '';
                   2429:     }    
                   2430: 
                   2431:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2432:                          &escape('Checkin - '.$token)) ne 'ok') {
                   2433: 	return '';
                   2434:     }
                   2435: 
                   2436:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      2437: }
                   2438: 
                   2439: # --------------------------------------------- Set Expire Date for Spreadsheet
                   2440: 
                   2441: sub expirespread {
                   2442:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 2443:     my $cid=$env{'request.course.id'}; 
1.110     www      2444:     if ($cid) {
                   2445:        my $now=time;
                   2446:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 2447:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   2448:                             $env{'course.'.$cid.'.num'}.
1.110     www      2449: 	        	    ':nohist_expirationdates:'.
                   2450:                             &escape($key).'='.$now,
1.620     albertel 2451:                             $env{'course.'.$cid.'.home'})
1.110     www      2452:     }
                   2453:     return 'ok';
1.14      www      2454: }
                   2455: 
1.109     www      2456: # ----------------------------------------------------- Devalidate Spreadsheets
                   2457: 
                   2458: sub devalidate {
1.325     www      2459:     my ($symb,$uname,$udom)=@_;
1.620     albertel 2460:     my $cid=$env{'request.course.id'}; 
1.109     www      2461:     if ($cid) {
1.391     matthew  2462:         # delete the stored spreadsheets for
                   2463:         # - the student level sheet of this user in course's homespace
                   2464:         # - the assessment level sheet for this resource 
                   2465:         #   for this user in user's homespace
1.553     albertel 2466: 	# - current conditional state info
1.325     www      2467: 	my $key=$uname.':'.$udom.':';
1.109     www      2468:         my $status=
1.299     matthew  2469: 	    &del('nohist_calculatedsheets',
1.391     matthew  2470: 		 [$key.'studentcalc:'],
1.620     albertel 2471: 		 $env{'course.'.$cid.'.domain'},
                   2472: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 2473: 		.' '.
                   2474: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  2475: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      2476:         unless ($status eq 'ok ok') {
                   2477:            &logthis('Could not devalidate spreadsheet '.
1.325     www      2478:                     $uname.' at '.$udom.' for '.
1.109     www      2479: 		    $symb.': '.$status);
1.133     albertel 2480:         }
1.553     albertel 2481: 	&delenv('user.state.'.$cid);
1.109     www      2482:     }
                   2483: }
                   2484: 
1.265     albertel 2485: sub get_scalar {
                   2486:     my ($string,$end) = @_;
                   2487:     my $value;
                   2488:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   2489: 	$value = $1;
                   2490:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   2491: 	$value = $1;
                   2492:     }
                   2493:     return &unescape($value);
                   2494: }
                   2495: 
                   2496: sub array2str {
                   2497:   my (@array) = @_;
                   2498:   my $result=&arrayref2str(\@array);
                   2499:   $result=~s/^__ARRAY_REF__//;
                   2500:   $result=~s/__END_ARRAY_REF__$//;
                   2501:   return $result;
                   2502: }
                   2503: 
1.204     albertel 2504: sub arrayref2str {
                   2505:   my ($arrayref) = @_;
1.265     albertel 2506:   my $result='__ARRAY_REF__';
1.204     albertel 2507:   foreach my $elem (@$arrayref) {
1.265     albertel 2508:     if(ref($elem) eq 'ARRAY') {
                   2509:       $result.=&arrayref2str($elem).'&';
                   2510:     } elsif(ref($elem) eq 'HASH') {
                   2511:       $result.=&hashref2str($elem).'&';
                   2512:     } elsif(ref($elem)) {
                   2513:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 2514:     } else {
                   2515:       $result.=&escape($elem).'&';
                   2516:     }
                   2517:   }
                   2518:   $result=~s/\&$//;
1.265     albertel 2519:   $result .= '__END_ARRAY_REF__';
1.204     albertel 2520:   return $result;
                   2521: }
                   2522: 
1.168     albertel 2523: sub hash2str {
1.204     albertel 2524:   my (%hash) = @_;
                   2525:   my $result=&hashref2str(\%hash);
1.265     albertel 2526:   $result=~s/^__HASH_REF__//;
                   2527:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 2528:   return $result;
                   2529: }
                   2530: 
                   2531: sub hashref2str {
                   2532:   my ($hashref)=@_;
1.265     albertel 2533:   my $result='__HASH_REF__';
1.800     albertel 2534:   foreach my $key (sort(keys(%$hashref))) {
                   2535:     if (ref($key) eq 'ARRAY') {
                   2536:       $result.=&arrayref2str($key).'=';
                   2537:     } elsif (ref($key) eq 'HASH') {
                   2538:       $result.=&hashref2str($key).'=';
                   2539:     } elsif (ref($key)) {
1.265     albertel 2540:       $result.='=';
1.800     albertel 2541:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 2542:     } else {
1.800     albertel 2543: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 2544:     }
                   2545: 
1.800     albertel 2546:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   2547:       $result.=&arrayref2str($hashref->{$key}).'&';
                   2548:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   2549:       $result.=&hashref2str($hashref->{$key}).'&';
                   2550:     } elsif(ref($hashref->{$key})) {
1.265     albertel 2551:        $result.='&';
1.800     albertel 2552:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 2553:     } else {
1.800     albertel 2554:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 2555:     }
                   2556:   }
1.168     albertel 2557:   $result=~s/\&$//;
1.265     albertel 2558:   $result .= '__END_HASH_REF__';
1.168     albertel 2559:   return $result;
                   2560: }
                   2561: 
                   2562: sub str2hash {
1.265     albertel 2563:     my ($string)=@_;
                   2564:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   2565:     return %$hash;
                   2566: }
                   2567: 
                   2568: sub str2hashref {
1.168     albertel 2569:   my ($string) = @_;
1.265     albertel 2570: 
                   2571:   my %hash;
                   2572: 
                   2573:   if($string !~ /^__HASH_REF__/) {
                   2574:       if (! ($string eq '' || !defined($string))) {
                   2575: 	  $hash{'error'}='Not hash reference';
                   2576:       }
                   2577:       return (\%hash, $string);
                   2578:   }
                   2579: 
                   2580:   $string =~ s/^__HASH_REF__//;
                   2581: 
                   2582:   while($string !~ /^__END_HASH_REF__/) {
                   2583:       #key
                   2584:       my $key='';
                   2585:       if($string =~ /^__HASH_REF__/) {
                   2586:           ($key, $string)=&str2hashref($string);
                   2587:           if(defined($key->{'error'})) {
                   2588:               $hash{'error'}='Bad data';
                   2589:               return (\%hash, $string);
                   2590:           }
                   2591:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2592:           ($key, $string)=&str2arrayref($string);
                   2593:           if($key->[0] eq 'Array reference error') {
                   2594:               $hash{'error'}='Bad data';
                   2595:               return (\%hash, $string);
                   2596:           }
                   2597:       } else {
                   2598:           $string =~ s/^(.*?)=//;
1.267     albertel 2599: 	  $key=&unescape($1);
1.265     albertel 2600:       }
                   2601:       $string =~ s/^=//;
                   2602: 
                   2603:       #value
                   2604:       my $value='';
                   2605:       if($string =~ /^__HASH_REF__/) {
                   2606:           ($value, $string)=&str2hashref($string);
                   2607:           if(defined($value->{'error'})) {
                   2608:               $hash{'error'}='Bad data';
                   2609:               return (\%hash, $string);
                   2610:           }
                   2611:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2612:           ($value, $string)=&str2arrayref($string);
                   2613:           if($value->[0] eq 'Array reference error') {
                   2614:               $hash{'error'}='Bad data';
                   2615:               return (\%hash, $string);
                   2616:           }
                   2617:       } else {
                   2618: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   2619:       }
                   2620:       $string =~ s/^&//;
                   2621: 
                   2622:       $hash{$key}=$value;
1.204     albertel 2623:   }
1.265     albertel 2624: 
                   2625:   $string =~ s/^__END_HASH_REF__//;
                   2626: 
                   2627:   return (\%hash, $string);
1.204     albertel 2628: }
                   2629: 
                   2630: sub str2array {
1.265     albertel 2631:     my ($string)=@_;
                   2632:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   2633:     return @$array;
                   2634: }
                   2635: 
                   2636: sub str2arrayref {
1.204     albertel 2637:   my ($string) = @_;
1.265     albertel 2638:   my @array;
                   2639: 
                   2640:   if($string !~ /^__ARRAY_REF__/) {
                   2641:       if (! ($string eq '' || !defined($string))) {
                   2642: 	  $array[0]='Array reference error';
                   2643:       }
                   2644:       return (\@array, $string);
                   2645:   }
                   2646: 
                   2647:   $string =~ s/^__ARRAY_REF__//;
                   2648: 
                   2649:   while($string !~ /^__END_ARRAY_REF__/) {
                   2650:       my $value='';
                   2651:       if($string =~ /^__HASH_REF__/) {
                   2652:           ($value, $string)=&str2hashref($string);
                   2653:           if(defined($value->{'error'})) {
                   2654:               $array[0] ='Array reference error';
                   2655:               return (\@array, $string);
                   2656:           }
                   2657:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2658:           ($value, $string)=&str2arrayref($string);
                   2659:           if($value->[0] eq 'Array reference error') {
                   2660:               $array[0] ='Array reference error';
                   2661:               return (\@array, $string);
                   2662:           }
                   2663:       } else {
                   2664: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   2665:       }
                   2666:       $string =~ s/^&//;
                   2667: 
                   2668:       push(@array, $value);
1.191     harris41 2669:   }
1.265     albertel 2670: 
                   2671:   $string =~ s/^__END_ARRAY_REF__//;
                   2672: 
                   2673:   return (\@array, $string);
1.168     albertel 2674: }
                   2675: 
1.167     albertel 2676: # -------------------------------------------------------------------Temp Store
                   2677: 
1.168     albertel 2678: sub tmpreset {
                   2679:   my ($symb,$namespace,$domain,$stuname) = @_;
                   2680:   if (!$symb) {
                   2681:     $symb=&symbread();
1.620     albertel 2682:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2683:   }
                   2684:   $symb=escape($symb);
                   2685: 
1.620     albertel 2686:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 2687:   $namespace=~s/\//\_/g;
                   2688:   $namespace=~s/\W//g;
                   2689: 
1.620     albertel 2690:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2691:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2692:   if ($domain eq 'public' && $stuname eq 'public') {
                   2693:       $stuname=$ENV{'REMOTE_ADDR'};
                   2694:   }
1.168     albertel 2695:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2696:   my %hash;
                   2697:   if (tie(%hash,'GDBM_File',
                   2698: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2699: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2700:     foreach my $key (keys %hash) {
1.180     albertel 2701:       if ($key=~ /:$symb/) {
1.168     albertel 2702: 	delete($hash{$key});
                   2703:       }
                   2704:     }
                   2705:   }
                   2706: }
                   2707: 
1.167     albertel 2708: sub tmpstore {
1.168     albertel 2709:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2710: 
                   2711:   if (!$symb) {
                   2712:     $symb=&symbread();
1.620     albertel 2713:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2714:   }
                   2715:   $symb=escape($symb);
                   2716: 
                   2717:   if (!$namespace) {
                   2718:     # I don't think we would ever want to store this for a course.
                   2719:     # it seems this will only be used if we don't have a course.
1.620     albertel 2720:     #$namespace=$env{'request.course.id'};
1.168     albertel 2721:     #if (!$namespace) {
1.620     albertel 2722:       $namespace=$env{'request.state'};
1.168     albertel 2723:     #}
                   2724:   }
                   2725:   $namespace=~s/\//\_/g;
                   2726:   $namespace=~s/\W//g;
1.620     albertel 2727:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2728:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2729:   if ($domain eq 'public' && $stuname eq 'public') {
                   2730:       $stuname=$ENV{'REMOTE_ADDR'};
                   2731:   }
1.168     albertel 2732:   my $now=time;
                   2733:   my %hash;
                   2734:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2735:   if (tie(%hash,'GDBM_File',
                   2736: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2737: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2738:     $hash{"version:$symb"}++;
                   2739:     my $version=$hash{"version:$symb"};
                   2740:     my $allkeys=''; 
                   2741:     foreach my $key (keys(%$storehash)) {
                   2742:       $allkeys.=$key.':';
1.591     albertel 2743:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 2744:     }
                   2745:     $hash{"$version:$symb:timestamp"}=$now;
                   2746:     $allkeys.='timestamp';
                   2747:     $hash{"$version:keys:$symb"}=$allkeys;
                   2748:     if (untie(%hash)) {
                   2749:       return 'ok';
                   2750:     } else {
                   2751:       return "error:$!";
                   2752:     }
                   2753:   } else {
                   2754:     return "error:$!";
                   2755:   }
                   2756: }
1.167     albertel 2757: 
1.168     albertel 2758: # -----------------------------------------------------------------Temp Restore
1.167     albertel 2759: 
1.168     albertel 2760: sub tmprestore {
                   2761:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 2762: 
1.168     albertel 2763:   if (!$symb) {
                   2764:     $symb=&symbread();
1.620     albertel 2765:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2766:   }
                   2767:   $symb=escape($symb);
                   2768: 
1.620     albertel 2769:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 2770: 
1.620     albertel 2771:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2772:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2773:   if ($domain eq 'public' && $stuname eq 'public') {
                   2774:       $stuname=$ENV{'REMOTE_ADDR'};
                   2775:   }
1.168     albertel 2776:   my %returnhash;
                   2777:   $namespace=~s/\//\_/g;
                   2778:   $namespace=~s/\W//g;
                   2779:   my %hash;
                   2780:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2781:   if (tie(%hash,'GDBM_File',
                   2782: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2783: 	  &GDBM_READER(),0640)) {
1.168     albertel 2784:     my $version=$hash{"version:$symb"};
                   2785:     $returnhash{'version'}=$version;
                   2786:     my $scope;
                   2787:     for ($scope=1;$scope<=$version;$scope++) {
                   2788:       my $vkeys=$hash{"$scope:keys:$symb"};
                   2789:       my @keys=split(/:/,$vkeys);
                   2790:       my $key;
                   2791:       $returnhash{"$scope:keys"}=$vkeys;
                   2792:       foreach $key (@keys) {
1.591     albertel 2793: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   2794: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 2795:       }
                   2796:     }
1.168     albertel 2797:     if (!(untie(%hash))) {
                   2798:       return "error:$!";
                   2799:     }
                   2800:   } else {
                   2801:     return "error:$!";
                   2802:   }
                   2803:   return %returnhash;
1.167     albertel 2804: }
                   2805: 
1.9       www      2806: # ----------------------------------------------------------------------- Store
                   2807: 
                   2808: sub store {
1.124     www      2809:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2810:     my $home='';
                   2811: 
1.168     albertel 2812:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2813: 
1.213     www      2814:     $symb=&symbclean($symb);
1.122     albertel 2815:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2816: 
1.620     albertel 2817:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2818:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2819: 
                   2820:     &devalidate($symb,$stuname,$domain);
1.109     www      2821: 
                   2822:     $symb=escape($symb);
1.187     www      2823:     if (!$namespace) { 
1.620     albertel 2824:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2825:           return ''; 
                   2826:        } 
                   2827:     }
1.620     albertel 2828:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2829: 
                   2830:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2831:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   2832: 
1.12      www      2833:     my $namevalue='';
1.800     albertel 2834:     foreach my $key (keys(%$storehash)) {
                   2835:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 2836:     }
1.12      www      2837:     $namevalue=~s/\&$//;
1.187     www      2838:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      2839:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      2840: }
                   2841: 
1.47      www      2842: # -------------------------------------------------------------- Critical Store
                   2843: 
                   2844: sub cstore {
1.124     www      2845:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2846:     my $home='';
                   2847: 
1.168     albertel 2848:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2849: 
1.213     www      2850:     $symb=&symbclean($symb);
1.122     albertel 2851:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2852: 
1.620     albertel 2853:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2854:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2855: 
                   2856:     &devalidate($symb,$stuname,$domain);
1.109     www      2857: 
                   2858:     $symb=escape($symb);
1.187     www      2859:     if (!$namespace) { 
1.620     albertel 2860:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2861:           return ''; 
                   2862:        } 
                   2863:     }
1.620     albertel 2864:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2865: 
                   2866:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2867:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 2868: 
1.47      www      2869:     my $namevalue='';
1.800     albertel 2870:     foreach my $key (keys(%$storehash)) {
                   2871:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 2872:     }
1.47      www      2873:     $namevalue=~s/\&$//;
1.187     www      2874:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      2875:     return critical
                   2876:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      2877: }
                   2878: 
1.9       www      2879: # --------------------------------------------------------------------- Restore
                   2880: 
                   2881: sub restore {
1.124     www      2882:     my ($symb,$namespace,$domain,$stuname) = @_;
                   2883:     my $home='';
                   2884: 
1.168     albertel 2885:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2886: 
1.122     albertel 2887:     if (!$symb) {
                   2888:       unless ($symb=escape(&symbread())) { return ''; }
                   2889:     } else {
1.213     www      2890:       $symb=&escape(&symbclean($symb));
1.122     albertel 2891:     }
1.188     www      2892:     if (!$namespace) { 
1.620     albertel 2893:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      2894:           return ''; 
                   2895:        } 
                   2896:     }
1.620     albertel 2897:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2898:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   2899:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 2900:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   2901: 
1.12      www      2902:     my %returnhash=();
1.800     albertel 2903:     foreach my $line (split(/\&/,$answer)) {
                   2904: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 2905:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 2906:     }
1.75      www      2907:     my $version;
                   2908:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 2909:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   2910:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 2911:        }
1.75      www      2912:     }
1.13      www      2913:     return %returnhash;
1.34      www      2914: }
                   2915: 
                   2916: # ---------------------------------------------------------- Course Description
                   2917: 
                   2918: sub coursedescription {
1.731     albertel 2919:     my ($courseid,$args)=@_;
1.34      www      2920:     $courseid=~s/^\///;
1.49      www      2921:     $courseid=~s/\_/\//g;
1.34      www      2922:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 2923:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 2924:     my $normalid=$cdomain.'_'.$cnum;
                   2925:     # need to always cache even if we get errors otherwise we keep 
                   2926:     # trying and trying and trying to get the course description.
                   2927:     my %envhash=();
                   2928:     my %returnhash=();
1.731     albertel 2929:     
                   2930:     my $expiretime=600;
                   2931:     if ($env{'request.course.id'} eq $normalid) {
                   2932: 	$expiretime=120;
                   2933:     }
                   2934: 
                   2935:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   2936:     if (!$args->{'freshen_cache'}
                   2937: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   2938: 	foreach my $key (keys(%env)) {
                   2939: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   2940: 	    my ($setting) = $1;
                   2941: 	    $returnhash{$setting} = $env{$key};
                   2942: 	}
                   2943: 	return %returnhash;
                   2944:     }
                   2945: 
                   2946:     # get the data agin
                   2947:     if (!$args->{'one_time'}) {
                   2948: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   2949:     }
1.811     albertel 2950: 
1.34      www      2951:     if ($chome ne 'no_host') {
1.302     albertel 2952:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 2953:        if (!exists($returnhash{'con_lost'})) {
                   2954:            $returnhash{'home'}= $chome;
                   2955: 	   $returnhash{'domain'} = $cdomain;
                   2956: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  2957:            if (!defined($returnhash{'type'})) {
                   2958:                $returnhash{'type'} = 'Course';
                   2959:            }
1.130     albertel 2960:            while (my ($name,$value) = each %returnhash) {
1.53      www      2961:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 2962:            }
1.270     www      2963:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      2964:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 2965: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      2966:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   2967:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   2968:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      2969:        }
                   2970:     }
1.731     albertel 2971:     if (!$args->{'one_time'}) {
                   2972: 	&appenv(%envhash);
                   2973:     }
1.302     albertel 2974:     return %returnhash;
1.461     www      2975: }
                   2976: 
                   2977: # -------------------------------------------------See if a user is privileged
                   2978: 
                   2979: sub privileged {
                   2980:     my ($username,$domain)=@_;
                   2981:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   2982: 			&homeserver($username,$domain));
                   2983:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   2984:     my $now=time;
                   2985:     if ($rolesdump ne '') {
1.800     albertel 2986:         foreach my $entry (split(/&/,$rolesdump)) {
                   2987: 	    if ($entry!~/^rolesdef_/) {
                   2988: 		my ($area,$role)=split(/=/,$entry);
1.461     www      2989: 		$area=~s/\_\w\w$//;
                   2990: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   2991: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   2992: 		    my $active=1;
                   2993: 		    if ($tend) {
                   2994: 			if ($tend<$now) { $active=0; }
                   2995: 		    }
                   2996: 		    if ($tstart) {
                   2997: 			if ($tstart>$now) { $active=0; }
                   2998: 		    }
                   2999: 		    if ($active) { return 1; }
                   3000: 		}
                   3001: 	    }
                   3002: 	}
                   3003:     }
                   3004:     return 0;
1.9       www      3005: }
1.1       albertel 3006: 
1.103     harris41 3007: # -------------------------------------------------------- Get user privileges
1.11      www      3008: 
                   3009: sub rolesinit {
                   3010:     my ($domain,$username,$authhost)=@_;
                   3011:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12      www      3012:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11      www      3013:     my %allroles=();
1.678     raeburn  3014:     my %allgroups=();   
1.11      www      3015:     my $now=time;
1.743     albertel 3016:     my %userroles = ('user.login.time' => $now);
1.678     raeburn  3017:     my $group_privs;
1.11      www      3018: 
                   3019:     if ($rolesdump ne '') {
1.800     albertel 3020:         foreach my $entry (split(/&/,$rolesdump)) {
                   3021: 	  if ($entry!~/^rolesdef_/) {
                   3022:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 3023: 	    $area=~s/\_\w\w$//;
1.678     raeburn  3024:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 3025: 	    if ($role=~/^cr/) { 
1.807     albertel 3026: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   3027: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 3028: 		    ($tend,$tstart)=split('_',$trest);
                   3029: 		} else {
                   3030: 		    $trole=$role;
                   3031: 		}
1.678     raeburn  3032:             } elsif ($role =~ m|^gr/|) {
                   3033:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   3034:                 ($trole,$group_privs) = split(/\//,$trole);
                   3035:                 $group_privs = &unescape($group_privs);
1.587     albertel 3036: 	    } else {
                   3037: 		($trole,$tend,$tstart)=split(/_/,$role);
                   3038: 	    }
1.743     albertel 3039: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   3040: 					 $username);
                   3041: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  3042:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   3043:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      3044:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 3045: 		my $spec=$trole.'.'.$area;
                   3046: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   3047: 		if ($trole =~ /^cr\//) {
1.567     raeburn  3048:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  3049:                 } elsif ($trole eq 'gr') {
                   3050:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 3051: 		} else {
1.567     raeburn  3052:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 3053: 		}
1.12      www      3054:             }
1.662     raeburn  3055:           }
1.191     harris41 3056:         }
1.743     albertel 3057:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   3058:         $userroles{'user.adv'}    = $adv;
                   3059: 	$userroles{'user.author'} = $author;
1.620     albertel 3060:         $env{'user.adv'}=$adv;
1.11      www      3061:     }
1.743     albertel 3062:     return \%userroles;  
1.11      www      3063: }
                   3064: 
1.567     raeburn  3065: sub set_arearole {
                   3066:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   3067: # log the associated role with the area
                   3068:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 3069:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  3070: }
                   3071: 
                   3072: sub custom_roleprivs {
                   3073:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   3074:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   3075:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 3076:     if (&hostname($homsvr) ne '') {
1.567     raeburn  3077:         my ($rdummy,$roledef)=
                   3078:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   3079:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   3080:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   3081:             if (defined($syspriv)) {
                   3082:                 $$allroles{'cm./'}.=':'.$syspriv;
                   3083:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   3084:             }
                   3085:             if ($tdomain ne '') {
                   3086:                 if (defined($dompriv)) {
                   3087:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   3088:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   3089:                 }
                   3090:                 if (($trest ne '') && (defined($coursepriv))) {
                   3091:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   3092:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   3093:                 }
                   3094:             }
                   3095:         }
                   3096:     }
                   3097: }
                   3098: 
1.678     raeburn  3099: sub group_roleprivs {
                   3100:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   3101:     my $access = 1;
                   3102:     my $now = time;
                   3103:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   3104:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   3105:     if ($access) {
1.811     albertel 3106:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  3107:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   3108:     }
                   3109: }
1.567     raeburn  3110: 
                   3111: sub standard_roleprivs {
                   3112:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   3113:     if (defined($pr{$trole.':s'})) {
                   3114:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   3115:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   3116:     }
                   3117:     if ($tdomain ne '') {
                   3118:         if (defined($pr{$trole.':d'})) {
                   3119:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3120:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3121:         }
                   3122:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   3123:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   3124:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   3125:         }
                   3126:     }
                   3127: }
                   3128: 
                   3129: sub set_userprivs {
1.678     raeburn  3130:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  3131:     my $author=0;
                   3132:     my $adv=0;
1.678     raeburn  3133:     my %grouproles = ();
                   3134:     if (keys(%{$allgroups}) > 0) {
                   3135:         foreach my $role (keys %{$allroles}) {
1.681     raeburn  3136:             my ($trole,$area,$sec,$extendedarea);
1.811     albertel 3137:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)-) {
1.678     raeburn  3138:                 $trole = $1;
                   3139:                 $area = $2;
1.681     raeburn  3140:                 $sec = $3;
                   3141:                 $extendedarea = $area.$sec;
                   3142:                 if (exists($$allgroups{$area})) {
                   3143:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   3144:                         my $spec = $trole.'.'.$extendedarea;
                   3145:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   3146:                                                 $$allgroups{$area}{$group};
1.678     raeburn  3147:                     }
                   3148:                 }
                   3149:             }
                   3150:         }
                   3151:     }
1.800     albertel 3152:     foreach my $group (keys(%grouproles)) {
                   3153:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  3154:     }
1.800     albertel 3155:     foreach my $role (keys(%{$allroles})) {
                   3156:         my %thesepriv;
                   3157:         if (($role=~/^au/) || ($role=~/^ca/)) { $author=1; }
                   3158:         foreach my $item (split(/:/,$$allroles{$role})) {
                   3159:             if ($item ne '') {
                   3160:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  3161:                 if ($restrictions eq '') {
                   3162:                     $thesepriv{$privilege}='F';
                   3163:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   3164:                     $thesepriv{$privilege}.=$restrictions;
                   3165:                 }
                   3166:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   3167:             }
                   3168:         }
                   3169:         my $thesestr='';
1.800     albertel 3170:         foreach my $priv (keys(%thesepriv)) {
                   3171: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   3172: 	}
                   3173:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  3174:     }
                   3175:     return ($author,$adv);
                   3176: }
                   3177: 
1.12      www      3178: # --------------------------------------------------------------- get interface
                   3179: 
                   3180: sub get {
1.131     albertel 3181:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3182:    my $items='';
1.800     albertel 3183:    foreach my $item (@$storearr) {
                   3184:        $items.=&escape($item).'&';
1.191     harris41 3185:    }
1.12      www      3186:    $items=~s/\&$//;
1.620     albertel 3187:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3188:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 3189:    my $uhome=&homeserver($uname,$udomain);
                   3190: 
1.133     albertel 3191:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3192:    my @pairs=split(/\&/,$rep);
1.273     albertel 3193:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   3194:      return @pairs;
                   3195:    }
1.15      www      3196:    my %returnhash=();
1.42      www      3197:    my $i=0;
1.800     albertel 3198:    foreach my $item (@$storearr) {
                   3199:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3200:       $i++;
1.191     harris41 3201:    }
1.15      www      3202:    return %returnhash;
1.27      www      3203: }
                   3204: 
                   3205: # --------------------------------------------------------------- del interface
                   3206: 
                   3207: sub del {
1.133     albertel 3208:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      3209:    my $items='';
1.800     albertel 3210:    foreach my $item (@$storearr) {
                   3211:        $items.=&escape($item).'&';
1.191     harris41 3212:    }
1.27      www      3213:    $items=~s/\&$//;
1.620     albertel 3214:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3215:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3216:    my $uhome=&homeserver($uname,$udomain);
                   3217: 
                   3218:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3219: }
                   3220: 
                   3221: # -------------------------------------------------------------- dump interface
                   3222: 
                   3223: sub dump {
1.755     albertel 3224:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   3225:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3226:     if (!$uname) { $uname=$env{'user.name'}; }
                   3227:     my $uhome=&homeserver($uname,$udomain);
                   3228:     if ($regexp) {
                   3229: 	$regexp=&escape($regexp);
                   3230:     } else {
                   3231: 	$regexp='.';
                   3232:     }
                   3233:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3234:     my @pairs=split(/\&/,$rep);
                   3235:     my %returnhash=();
                   3236:     foreach my $item (@pairs) {
                   3237: 	my ($key,$value)=split(/=/,$item,2);
                   3238: 	$key = &unescape($key);
                   3239: 	next if ($key =~ /^error: 2 /);
                   3240: 	$returnhash{$key}=&thaw_unescape($value);
                   3241:     }
                   3242:     return %returnhash;
1.407     www      3243: }
                   3244: 
1.717     albertel 3245: # --------------------------------------------------------- dumpstore interface
                   3246: 
                   3247: sub dumpstore {
                   3248:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 3249:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3250:    if (!$uname) { $uname=$env{'user.name'}; }
                   3251:    my $uhome=&homeserver($uname,$udomain);
                   3252:    if ($regexp) {
                   3253:        $regexp=&escape($regexp);
                   3254:    } else {
                   3255:        $regexp='.';
                   3256:    }
                   3257:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3258:    my @pairs=split(/\&/,$rep);
                   3259:    my %returnhash=();
                   3260:    foreach my $item (@pairs) {
                   3261:        my ($key,$value)=split(/=/,$item,2);
                   3262:        next if ($key =~ /^error: 2 /);
                   3263:        $returnhash{$key}=&thaw_unescape($value);
                   3264:    }
                   3265:    return %returnhash;
1.717     albertel 3266: }
                   3267: 
1.407     www      3268: # -------------------------------------------------------------- keys interface
                   3269: 
                   3270: sub getkeys {
                   3271:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 3272:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3273:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      3274:    my $uhome=&homeserver($uname,$udomain);
                   3275:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   3276:    my @keyarray=();
1.800     albertel 3277:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  3278:       next if ($key =~ /^error: 2 /);
1.800     albertel 3279:       push(@keyarray,&unescape($key));
1.407     www      3280:    }
                   3281:    return @keyarray;
1.318     matthew  3282: }
                   3283: 
1.319     matthew  3284: # --------------------------------------------------------------- currentdump
                   3285: sub currentdump {
1.328     matthew  3286:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 3287:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   3288:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   3289:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  3290:    my $uhome = &homeserver($sname,$sdom);
                   3291:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  3292:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  3293:    #
1.318     matthew  3294:    my %returnhash=();
1.319     matthew  3295:    #
                   3296:    if ($rep eq "unknown_cmd") { 
                   3297:        # an old lond will not know currentdump
                   3298:        # Do a dump and make it look like a currentdump
1.822     albertel 3299:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  3300:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   3301:        my %hash = @tmp;
                   3302:        @tmp=();
1.424     matthew  3303:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  3304:    } else {
                   3305:        my @pairs=split(/\&/,$rep);
1.800     albertel 3306:        foreach my $pair (@pairs) {
                   3307:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  3308:            my ($symb,$param) = split(/:/,$key);
                   3309:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 3310:                                                         &thaw_unescape($value);
1.319     matthew  3311:        }
1.191     harris41 3312:    }
1.12      www      3313:    return %returnhash;
1.424     matthew  3314: }
                   3315: 
                   3316: sub convert_dump_to_currentdump{
                   3317:     my %hash = %{shift()};
                   3318:     my %returnhash;
                   3319:     # Code ripped from lond, essentially.  The only difference
                   3320:     # here is the unescaping done by lonnet::dump().  Conceivably
                   3321:     # we might run in to problems with parameter names =~ /^v\./
                   3322:     while (my ($key,$value) = each(%hash)) {
                   3323:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 3324: 	$symb  = &unescape($symb);
                   3325: 	$param = &unescape($param);
1.424     matthew  3326:         next if ($v eq 'version' || $symb eq 'keys');
                   3327:         next if (exists($returnhash{$symb}) &&
                   3328:                  exists($returnhash{$symb}->{$param}) &&
                   3329:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   3330:         $returnhash{$symb}->{$param}=$value;
                   3331:         $returnhash{$symb}->{'v.'.$param}=$v;
                   3332:     }
                   3333:     #
                   3334:     # Remove all of the keys in the hashes which keep track of
                   3335:     # the version of the parameter.
                   3336:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   3337:         # use a foreach because we are going to delete from the hash.
                   3338:         foreach my $key (keys(%$param_hash)) {
                   3339:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   3340:         }
                   3341:     }
                   3342:     return \%returnhash;
1.12      www      3343: }
                   3344: 
1.627     albertel 3345: # ------------------------------------------------------ critical inc interface
                   3346: 
                   3347: sub cinc {
                   3348:     return &inc(@_,'critical');
                   3349: }
                   3350: 
1.449     matthew  3351: # --------------------------------------------------------------- inc interface
                   3352: 
                   3353: sub inc {
1.627     albertel 3354:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 3355:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3356:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  3357:     my $uhome=&homeserver($uname,$udomain);
                   3358:     my $items='';
                   3359:     if (! ref($store)) {
                   3360:         # got a single value, so use that instead
                   3361:         $items = &escape($store).'=&';
                   3362:     } elsif (ref($store) eq 'SCALAR') {
                   3363:         $items = &escape($$store).'=&';        
                   3364:     } elsif (ref($store) eq 'ARRAY') {
                   3365:         $items = join('=&',map {&escape($_);} @{$store});
                   3366:     } elsif (ref($store) eq 'HASH') {
                   3367:         while (my($key,$value) = each(%{$store})) {
                   3368:             $items.= &escape($key).'='.&escape($value).'&';
                   3369:         }
                   3370:     }
                   3371:     $items=~s/\&$//;
1.627     albertel 3372:     if ($critical) {
                   3373: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3374:     } else {
                   3375: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3376:     }
1.449     matthew  3377: }
                   3378: 
1.12      www      3379: # --------------------------------------------------------------- put interface
                   3380: 
                   3381: sub put {
1.134     albertel 3382:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3383:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3384:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3385:    my $uhome=&homeserver($uname,$udomain);
1.12      www      3386:    my $items='';
1.800     albertel 3387:    foreach my $item (keys(%$storehash)) {
                   3388:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3389:    }
1.12      www      3390:    $items=~s/\&$//;
1.134     albertel 3391:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      3392: }
                   3393: 
1.631     albertel 3394: # ------------------------------------------------------------ newput interface
                   3395: 
                   3396: sub newput {
                   3397:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   3398:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3399:    if (!$uname) { $uname=$env{'user.name'}; }
                   3400:    my $uhome=&homeserver($uname,$udomain);
                   3401:    my $items='';
                   3402:    foreach my $key (keys(%$storehash)) {
                   3403:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   3404:    }
                   3405:    $items=~s/\&$//;
                   3406:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   3407: }
                   3408: 
                   3409: # ---------------------------------------------------------  putstore interface
                   3410: 
1.524     raeburn  3411: sub putstore {
1.715     albertel 3412:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 3413:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3414:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  3415:    my $uhome=&homeserver($uname,$udomain);
                   3416:    my $items='';
1.715     albertel 3417:    foreach my $key (keys(%$storehash)) {
                   3418:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  3419:    }
1.715     albertel 3420:    $items=~s/\&$//;
1.716     albertel 3421:    my $esc_symb=&escape($symb);
                   3422:    my $esc_v=&escape($version);
1.715     albertel 3423:    my $reply =
1.716     albertel 3424:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 3425: 	      $uhome);
                   3426:    if ($reply eq 'unknown_cmd') {
1.716     albertel 3427:        # gfall back to way things use to be done
1.715     albertel 3428:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   3429: 			    $uname);
1.524     raeburn  3430:    }
1.715     albertel 3431:    return $reply;
                   3432: }
                   3433: 
                   3434: sub old_putstore {
1.716     albertel 3435:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   3436:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3437:     if (!$uname) { $uname=$env{'user.name'}; }
                   3438:     my $uhome=&homeserver($uname,$udomain);
                   3439:     my %newstorehash;
1.800     albertel 3440:     foreach my $item (keys(%$storehash)) {
                   3441: 	my $key = $version.':'.&escape($symb).':'.$item;
                   3442: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 3443:     }
                   3444:     my $items='';
                   3445:     my %allitems = ();
1.800     albertel 3446:     foreach my $item (keys(%newstorehash)) {
                   3447: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 3448: 	    my $key = $1.':keys:'.$2;
                   3449: 	    $allitems{$key} .= $3.':';
                   3450: 	}
1.800     albertel 3451: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 3452:     }
1.800     albertel 3453:     foreach my $item (keys(%allitems)) {
                   3454: 	$allitems{$item} =~ s/\:$//;
                   3455: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 3456:     }
                   3457:     $items=~s/\&$//;
                   3458:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  3459: }
                   3460: 
1.47      www      3461: # ------------------------------------------------------ critical put interface
                   3462: 
                   3463: sub cput {
1.134     albertel 3464:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3465:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3466:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3467:    my $uhome=&homeserver($uname,$udomain);
1.47      www      3468:    my $items='';
1.800     albertel 3469:    foreach my $item (keys(%$storehash)) {
                   3470:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3471:    }
1.47      www      3472:    $items=~s/\&$//;
1.134     albertel 3473:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3474: }
                   3475: 
                   3476: # -------------------------------------------------------------- eget interface
                   3477: 
                   3478: sub eget {
1.133     albertel 3479:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3480:    my $items='';
1.800     albertel 3481:    foreach my $item (@$storearr) {
                   3482:        $items.=&escape($item).'&';
1.191     harris41 3483:    }
1.12      www      3484:    $items=~s/\&$//;
1.620     albertel 3485:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3486:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3487:    my $uhome=&homeserver($uname,$udomain);
                   3488:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3489:    my @pairs=split(/\&/,$rep);
                   3490:    my %returnhash=();
1.42      www      3491:    my $i=0;
1.800     albertel 3492:    foreach my $item (@$storearr) {
                   3493:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3494:       $i++;
1.191     harris41 3495:    }
1.12      www      3496:    return %returnhash;
                   3497: }
                   3498: 
1.667     albertel 3499: # ------------------------------------------------------------ tmpput interface
                   3500: sub tmpput {
1.802     raeburn  3501:     my ($storehash,$server,$context)=@_;
1.667     albertel 3502:     my $items='';
1.800     albertel 3503:     foreach my $item (keys(%$storehash)) {
                   3504: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 3505:     }
                   3506:     $items=~s/\&$//;
1.802     raeburn  3507:     if (defined($context)) {
                   3508:         $items .= ':'.&escape($context);
                   3509:     }
1.667     albertel 3510:     return &reply("tmpput:$items",$server);
                   3511: }
                   3512: 
                   3513: # ------------------------------------------------------------ tmpget interface
                   3514: sub tmpget {
1.688     albertel 3515:     my ($token,$server)=@_;
                   3516:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3517:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 3518:     my %returnhash;
                   3519:     foreach my $item (split(/\&/,$rep)) {
                   3520: 	my ($key,$value)=split(/=/,$item);
                   3521: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   3522:     }
                   3523:     return %returnhash;
                   3524: }
                   3525: 
1.688     albertel 3526: # ------------------------------------------------------------ tmpget interface
                   3527: sub tmpdel {
                   3528:     my ($token,$server)=@_;
                   3529:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3530:     return &reply("tmpdel:$token",$server);
                   3531: }
                   3532: 
1.765     albertel 3533: # -------------------------------------------------- portfolio access checking
                   3534: 
                   3535: sub portfolio_access {
1.766     albertel 3536:     my ($requrl) = @_;
1.765     albertel 3537:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   3538:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  3539:     if ($result) {
                   3540:         my %setters;
                   3541:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3542:             my ($startblock,$endblock) =
                   3543:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   3544:             if ($startblock && $endblock) {
                   3545:                 return 'B';
                   3546:             }
                   3547:         } else {
                   3548:             my ($startblock,$endblock) =
                   3549:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   3550:             if ($startblock && $endblock) {
                   3551:                 return 'B';
                   3552:             }
                   3553:         }
                   3554:     }
1.765     albertel 3555:     if ($result eq 'ok') {
1.766     albertel 3556:        return 'F';
1.765     albertel 3557:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 3558:        return 'A';
1.765     albertel 3559:     }
1.766     albertel 3560:     return '';
1.765     albertel 3561: }
                   3562: 
                   3563: sub get_portfolio_access {
1.767     albertel 3564:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   3565: 
                   3566:     if (!ref($access_hash)) {
                   3567: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   3568: 	my %access_controls = &get_access_controls($current_perms,$group,
                   3569: 						   $file_name);
                   3570: 	$access_hash = $access_controls{$file_name};
                   3571:     }
                   3572: 
1.765     albertel 3573:     my ($public,$guest,@domains,@users,@courses,@groups);
                   3574:     my $now = time;
                   3575:     if (ref($access_hash) eq 'HASH') {
                   3576:         foreach my $key (keys(%{$access_hash})) {
                   3577:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   3578:             if ($start > $now) {
                   3579:                 next;
                   3580:             }
                   3581:             if ($end && $end<$now) {
                   3582:                 next;
                   3583:             }
                   3584:             if ($scope eq 'public') {
                   3585:                 $public = $key;
                   3586:                 last;
                   3587:             } elsif ($scope eq 'guest') {
                   3588:                 $guest = $key;
                   3589:             } elsif ($scope eq 'domains') {
                   3590:                 push(@domains,$key);
                   3591:             } elsif ($scope eq 'users') {
                   3592:                 push(@users,$key);
                   3593:             } elsif ($scope eq 'course') {
                   3594:                 push(@courses,$key);
                   3595:             } elsif ($scope eq 'group') {
                   3596:                 push(@groups,$key);
                   3597:             }
                   3598:         }
                   3599:         if ($public) {
                   3600:             return 'ok';
                   3601:         }
                   3602:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3603:             if ($guest) {
                   3604:                 return $guest;
                   3605:             }
                   3606:         } else {
                   3607:             if (@domains > 0) {
                   3608:                 foreach my $domkey (@domains) {
                   3609:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   3610:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   3611:                             return 'ok';
                   3612:                         }
                   3613:                     }
                   3614:                 }
                   3615:             }
                   3616:             if (@users > 0) {
                   3617:                 foreach my $userkey (@users) {
1.865     raeburn  3618:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   3619:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   3620:                             if (ref($item) eq 'HASH') {
                   3621:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   3622:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   3623:                                     return 'ok';
                   3624:                                 }
                   3625:                             }
                   3626:                         }
                   3627:                     } 
1.765     albertel 3628:                 }
                   3629:             }
                   3630:             my %roleshash;
                   3631:             my @courses_and_groups = @courses;
                   3632:             push(@courses_and_groups,@groups); 
                   3633:             if (@courses_and_groups > 0) {
                   3634:                 my (%allgroups,%allroles); 
                   3635:                 my ($start,$end,$role,$sec,$group);
                   3636:                 foreach my $envkey (%env) {
1.811     albertel 3637:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 3638:                         my $cid = $2.'_'.$3; 
                   3639:                         if ($1 eq 'gr') {
                   3640:                             $group = $4;
                   3641:                             $allgroups{$cid}{$group} = $env{$envkey};
                   3642:                         } else {
                   3643:                             if ($4 eq '') {
                   3644:                                 $sec = 'none';
                   3645:                             } else {
                   3646:                                 $sec = $4;
                   3647:                             }
                   3648:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3649:                         }
1.811     albertel 3650:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 3651:                         my $cid = $2.'_'.$3;
                   3652:                         if ($4 eq '') {
                   3653:                             $sec = 'none';
                   3654:                         } else {
                   3655:                             $sec = $4;
                   3656:                         }
                   3657:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3658:                     }
                   3659:                 }
                   3660:                 if (keys(%allroles) == 0) {
                   3661:                     return;
                   3662:                 }
                   3663:                 foreach my $key (@courses_and_groups) {
                   3664:                     my %content = %{$$access_hash{$key}};
                   3665:                     my $cnum = $content{'number'};
                   3666:                     my $cdom = $content{'domain'};
                   3667:                     my $cid = $cdom.'_'.$cnum;
                   3668:                     if (!exists($allroles{$cid})) {
                   3669:                         next;
                   3670:                     }    
                   3671:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   3672:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   3673:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   3674:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   3675:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   3676:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   3677:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   3678:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   3679:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   3680:                                         if (grep/^all$/,@sections) {
                   3681:                                             return 'ok';
                   3682:                                         } else {
                   3683:                                             if (grep/^$sec$/,@sections) {
                   3684:                                                 return 'ok';
                   3685:                                             }
                   3686:                                         }
                   3687:                                     }
                   3688:                                 }
                   3689:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   3690:                                     if (grep/^none$/,@groups) {
                   3691:                                         return 'ok';
                   3692:                                     }
                   3693:                                 } else {
                   3694:                                     if (grep/^all$/,@groups) {
                   3695:                                         return 'ok';
                   3696:                                     } 
                   3697:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   3698:                                         if (grep/^$group$/,@groups) {
                   3699:                                             return 'ok';
                   3700:                                         }
                   3701:                                     }
                   3702:                                 } 
                   3703:                             }
                   3704:                         }
                   3705:                     }
                   3706:                 }
                   3707:             }
                   3708:             if ($guest) {
                   3709:                 return $guest;
                   3710:             }
                   3711:         }
                   3712:     }
                   3713:     return;
                   3714: }
                   3715: 
                   3716: sub course_group_datechecker {
                   3717:     my ($dates,$now,$status) = @_;
                   3718:     my ($start,$end) = split(/\./,$dates);
                   3719:     if (!$start && !$end) {
                   3720:         return 'ok';
                   3721:     }
                   3722:     if (grep/^active$/,@{$status}) {
                   3723:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   3724:             return 'ok';
                   3725:         }
                   3726:     }
                   3727:     if (grep/^previous$/,@{$status}) {
                   3728:         if ($end > $now ) {
                   3729:             return 'ok';
                   3730:         }
                   3731:     }
                   3732:     if (grep/^future$/,@{$status}) {
                   3733:         if ($start > $now) {
                   3734:             return 'ok';
                   3735:         }
                   3736:     }
                   3737:     return; 
                   3738: }
                   3739: 
                   3740: sub parse_portfolio_url {
                   3741:     my ($url) = @_;
                   3742: 
                   3743:     my ($type,$udom,$unum,$group,$file_name);
                   3744:     
1.823     albertel 3745:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 3746: 	$type = 1;
                   3747:         $udom = $1;
                   3748:         $unum = $2;
                   3749:         $file_name = $3;
1.823     albertel 3750:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 3751: 	$type = 2;
                   3752:         $udom = $1;
                   3753:         $unum = $2;
                   3754:         $group = $3;
                   3755:         $file_name = $3.'/'.$4;
                   3756:     }
                   3757:     if (wantarray) {
                   3758: 	return ($type,$udom,$unum,$file_name,$group);
                   3759:     }
                   3760:     return $type;
                   3761: }
                   3762: 
                   3763: sub is_portfolio_url {
                   3764:     my ($url) = @_;
                   3765:     return scalar(&parse_portfolio_url($url));
                   3766: }
                   3767: 
1.798     raeburn  3768: sub is_portfolio_file {
                   3769:     my ($file) = @_;
1.820     raeburn  3770:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  3771:         return 1;
                   3772:     }
                   3773:     return;
                   3774: }
                   3775: 
                   3776: 
1.341     www      3777: # ---------------------------------------------- Custom access rule evaluation
                   3778: 
                   3779: sub customaccess {
                   3780:     my ($priv,$uri)=@_;
1.807     albertel 3781:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      3782:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 3783:     $udom = &LONCAPA::clean_domain($udom);
                   3784:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      3785:     my $access=0;
1.800     albertel 3786:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
                   3787: 	my ($effect,$realm,$role)=split(/\:/,$right);
1.343     www      3788:         if ($role) {
                   3789: 	   if ($role ne $urole) { next; }
                   3790:         }
1.800     albertel 3791:         foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   3792:             my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
1.343     www      3793:             if ($tdom) {
                   3794: 		if ($tdom ne $udom) { next; }
                   3795:             }
                   3796:             if ($tcrs) {
                   3797: 		if ($tcrs ne $ucrs) { next; }
                   3798:             }
                   3799:             if ($tsec) {
                   3800: 		if ($tsec ne $usec) { next; }
                   3801:             }
                   3802:             $access=($effect eq 'allow');
                   3803:             last;
1.342     www      3804:         }
1.402     bowersj2 3805: 	if ($realm eq '' && $role eq '') {
                   3806:             $access=($effect eq 'allow');
                   3807: 	}
1.341     www      3808:     }
                   3809:     return $access;
                   3810: }
                   3811: 
1.103     harris41 3812: # ------------------------------------------------- Check for a user privilege
1.12      www      3813: 
                   3814: sub allowed {
1.810     raeburn  3815:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 3816:     my $ver_orguri=$uri;
1.439     www      3817:     $uri=&deversion($uri);
1.152     www      3818:     my $orguri=$uri;
1.52      www      3819:     $uri=&declutter($uri);
1.809     raeburn  3820: 
1.810     raeburn  3821:     if ($priv eq 'evb') {
                   3822: # Evade communication block restrictions for specified role in a course
                   3823:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   3824:             return $1;
                   3825:         } else {
                   3826:             return;
                   3827:         }
                   3828:     }
                   3829: 
1.620     albertel 3830:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      3831: # Free bre access to adm and meta resources
1.775     albertel 3832:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 3833: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   3834: 	&& ($priv eq 'bre')) {
1.14      www      3835: 	return 'F';
1.159     www      3836:     }
                   3837: 
1.545     banghart 3838: # Free bre access to user's own portfolio contents
1.714     raeburn  3839:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  3840:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  3841: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  3842:         my %setters;
                   3843:         my ($startblock,$endblock) = 
                   3844:             &Apache::loncommon::blockcheck(\%setters,'port');
                   3845:         if ($startblock && $endblock) {
                   3846:             return 'B';
                   3847:         } else {
                   3848:             return 'F';
                   3849:         }
1.545     banghart 3850:     }
                   3851: 
1.762     raeburn  3852: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  3853:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   3854:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   3855:         if (exists($env{'request.course.id'})) {
                   3856:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3857:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3858:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   3859:                 my $courseprivid=$env{'request.course.id'};
                   3860:                 $courseprivid=~s/\_/\//;
                   3861:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   3862:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   3863:                     return $1; 
1.762     raeburn  3864:                 } else {
                   3865:                     if ($env{'request.course.sec'}) {
                   3866:                         $courseprivid.='/'.$env{'request.course.sec'};
                   3867:                     }
                   3868:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   3869:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   3870:                         return $2;
                   3871:                     }
1.714     raeburn  3872:                 }
                   3873:             }
                   3874:         }
                   3875:     }
                   3876: 
1.159     www      3877: # Free bre to public access
                   3878: 
                   3879:     if ($priv eq 'bre') {
1.238     www      3880:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 3881: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      3882:            return 'F'; 
                   3883:         }
1.238     www      3884:         if ($copyright eq 'priv') {
                   3885:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3886: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      3887: 		return '';
                   3888:             }
                   3889:         }
                   3890:         if ($copyright eq 'domain') {
                   3891:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3892: 	    unless (($env{'user.domain'} eq $1) ||
                   3893:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      3894: 		return '';
                   3895:             }
1.262     matthew  3896:         }
1.620     albertel 3897:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  3898:             # Library role, so allow browsing of resources in this domain.
                   3899:             return 'F';
1.238     www      3900:         }
1.341     www      3901:         if ($copyright eq 'custom') {
                   3902: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   3903:         }
1.14      www      3904:     }
1.264     matthew  3905:     # Domain coordinator is trying to create a course
1.620     albertel 3906:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  3907:         # uri is the requested domain in this case.
                   3908:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  3909:         # a role of dc for the domain in question.
1.620     albertel 3910:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  3911:     }
1.29      www      3912: 
1.52      www      3913:     my $thisallowed='';
                   3914:     my $statecond=0;
                   3915:     my $courseprivid='';
                   3916: 
                   3917: # Course
                   3918: 
1.620     albertel 3919:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3920:        $thisallowed.=$1;
                   3921:     }
1.29      www      3922: 
1.52      www      3923: # Domain
                   3924: 
1.620     albertel 3925:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 3926:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3927:        $thisallowed.=$1;
                   3928:     }
1.52      www      3929: 
                   3930: # Course: uri itself is a course
1.66      www      3931:     my $courseuri=$uri;
                   3932:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      3933:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      3934: 
1.620     albertel 3935:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 3936:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3937:        $thisallowed.=$1;
                   3938:     }
1.29      www      3939: 
1.665     albertel 3940: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 3941: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 3942:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 3943: 	$thisallowed='';
1.671     raeburn  3944:         my ($match)=&is_on_map($uri);
                   3945:         if ($match) {
                   3946:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   3947:                   =~/\Q$priv\E\&([^\:]*)/) {
                   3948:                 $thisallowed.=$1;
                   3949:             }
                   3950:         } else {
1.705     albertel 3951:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  3952:             if ($refuri) {
                   3953:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  3954:                     $thisallowed='F';
1.671     raeburn  3955:                 } else {
                   3956:                     $refuri=&declutter($refuri);
                   3957:                     my ($match) = &is_on_map($refuri);
                   3958:                     if ($match) {
                   3959:                         $thisallowed='F';
                   3960:                     }
1.669     raeburn  3961:                 }
1.671     raeburn  3962:             }
                   3963:         }
1.314     www      3964:     }
1.492     albertel 3965: 
1.766     albertel 3966:     if ($priv eq 'bre'
                   3967: 	&& $thisallowed ne 'F' 
                   3968: 	&& $thisallowed ne '2'
                   3969: 	&& &is_portfolio_url($uri)) {
                   3970: 	$thisallowed = &portfolio_access($uri);
                   3971:     }
                   3972:     
1.52      www      3973: # Full access at system, domain or course-wide level? Exit.
1.29      www      3974: 
                   3975:     if ($thisallowed=~/F/) {
                   3976: 	return 'F';
                   3977:     }
                   3978: 
1.52      www      3979: # If this is generating or modifying users, exit with special codes
1.29      www      3980: 
1.643     www      3981:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   3982: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 3983: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      3984: # no author name given, so this just checks on the general right to make a co-author in this domain
                   3985: 	    unless ($auname) { return $thisallowed; }
                   3986: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 3987: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   3988: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   3989: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   3990: 	}
1.52      www      3991: 	return $thisallowed;
                   3992:     }
                   3993: #
1.103     harris41 3994: # Gathered so far: system, domain and course wide privileges
1.52      www      3995: #
                   3996: # Course: See if uri or referer is an individual resource that is part of 
                   3997: # the course
                   3998: 
1.620     albertel 3999:     if ($env{'request.course.id'}) {
1.232     www      4000: 
1.620     albertel 4001:        $courseprivid=$env{'request.course.id'};
                   4002:        if ($env{'request.course.sec'}) {
                   4003:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      4004:        }
                   4005:        $courseprivid=~s/\_/\//;
                   4006:        my $checkreferer=1;
1.232     www      4007:        my ($match,$cond)=&is_on_map($uri);
                   4008:        if ($match) {
                   4009:            $statecond=$cond;
1.620     albertel 4010:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4011:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4012:                $thisallowed.=$1;
                   4013:                $checkreferer=0;
                   4014:            }
1.29      www      4015:        }
1.83      www      4016:        
1.148     www      4017:        if ($checkreferer) {
1.620     albertel 4018: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      4019:             unless ($refuri) {
1.800     albertel 4020:                 foreach my $key (keys(%env)) {
                   4021: 		    if ($key=~/^httpref\..*\*/) {
                   4022: 			my $pattern=$key;
1.156     www      4023:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      4024:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   4025:                         $pattern=~s/\//\\\//g;
1.152     www      4026:                         if ($orguri=~/$pattern/) {
1.800     albertel 4027: 			    $refuri=$env{$key};
1.148     www      4028:                         }
                   4029:                     }
1.191     harris41 4030:                 }
1.148     www      4031:             }
1.232     www      4032: 
1.148     www      4033:          if ($refuri) { 
1.152     www      4034: 	  $refuri=&declutter($refuri);
1.232     www      4035:           my ($match,$cond)=&is_on_map($refuri);
                   4036:             if ($match) {
                   4037:               my $refstatecond=$cond;
1.620     albertel 4038:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4039:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4040:                   $thisallowed.=$1;
1.53      www      4041:                   $uri=$refuri;
                   4042:                   $statecond=$refstatecond;
1.52      www      4043:               }
                   4044:           }
1.148     www      4045:         }
1.29      www      4046:        }
1.52      www      4047:    }
1.29      www      4048: 
1.52      www      4049: #
1.103     harris41 4050: # Gathered now: all privileges that could apply, and condition number
1.52      www      4051: # 
                   4052: #
                   4053: # Full or no access?
                   4054: #
1.29      www      4055: 
1.52      www      4056:     if ($thisallowed=~/F/) {
                   4057: 	return 'F';
                   4058:     }
1.29      www      4059: 
1.52      www      4060:     unless ($thisallowed) {
                   4061:         return '';
                   4062:     }
1.29      www      4063: 
1.52      www      4064: # Restrictions exist, deal with them
                   4065: #
                   4066: #   C:according to course preferences
                   4067: #   R:according to resource settings
                   4068: #   L:unless locked
                   4069: #   X:according to user session state
                   4070: #
                   4071: 
                   4072: # Possibly locked functionality, check all courses
1.54      www      4073: # Locks might take effect only after 10 minutes cache expiration for other
                   4074: # courses, and 2 minutes for current course
1.52      www      4075: 
                   4076:     my $envkey;
                   4077:     if ($thisallowed=~/L/) {
1.620     albertel 4078:         foreach $envkey (keys %env) {
1.54      www      4079:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   4080:                my $courseid=$2;
                   4081:                my $roleid=$1.'.'.$2;
1.92      www      4082:                $courseid=~s/^\///;
1.54      www      4083:                my $expiretime=600;
1.620     albertel 4084:                if ($env{'request.role'} eq $roleid) {
1.54      www      4085: 		  $expiretime=120;
                   4086:                }
                   4087: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   4088:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 4089:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 4090: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      4091:                }
1.620     albertel 4092:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4093:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   4094: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   4095:                        &log($env{'user.domain'},$env{'user.name'},
                   4096:                             $env{'user.home'},
1.57      www      4097:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      4098:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4099:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4100: 		       return '';
                   4101:                    }
                   4102:                }
1.620     albertel 4103:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4104:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   4105: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   4106:                        &log($env{'user.domain'},$env{'user.name'},
                   4107:                             $env{'user.home'},
1.57      www      4108:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      4109:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4110:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4111: 		       return '';
                   4112:                    }
                   4113:                }
                   4114: 	   }
1.29      www      4115:        }
1.52      www      4116:     }
                   4117:    
                   4118: #
                   4119: # Rest of the restrictions depend on selected course
                   4120: #
                   4121: 
1.620     albertel 4122:     unless ($env{'request.course.id'}) {
1.766     albertel 4123: 	if ($thisallowed eq 'A') {
                   4124: 	    return 'A';
1.814     raeburn  4125:         } elsif ($thisallowed eq 'B') {
                   4126:             return 'B';
1.766     albertel 4127: 	} else {
                   4128: 	    return '1';
                   4129: 	}
1.52      www      4130:     }
1.29      www      4131: 
1.52      www      4132: #
                   4133: # Now user is definitely in a course
                   4134: #
1.53      www      4135: 
                   4136: 
                   4137: # Course preferences
                   4138: 
                   4139:    if ($thisallowed=~/C/) {
1.620     albertel 4140:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   4141:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   4142:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 4143: 	   =~/\Q$rolecode\E/) {
1.689     albertel 4144: 	   if ($priv ne 'pch') { 
                   4145: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4146: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   4147: 			$env{'request.course.id'});
                   4148: 	   }
1.237     www      4149:            return '';
                   4150:        }
                   4151: 
1.620     albertel 4152:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 4153: 	   =~/\Q$unamedom\E/) {
1.689     albertel 4154: 	   if ($priv ne 'pch') { 
                   4155: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   4156: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   4157: 			$env{'request.course.id'});
                   4158: 	   }
1.54      www      4159:            return '';
                   4160:        }
1.53      www      4161:    }
                   4162: 
                   4163: # Resource preferences
                   4164: 
                   4165:    if ($thisallowed=~/R/) {
1.620     albertel 4166:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 4167:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 4168: 	   if ($priv ne 'pch') { 
                   4169: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4170: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   4171: 	   }
                   4172: 	   return '';
1.54      www      4173:        }
1.53      www      4174:    }
1.30      www      4175: 
1.246     www      4176: # Restricted by state or randomout?
1.30      www      4177: 
1.52      www      4178:    if ($thisallowed=~/X/) {
1.620     albertel 4179:       if ($env{'acc.randomout'}) {
1.579     albertel 4180: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 4181:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      4182:             return ''; 
                   4183:          }
1.247     www      4184:       }
                   4185:       if (&condval($statecond)) {
1.52      www      4186: 	 return '2';
                   4187:       } else {
                   4188:          return '';
                   4189:       }
                   4190:    }
1.30      www      4191: 
1.766     albertel 4192:     if ($thisallowed eq 'A') {
                   4193: 	return 'A';
1.814     raeburn  4194:     } elsif ($thisallowed eq 'B') {
                   4195:         return 'B';
1.766     albertel 4196:     }
1.52      www      4197:    return 'F';
1.232     www      4198: }
                   4199: 
1.710     albertel 4200: sub split_uri_for_cond {
                   4201:     my $uri=&deversion(&declutter(shift));
                   4202:     my @uriparts=split(/\//,$uri);
                   4203:     my $filename=pop(@uriparts);
                   4204:     my $pathname=join('/',@uriparts);
                   4205:     return ($pathname,$filename);
                   4206: }
1.232     www      4207: # --------------------------------------------------- Is a resource on the map?
                   4208: 
                   4209: sub is_on_map {
1.710     albertel 4210:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 4211:     #Trying to find the conditional for the file
1.620     albertel 4212:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 4213: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      4214:     if ($match) {
1.289     bowersj2 4215: 	return (1,$1);
                   4216:     } else {
1.434     www      4217: 	return (0,0);
1.289     bowersj2 4218:     }
1.12      www      4219: }
                   4220: 
1.427     www      4221: # --------------------------------------------------------- Get symb from alias
                   4222: 
                   4223: sub get_symb_from_alias {
                   4224:     my $symb=shift;
                   4225:     my ($map,$resid,$url)=&decode_symb($symb);
                   4226: # Already is a symb
                   4227:     if ($url) { return $symb; }
                   4228: # Must be an alias
                   4229:     my $aliassymb='';
                   4230:     my %bighash;
1.620     albertel 4231:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      4232:                             &GDBM_READER(),0640)) {
                   4233:         my $rid=$bighash{'mapalias_'.$symb};
                   4234: 	if ($rid) {
                   4235: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 4236: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   4237: 				    $resid,$bighash{'src_'.$rid});
1.427     www      4238: 	}
                   4239:         untie %bighash;
                   4240:     }
                   4241:     return $aliassymb;
                   4242: }
                   4243: 
1.12      www      4244: # ----------------------------------------------------------------- Define Role
                   4245: 
                   4246: sub definerole {
                   4247:   if (allowed('mcr','/')) {
                   4248:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 4249:     foreach my $role (split(':',$sysrole)) {
                   4250: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4251:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   4252:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   4253: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4254:                return "refused:s:$crole&$cqual"; 
                   4255:             }
                   4256:         }
1.191     harris41 4257:     }
1.800     albertel 4258:     foreach my $role (split(':',$domrole)) {
                   4259: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4260:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   4261:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   4262: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      4263:                return "refused:d:$crole&$cqual"; 
                   4264:             }
                   4265:         }
1.191     harris41 4266:     }
1.800     albertel 4267:     foreach my $role (split(':',$courole)) {
                   4268: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4269:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   4270:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   4271: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4272:                return "refused:c:$crole&$cqual"; 
                   4273:             }
                   4274:         }
1.191     harris41 4275:     }
1.620     albertel 4276:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   4277:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4278: 	        "rolesdef_$rolename=".
                   4279:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 4280:     return reply($command,$env{'user.home'});
1.12      www      4281:   } else {
                   4282:     return 'refused';
                   4283:   }
1.105     harris41 4284: }
                   4285: 
                   4286: # ---------------- Make a metadata query against the network of library servers
                   4287: 
                   4288: sub metadata_query {
1.244     matthew  4289:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 4290:     my %rhash;
1.845     albertel 4291:     my %libserv = &all_library();
1.244     matthew  4292:     my @server_list = (defined($server_array) ? @$server_array
                   4293:                                               : keys(%libserv) );
                   4294:     for my $server (@server_list) {
1.118     harris41 4295: 	unless ($custom or $customshow) {
                   4296: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   4297: 	    $rhash{$server}=$reply;
                   4298: 	}
                   4299: 	else {
                   4300: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   4301: 			     &escape($custom).':'.&escape($customshow),
                   4302: 			     $server);
                   4303: 	    $rhash{$server}=$reply;
                   4304: 	}
1.112     harris41 4305:     }
1.118     harris41 4306:     return \%rhash;
1.240     www      4307: }
                   4308: 
                   4309: # ----------------------------------------- Send log queries and wait for reply
                   4310: 
                   4311: sub log_query {
                   4312:     my ($uname,$udom,$query,%filters)=@_;
                   4313:     my $uhome=&homeserver($uname,$udom);
                   4314:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 4315:     my $uhost=&hostname($uhome);
1.800     albertel 4316:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      4317:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   4318:                        $uhome);
1.479     albertel 4319:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      4320:     return get_query_reply($queryid);
                   4321: }
                   4322: 
1.818     raeburn  4323: # -------------------------- Update MySQL table for portfolio file
                   4324: 
                   4325: sub update_portfolio_table {
1.821     raeburn  4326:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.818     raeburn  4327:     my $homeserver = &homeserver($uname,$udom);
                   4328:     my $queryid=
1.821     raeburn  4329:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   4330:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  4331:     my $reply = &get_query_reply($queryid);
                   4332:     return $reply;
                   4333: }
                   4334: 
1.508     raeburn  4335: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  4336: 
                   4337: sub fetch_enrollment_query {
1.511     raeburn  4338:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  4339:     my $homeserver;
1.547     raeburn  4340:     my $maxtries = 1;
1.508     raeburn  4341:     if ($context eq 'automated') {
                   4342:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  4343:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  4344:     } else {
                   4345:         $homeserver = &homeserver($cnum,$dom);
                   4346:     }
1.838     albertel 4347:     my $host=&hostname($homeserver);
1.506     raeburn  4348:     my $cmd = '';
1.800     albertel 4349:     foreach my $affiliate (keys %{$affiliatesref}) {
                   4350:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  4351:     }
                   4352:     $cmd =~ s/%%$//;
                   4353:     $cmd = &escape($cmd);
                   4354:     my $query = 'fetchenrollment';
1.620     albertel 4355:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  4356:     unless ($queryid=~/^\Q$host\E\_/) { 
                   4357:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   4358:         return 'error: '.$queryid;
                   4359:     }
1.506     raeburn  4360:     my $reply = &get_query_reply($queryid);
1.547     raeburn  4361:     my $tries = 1;
                   4362:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4363:         $reply = &get_query_reply($queryid);
                   4364:         $tries ++;
                   4365:     }
1.526     raeburn  4366:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 4367:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  4368:     } else {
1.515     raeburn  4369:         my @responses = split/:/,$reply;
                   4370:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 4371:             foreach my $line (@responses) {
                   4372:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  4373:                 $$replyref{$key} = $value;
                   4374:             }
                   4375:         } else {
1.506     raeburn  4376:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 4377:             foreach my $line (@responses) {
                   4378:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  4379:                 $$replyref{$key} = $value;
                   4380:                 if ($value > 0) {
1.800     albertel 4381:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   4382:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  4383:                         my $destname = $pathname.'/'.$filename;
                   4384:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  4385:                         if ($xml_classlist =~ /^error/) {
                   4386:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   4387:                         } else {
1.506     raeburn  4388:                             if ( open(FILE,">$destname") ) {
                   4389:                                 print FILE &unescape($xml_classlist);
                   4390:                                 close(FILE);
1.526     raeburn  4391:                             } else {
                   4392:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  4393:                             }
                   4394:                         }
                   4395:                     }
                   4396:                 }
                   4397:             }
                   4398:         }
                   4399:         return 'ok';
                   4400:     }
                   4401:     return 'error';
                   4402: }
                   4403: 
1.242     www      4404: sub get_query_reply {
                   4405:     my $queryid=shift;
1.240     www      4406:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   4407:     my $reply='';
                   4408:     for (1..100) {
                   4409: 	sleep 2;
                   4410:         if (-e $replyfile.'.end') {
1.448     albertel 4411: 	    if (open(my $fh,$replyfile)) {
1.240     www      4412:                $reply.=<$fh>;
1.448     albertel 4413:                close($fh);
1.240     www      4414: 	   } else { return 'error: reply_file_error'; }
1.242     www      4415:            return &unescape($reply);
                   4416: 	}
1.240     www      4417:     }
1.242     www      4418:     return 'timeout:'.$queryid;
1.240     www      4419: }
                   4420: 
                   4421: sub courselog_query {
1.241     www      4422: #
                   4423: # possible filters:
                   4424: # url: url or symb
                   4425: # username
                   4426: # domain
                   4427: # action: view, submit, grade
                   4428: # start: timestamp
                   4429: # end: timestamp
                   4430: #
1.240     www      4431:     my (%filters)=@_;
1.620     albertel 4432:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      4433:     if ($filters{'url'}) {
                   4434: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   4435:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   4436:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   4437:     }
1.620     albertel 4438:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4439:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      4440:     return &log_query($cname,$cdom,'courselog',%filters);
                   4441: }
                   4442: 
                   4443: sub userlog_query {
1.858     raeburn  4444: #
                   4445: # possible filters:
                   4446: # action: log check role
                   4447: # start: timestamp
                   4448: # end: timestamp
                   4449: #
1.240     www      4450:     my ($uname,$udom,%filters)=@_;
                   4451:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      4452: }
                   4453: 
1.506     raeburn  4454: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   4455: 
                   4456: sub auto_run {
1.508     raeburn  4457:     my ($cnum,$cdom) = @_;
                   4458:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4459:     my $response = &reply('autorun:'.$cdom,$homeserver);
1.506     raeburn  4460:     return $response;
                   4461: }
1.776     albertel 4462: 
1.506     raeburn  4463: sub auto_get_sections {
1.508     raeburn  4464:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   4465:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  4466:     my @secs = ();
1.511     raeburn  4467:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  4468:     unless ($response eq 'refused') {
                   4469:         @secs = split/:/,$response;
                   4470:     }
                   4471:     return @secs;
                   4472: }
1.776     albertel 4473: 
1.506     raeburn  4474: sub auto_new_course {
1.508     raeburn  4475:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   4476:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  4477:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  4478:     return $response;
                   4479: }
1.776     albertel 4480: 
1.506     raeburn  4481: sub auto_validate_courseID {
1.508     raeburn  4482:     my ($cnum,$cdom,$inst_course_id) = @_;
                   4483:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4484:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  4485:     return $response;
                   4486: }
1.776     albertel 4487: 
1.506     raeburn  4488: sub auto_create_password {
1.508     raeburn  4489:     my ($cnum,$cdom,$authparam) = @_;
                   4490:     my $homeserver = &homeserver($cnum,$cdom); 
1.506     raeburn  4491:     my $create_passwd = 0;
                   4492:     my $authchk = '';
1.511     raeburn  4493:     my $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
1.506     raeburn  4494:     if ($response eq 'refused') {
                   4495:         $authchk = 'refused';
                   4496:     } else {
                   4497:         ($authparam,$create_passwd,$authchk) = split/:/,$response;
                   4498:     }
                   4499:     return ($authparam,$create_passwd,$authchk);
                   4500: }
                   4501: 
1.706     raeburn  4502: sub auto_photo_permission {
                   4503:     my ($cnum,$cdom,$students) = @_;
                   4504:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 4505:     my ($outcome,$perm_reqd,$conditions) = 
                   4506: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 4507:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4508: 	return (undef,undef);
                   4509:     }
1.706     raeburn  4510:     return ($outcome,$perm_reqd,$conditions);
                   4511: }
                   4512: 
                   4513: sub auto_checkphotos {
                   4514:     my ($uname,$udom,$pid) = @_;
                   4515:     my $homeserver = &homeserver($uname,$udom);
                   4516:     my ($result,$resulttype);
                   4517:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 4518: 				   &escape($uname).':'.&escape($pid),
                   4519: 				   $homeserver));
1.709     albertel 4520:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4521: 	return (undef,undef);
                   4522:     }
1.706     raeburn  4523:     if ($outcome) {
                   4524:         ($result,$resulttype) = split(/:/,$outcome);
                   4525:     } 
                   4526:     return ($result,$resulttype);
                   4527: }
                   4528: 
                   4529: sub auto_photochoice {
                   4530:     my ($cnum,$cdom) = @_;
                   4531:     my $homeserver = &homeserver($cnum,$cdom);
                   4532:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 4533: 						       &escape($cdom),
                   4534: 						       $homeserver)));
1.709     albertel 4535:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4536: 	return (undef,undef);
                   4537:     }
1.706     raeburn  4538:     return ($update,$comment);
                   4539: }
                   4540: 
                   4541: sub auto_photoupdate {
                   4542:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   4543:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 4544:     my $host=&hostname($homeserver);
1.706     raeburn  4545:     my $cmd = '';
                   4546:     my $maxtries = 1;
1.800     albertel 4547:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   4548:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  4549:     }
                   4550:     $cmd =~ s/%%$//;
                   4551:     $cmd = &escape($cmd);
                   4552:     my $query = 'institutionalphotos';
                   4553:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   4554:     unless ($queryid=~/^\Q$host\E\_/) {
                   4555:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   4556:         return 'error: '.$queryid;
                   4557:     }
                   4558:     my $reply = &get_query_reply($queryid);
                   4559:     my $tries = 1;
                   4560:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4561:         $reply = &get_query_reply($queryid);
                   4562:         $tries ++;
                   4563:     }
                   4564:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   4565:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   4566:     } else {
                   4567:         my @responses = split(/:/,$reply);
                   4568:         my $outcome = shift(@responses); 
                   4569:         foreach my $item (@responses) {
                   4570:             my ($key,$value) = split(/=/,$item);
                   4571:             $$photo{$key} = $value;
                   4572:         }
                   4573:         return $outcome;
                   4574:     }
                   4575:     return 'error';
                   4576: }
                   4577: 
1.521     raeburn  4578: sub auto_instcode_format {
1.793     albertel 4579:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   4580: 	$cat_order) = @_;
1.521     raeburn  4581:     my $courses = '';
1.772     raeburn  4582:     my @homeservers;
1.521     raeburn  4583:     if ($caller eq 'global') {
1.841     albertel 4584: 	my %servers = &get_servers($codedom,'library');
                   4585: 	foreach my $tryserver (keys(%servers)) {
                   4586: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   4587: 		push(@homeservers,$tryserver);
                   4588: 	    }
1.584     raeburn  4589:         }
1.521     raeburn  4590:     } else {
1.772     raeburn  4591:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  4592:     }
1.793     albertel 4593:     foreach my $code (keys(%{$instcodes})) {
                   4594:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  4595:     }
                   4596:     chop($courses);
1.772     raeburn  4597:     my $ok_response = 0;
                   4598:     my $response;
                   4599:     while (@homeservers > 0 && $ok_response == 0) {
                   4600:         my $server = shift(@homeservers); 
                   4601:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   4602:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   4603:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.793     albertel 4604: 		split/:/,$response;
1.772     raeburn  4605:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   4606:             push(@{$codetitles},&str2array($codetitles_str));
                   4607:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   4608:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   4609:             $ok_response = 1;
                   4610:         }
                   4611:     }
                   4612:     if ($ok_response) {
1.521     raeburn  4613:         return 'ok';
1.772     raeburn  4614:     } else {
                   4615:         return $response;
1.521     raeburn  4616:     }
                   4617: }
                   4618: 
1.792     raeburn  4619: sub auto_instcode_defaults {
                   4620:     my ($domain,$returnhash,$code_order) = @_;
                   4621:     my @homeservers;
1.841     albertel 4622: 
                   4623:     my %servers = &get_servers($domain,'library');
                   4624:     foreach my $tryserver (keys(%servers)) {
                   4625: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   4626: 	    push(@homeservers,$tryserver);
                   4627: 	}
1.792     raeburn  4628:     }
1.841     albertel 4629: 
1.792     raeburn  4630:     my $response;
1.841     albertel 4631:     foreach my $server (@homeservers) {
1.792     raeburn  4632:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 4633:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   4634: 	
                   4635: 	foreach my $pair (split(/\&/,$response)) {
                   4636: 	    my ($name,$value)=split(/\=/,$pair);
                   4637: 	    if ($name eq 'code_order') {
                   4638: 		@{$code_order} = split(/\&/,&unescape($value));
                   4639: 	    } else {
                   4640: 		$returnhash->{&unescape($name)}=&unescape($value);
                   4641: 	    }
                   4642: 	}
                   4643: 	return 'ok';
1.792     raeburn  4644:     }
1.841     albertel 4645: 
                   4646:     return $response;
1.792     raeburn  4647: } 
                   4648: 
1.777     albertel 4649: sub auto_validate_class_sec {
1.773     raeburn  4650:     my ($cdom,$cnum,$owner,$inst_class) = @_;
                   4651:     my $homeserver = &homeserver($cnum,$cdom);
                   4652:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.774     banghart 4653:                         &escape($owner).':'.$cdom,$homeserver);
1.773     raeburn  4654:     return $response;
                   4655: }
                   4656: 
1.679     raeburn  4657: # ------------------------------------------------------- Course Group routines
                   4658: 
                   4659: sub get_coursegroups {
1.809     raeburn  4660:     my ($cdom,$cnum,$group,$namespace) = @_;
                   4661:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  4662: }
                   4663: 
1.679     raeburn  4664: sub modify_coursegroup {
                   4665:     my ($cdom,$cnum,$groupsettings) = @_;
                   4666:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   4667: }
                   4668: 
1.809     raeburn  4669: sub toggle_coursegroup_status {
                   4670:     my ($cdom,$cnum,$group,$action) = @_;
                   4671:     my ($from_namespace,$to_namespace);
                   4672:     if ($action eq 'delete') {
                   4673:         $from_namespace = 'coursegroups';
                   4674:         $to_namespace = 'deleted_groups';
                   4675:     } else {
                   4676:         $from_namespace = 'deleted_groups';
                   4677:         $to_namespace = 'coursegroups';
                   4678:     }
                   4679:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  4680:     if (my $tmp = &error(%curr_group)) {
                   4681:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   4682:         return ('read error',$tmp);
                   4683:     } else {
                   4684:         my %savedsettings = %curr_group; 
1.809     raeburn  4685:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  4686:         my $deloutcome;
                   4687:         if ($result eq 'ok') {
1.809     raeburn  4688:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  4689:         } else {
                   4690:             return ('write error',$result);
                   4691:         }
                   4692:         if ($deloutcome eq 'ok') {
                   4693:             return 'ok';
                   4694:         } else {
                   4695:             return ('delete error',$deloutcome);
                   4696:         }
                   4697:     }
                   4698: }
                   4699: 
1.679     raeburn  4700: sub modify_group_roles {
                   4701:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
                   4702:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   4703:     my $role = 'gr/'.&escape($userprivs);
                   4704:     my ($uname,$udom) = split(/:/,$user);
                   4705:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
1.684     raeburn  4706:     if ($result eq 'ok') {
                   4707:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   4708:     }
1.679     raeburn  4709:     return $result;
                   4710: }
                   4711: 
                   4712: sub modify_coursegroup_membership {
                   4713:     my ($cdom,$cnum,$membership) = @_;
                   4714:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   4715:     return $result;
                   4716: }
                   4717: 
1.682     raeburn  4718: sub get_active_groups {
                   4719:     my ($udom,$uname,$cdom,$cnum) = @_;
                   4720:     my $now = time;
                   4721:     my %groups = ();
                   4722:     foreach my $key (keys(%env)) {
1.811     albertel 4723:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  4724:             my ($start,$end) = split(/\./,$env{$key});
                   4725:             if (($end!=0) && ($end<$now)) { next; }
                   4726:             if (($start!=0) && ($start>$now)) { next; }
                   4727:             if ($1 eq $cdom && $2 eq $cnum) {
                   4728:                 $groups{$3} = $env{$key} ;
                   4729:             }
                   4730:         }
                   4731:     }
                   4732:     return %groups;
                   4733: }
                   4734: 
1.683     raeburn  4735: sub get_group_membership {
                   4736:     my ($cdom,$cnum,$group) = @_;
                   4737:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   4738: }
                   4739: 
                   4740: sub get_users_groups {
                   4741:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  4742:     my @usersgroups;
1.683     raeburn  4743:     my $cachetime=1800;
                   4744: 
                   4745:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  4746:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   4747:     if (defined($cached)) {
1.734     albertel 4748:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  4749:     } else {  
                   4750:         $grouplist = '';
1.816     raeburn  4751:         my $courseurl = &courseid_to_courseurl($courseid);
                   4752:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  4753:         my $access_end = $env{'course.'.$courseid.
                   4754:                               '.default_enrollment_end_date'};
                   4755:         my $now = time;
                   4756:         foreach my $key (keys(%roleshash)) {
                   4757:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   4758:                 my $group = $1;
                   4759:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   4760:                     my $start = $2;
                   4761:                     my $end = $1;
                   4762:                     if ($start == -1) { next; } # deleted from group
                   4763:                     if (($start!=0) && ($start>$now)) { next; }
                   4764:                     if (($end!=0) && ($end<$now)) {
                   4765:                         if ($access_end && $access_end < $now) {
                   4766:                             if ($access_end - $end < 86400) {
                   4767:                                 push(@usersgroups,$group);
1.733     raeburn  4768:                             }
                   4769:                         }
1.817     raeburn  4770:                         next;
1.733     raeburn  4771:                     }
1.817     raeburn  4772:                     push(@usersgroups,$group);
1.683     raeburn  4773:                 }
                   4774:             }
                   4775:         }
1.817     raeburn  4776:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   4777:         $grouplist = join(':',@usersgroups);
                   4778:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  4779:     }
1.733     raeburn  4780:     return @usersgroups;
1.683     raeburn  4781: }
                   4782: 
                   4783: sub devalidate_getgroups_cache {
                   4784:     my ($udom,$uname,$cdom,$cnum)=@_;
                   4785:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 4786: 
1.683     raeburn  4787:     my $hashid="$udom:$uname:$courseid";
                   4788:     &devalidate_cache_new('getgroups',$hashid);
                   4789: }
                   4790: 
1.12      www      4791: # ------------------------------------------------------------------ Plain Text
                   4792: 
                   4793: sub plaintext {
1.742     raeburn  4794:     my ($short,$type,$cid) = @_;
1.758     albertel 4795:     if ($short =~ /^cr/) {
                   4796: 	return (split('/',$short))[-1];
                   4797:     }
1.742     raeburn  4798:     if (!defined($cid)) {
                   4799:         $cid = $env{'request.course.id'};
                   4800:     }
                   4801:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
                   4802:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
                   4803:                                           '.plaintext'});
                   4804:     }
                   4805:     my %rolenames = (
                   4806:                       Course => 'std',
                   4807:                       Group => 'alt1',
                   4808:                     );
                   4809:     if (defined($type) && 
                   4810:          defined($rolenames{$type}) && 
                   4811:          defined($prp{$short}{$rolenames{$type}})) {
                   4812:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   4813:     } else {
                   4814:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   4815:     }
1.12      www      4816: }
                   4817: 
                   4818: # ----------------------------------------------------------------- Assign Role
                   4819: 
                   4820: sub assignrole {
1.357     www      4821:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
1.21      www      4822:     my $mrole;
                   4823:     if ($role =~ /^cr\//) {
1.393     www      4824:         my $cwosec=$url;
1.811     albertel 4825:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      4826: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      4827:            &logthis('Refused custom assignrole: '.
                   4828:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4829: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4830:            return 'refused'; 
                   4831:         }
1.21      www      4832:         $mrole='cr';
1.678     raeburn  4833:     } elsif ($role =~ /^gr\//) {
                   4834:         my $cwogrp=$url;
1.811     albertel 4835:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  4836:         unless (&allowed('mdg',$cwogrp)) {
                   4837:             &logthis('Refused group assignrole: '.
                   4838:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   4839:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   4840:             return 'refused';
                   4841:         }
                   4842:         $mrole='gr';
1.21      www      4843:     } else {
1.82      www      4844:         my $cwosec=$url;
1.811     albertel 4845:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.373     www      4846:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
1.104     www      4847:            &logthis('Refused assignrole: '.
                   4848:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4849: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4850:            return 'refused'; 
                   4851:         }
1.21      www      4852:         $mrole=$role;
                   4853:     }
1.620     albertel 4854:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4855:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      4856:     if ($end) { $command.='_'.$end; }
1.21      www      4857:     if ($start) {
                   4858: 	if ($end) { 
1.81      www      4859:            $command.='_'.$start; 
1.21      www      4860:         } else {
1.81      www      4861:            $command.='_0_'.$start;
1.21      www      4862:         }
                   4863:     }
1.739     raeburn  4864:     my $origstart = $start;
                   4865:     my $origend = $end;
1.357     www      4866: # actually delete
                   4867:     if ($deleteflag) {
1.373     www      4868: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      4869: # modify command to delete the role
1.620     albertel 4870:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      4871:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 4872: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      4873: # set start and finish to negative values for userrolelog
                   4874:            $start=-1;
                   4875:            $end=-1;
                   4876:         }
                   4877:     }
                   4878: # send command
1.349     www      4879:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      4880: # log new user role if status is ok
1.349     www      4881:     if ($answer eq 'ok') {
1.663     raeburn  4882: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  4883: # for course roles, perform group memberships changes triggered by role change.
                   4884:         unless ($role =~ /^gr/) {
                   4885:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   4886:                                              $origstart);
                   4887:         }
1.349     www      4888:     }
                   4889:     return $answer;
1.169     harris41 4890: }
                   4891: 
                   4892: # -------------------------------------------------- Modify user authentication
1.197     www      4893: # Overrides without validation
                   4894: 
1.169     harris41 4895: sub modifyuserauth {
                   4896:     my ($udom,$uname,$umode,$upass)=@_;
                   4897:     my $uhome=&homeserver($uname,$udom);
1.197     www      4898:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   4899:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 4900:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4901:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 4902:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   4903: 		     &escape($upass),$uhome);
1.620     albertel 4904:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      4905:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   4906:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   4907:     &log($udom,,$uname,$uhome,
1.620     albertel 4908:         'Authentication changed by '.$env{'user.domain'}.', '.
                   4909:                                      $env{'user.name'}.', '.$umode.
1.197     www      4910:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 4911:     unless ($reply eq 'ok') {
1.197     www      4912:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 4913: 	return 'error: '.$reply;
                   4914:     }   
1.170     harris41 4915:     return 'ok';
1.80      www      4916: }
                   4917: 
1.81      www      4918: # --------------------------------------------------------------- Modify a user
1.80      www      4919: 
1.81      www      4920: sub modifyuser {
1.206     matthew  4921:     my ($udom,    $uname, $uid,
                   4922:         $umode,   $upass, $first,
                   4923:         $middle,  $last,  $gene,
1.387     www      4924:         $forceid, $desiredhome, $email)=@_;
1.807     albertel 4925:     $udom= &LONCAPA::clean_domain($udom);
                   4926:     $uname=&LONCAPA::clean_username($uname);
1.81      www      4927:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4928:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  4929: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   4930:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   4931:                                      ' desiredhome not specified'). 
1.620     albertel 4932:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4933:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 4934:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      4935: # ----------------------------------------------------------------- Create User
1.406     albertel 4936:     if (($uhome eq 'no_host') && 
                   4937: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      4938:         my $unhome='';
1.844     albertel 4939:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  4940:             $unhome = $desiredhome;
1.620     albertel 4941: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   4942: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  4943:         } else { # load balancing routine for determining $unhome
1.81      www      4944:             my $loadm=10000000;
1.841     albertel 4945: 	    my %servers = &get_servers($udom,'library');
                   4946: 	    foreach my $tryserver (keys(%servers)) {
                   4947: 		my $answer=reply('load',$tryserver);
                   4948: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   4949: 		    $loadm=$answer;
                   4950: 		    $unhome=$tryserver;
                   4951: 		}
1.80      www      4952: 	    }
                   4953:         }
                   4954:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  4955: 	    return 'error: unable to find a home server for '.$uname.
                   4956:                    ' in domain '.$udom;
1.80      www      4957:         }
                   4958:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   4959:                          &escape($upass),$unhome);
                   4960: 	unless ($reply eq 'ok') {
                   4961:             return 'error: '.$reply;
                   4962:         }   
1.230     stredwic 4963:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      4964:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  4965: 	    return 'error: unable verify users home machine.';
1.80      www      4966:         }
1.209     matthew  4967:     }   # End of creation of new user
1.80      www      4968: # ---------------------------------------------------------------------- Add ID
                   4969:     if ($uid) {
                   4970:        $uid=~tr/A-Z/a-z/;
                   4971:        my %uidhash=&idrget($udom,$uname);
1.196     www      4972:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   4973:          && (!$forceid)) {
1.80      www      4974: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  4975: 	      return 'error: user id "'.$uid.'" does not match '.
                   4976:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      4977:           }
                   4978:        } else {
                   4979: 	  &idput($udom,($uname => $uid));
                   4980:        }
                   4981:     }
                   4982: # -------------------------------------------------------------- Add names, etc
1.313     matthew  4983:     my @tmp=&get('environment',
1.134     albertel 4984: 		   ['firstname','middlename','lastname','generation'],
                   4985: 		   $udom,$uname);
1.313     matthew  4986:     my %names;
                   4987:     if ($tmp[0] =~ m/^error:.*/) { 
                   4988:         %names=(); 
                   4989:     } else {
                   4990:         %names = @tmp;
                   4991:     }
1.388     www      4992: #
                   4993: # Make sure to not trash student environment if instructor does not bother
                   4994: # to supply name and email information
                   4995: #
                   4996:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  4997:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      4998:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  4999:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      5000:     if ($email) {
                   5001:        $email=~s/[^\w\@\.\-\,]//gs;
                   5002:        if ($email=~/\@/) { $names{'notification'} = $email;
                   5003: 			   $names{'critnotification'} = $email;
                   5004: 			   $names{'permanentemail'} = $email; }
                   5005:     }
1.134     albertel 5006:     my $reply = &put('environment', \%names, $udom,$uname);
                   5007:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.680     www      5008:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.81      www      5009:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      5010:              $umode.', '.$first.', '.$middle.', '.
                   5011: 	     $last.', '.$gene.' by '.
1.620     albertel 5012:              $env{'user.name'}.' at '.$env{'user.domain'});
1.134     albertel 5013:     return 'ok';
1.80      www      5014: }
                   5015: 
1.81      www      5016: # -------------------------------------------------------------- Modify student
1.80      www      5017: 
1.81      www      5018: sub modifystudent {
                   5019:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.515     raeburn  5020:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
1.455     albertel 5021:     if (!$cid) {
1.620     albertel 5022: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5023: 	    return 'not_in_class';
                   5024: 	}
1.80      www      5025:     }
                   5026: # --------------------------------------------------------------- Make the user
1.81      www      5027:     my $reply=&modifyuser
1.209     matthew  5028: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      5029:          $desiredhome,$email);
1.80      www      5030:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  5031:     # This will cause &modify_student_enrollment to get the uid from the
                   5032:     # students environment
                   5033:     $uid = undef if (!$forceid);
1.455     albertel 5034:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.515     raeburn  5035: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
1.297     matthew  5036:     return $reply;
                   5037: }
                   5038: 
                   5039: sub modify_student_enrollment {
1.515     raeburn  5040:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
1.455     albertel 5041:     my ($cdom,$cnum,$chome);
                   5042:     if (!$cid) {
1.620     albertel 5043: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5044: 	    return 'not_in_class';
                   5045: 	}
1.620     albertel 5046: 	$cdom=$env{'course.'.$cid.'.domain'};
                   5047: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 5048:     } else {
                   5049: 	($cdom,$cnum)=split(/_/,$cid);
                   5050:     }
1.620     albertel 5051:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 5052:     if (!$chome) {
1.457     raeburn  5053: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  5054:     }
1.455     albertel 5055:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  5056:     # Make sure the user exists
1.81      www      5057:     my $uhome=&homeserver($uname,$udom);
                   5058:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5059: 	return 'error: no such user';
                   5060:     }
1.297     matthew  5061:     # Get student data if we were not given enough information
                   5062:     if (!defined($first)  || $first  eq '' || 
                   5063:         !defined($last)   || $last   eq '' || 
                   5064:         !defined($uid)    || $uid    eq '' || 
                   5065:         !defined($middle) || $middle eq '' || 
                   5066:         !defined($gene)   || $gene   eq '') {
1.294     matthew  5067:         # They did not supply us with enough data to enroll the student, so
                   5068:         # we need to pick up more information.
1.297     matthew  5069:         my %tmp = &get('environment',
1.294     matthew  5070:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  5071:                        ,$udom,$uname);
                   5072: 
1.800     albertel 5073:         #foreach my $key (keys(%tmp)) {
                   5074:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 5075:         #}
1.294     matthew  5076:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   5077:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   5078:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  5079:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  5080:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   5081:     }
1.556     albertel 5082:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 5083:     my $reply=cput('classlist',
                   5084: 		   {"$uname:$udom" => 
1.515     raeburn  5085: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 5086: 		   $cdom,$cnum);
1.81      www      5087:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   5088: 	return 'error: '.$reply;
1.652     albertel 5089:     } else {
                   5090: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      5091:     }
1.297     matthew  5092:     # Add student role to user
1.83      www      5093:     my $uurl='/'.$cid;
1.81      www      5094:     $uurl=~s/\_/\//g;
                   5095:     if ($usec) {
                   5096: 	$uurl.='/'.$usec;
                   5097:     }
                   5098:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21      www      5099: }
                   5100: 
1.556     albertel 5101: sub format_name {
                   5102:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   5103:     my $name;
                   5104:     if ($first ne 'lastname') {
                   5105: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   5106:     } else {
                   5107: 	if ($lastname=~/\S/) {
                   5108: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   5109: 	    $name=~s/\s+,/,/;
                   5110: 	} else {
                   5111: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   5112: 	}
                   5113:     }
                   5114:     $name=~s/^\s+//;
                   5115:     $name=~s/\s+$//;
                   5116:     $name=~s/\s+/ /g;
                   5117:     return $name;
                   5118: }
                   5119: 
1.84      www      5120: # ------------------------------------------------- Write to course preferences
                   5121: 
                   5122: sub writecoursepref {
                   5123:     my ($courseid,%prefs)=@_;
                   5124:     $courseid=~s/^\///;
                   5125:     $courseid=~s/\_/\//g;
                   5126:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   5127:     my $chome=homeserver($cnum,$cdomain);
                   5128:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   5129: 	return 'error: no such course';
                   5130:     }
                   5131:     my $cstring='';
1.800     albertel 5132:     foreach my $pref (keys(%prefs)) {
                   5133: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 5134:     }
1.84      www      5135:     $cstring=~s/\&$//;
                   5136:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   5137: }
                   5138: 
                   5139: # ---------------------------------------------------------- Make/modify course
                   5140: 
                   5141: sub createcourse {
1.741     raeburn  5142:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
                   5143:         $course_owner,$crstype)=@_;
1.84      www      5144:     $url=&declutter($url);
                   5145:     my $cid='';
1.264     matthew  5146:     unless (&allowed('ccc',$udom)) {
1.84      www      5147:         return 'refused';
                   5148:     }
                   5149: # ------------------------------------------------------------------- Create ID
1.674     www      5150:    my $uname=int(1+rand(9)).
                   5151:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   5152:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      5153:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   5154: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 5155:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      5156:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5157:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   5158:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 5159:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      5160:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5161:            return 'error: unable to generate unique course-ID';
                   5162:        } 
                   5163:    }
1.264     matthew  5164: # ------------------------------------------------ Check supplied server name
1.620     albertel 5165:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.845     albertel 5166:     if (! &is_library($course_server)) {
1.264     matthew  5167:         return 'error:bad server name '.$course_server;
                   5168:     }
1.84      www      5169: # ------------------------------------------------------------- Make the course
                   5170:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  5171:                       $course_server);
1.84      www      5172:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 5173:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      5174:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5175: 	return 'error: no such course';
                   5176:     }
1.271     www      5177: # ----------------------------------------------------------------- Course made
1.516     raeburn  5178: # log existence
                   5179:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
1.741     raeburn  5180:                  ':'.&escape($inst_code).':'.&escape($course_owner).':'.
                   5181:                   &escape($crstype),$uhome);
1.358     www      5182:     &flushcourselogs();
                   5183: # set toplevel url
1.271     www      5184:     my $topurl=$url;
                   5185:     unless ($nonstandard) {
                   5186: # ------------------------------------------ For standard courses, make top url
                   5187:         my $mapurl=&clutter($url);
1.278     www      5188:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 5189:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      5190: <map>
                   5191: <resource id="1" type="start"></resource>
                   5192: <resource id="2" src="$mapurl"></resource>
                   5193: <resource id="3" type="finish"></resource>
                   5194: <link index="1" from="1" to="2"></link>
                   5195: <link index="2" from="2" to="3"></link>
                   5196: </map>
                   5197: ENDINITMAP
                   5198:         $topurl=&declutter(
1.638     albertel 5199:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      5200:                           );
                   5201:     }
                   5202: # ----------------------------------------------------------- Write preferences
1.84      www      5203:     &writecoursepref($udom.'_'.$uname,
                   5204:                      ('description' => $description,
1.271     www      5205:                       'url'         => $topurl));
1.84      www      5206:     return '/'.$udom.'/'.$uname;
                   5207: }
                   5208: 
1.813     albertel 5209: sub is_course {
                   5210:     my ($cdom,$cnum) = @_;
                   5211:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
                   5212: 				undef,'.');
                   5213:     if (exists($courses{$cdom.'_'.$cnum})) {
                   5214:         return 1;
                   5215:     }
                   5216:     return 0;
                   5217: }
                   5218: 
1.21      www      5219: # ---------------------------------------------------------- Assign Custom Role
                   5220: 
                   5221: sub assigncustomrole {
1.357     www      5222:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21      www      5223:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357     www      5224:                        $end,$start,$deleteflag);
1.21      www      5225: }
                   5226: 
                   5227: # ----------------------------------------------------------------- Revoke Role
                   5228: 
                   5229: sub revokerole {
1.357     www      5230:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21      www      5231:     my $now=time;
1.357     www      5232:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21      www      5233: }
                   5234: 
                   5235: # ---------------------------------------------------------- Revoke Custom Role
                   5236: 
                   5237: sub revokecustomrole {
1.357     www      5238:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21      www      5239:     my $now=time;
1.357     www      5240:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
                   5241:            $deleteflag);
1.17      www      5242: }
                   5243: 
1.533     banghart 5244: # ------------------------------------------------------------ Disk usage
1.535     albertel 5245: sub diskusage {
1.533     banghart 5246:     my ($udom,$uname,$directoryRoot)=@_;
                   5247:     $directoryRoot =~ s/\/$//;
1.535     albertel 5248:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
1.514     albertel 5249:     return $listing;
1.512     banghart 5250: }
                   5251: 
1.566     banghart 5252: sub is_locked {
                   5253:     my ($file_name, $domain, $user) = @_;
                   5254:     my @check;
                   5255:     my $is_locked;
                   5256:     push @check, $file_name;
1.613     albertel 5257:     my %locked = &get('file_permissions',\@check,
1.620     albertel 5258: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 5259:     my ($tmp)=keys(%locked);
                   5260:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  5261:     
1.566     banghart 5262:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  5263:         $is_locked = 'false';
                   5264:         foreach my $entry (@{$locked{$file_name}}) {
                   5265:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  5266:                $is_locked = 'true';
                   5267:                last;
1.745     raeburn  5268:            }
                   5269:        }
1.566     banghart 5270:     } else {
                   5271:         $is_locked = 'false';
                   5272:     }
                   5273: }
                   5274: 
1.759     albertel 5275: sub declutter_portfile {
                   5276:     my ($file) = @_;
1.833     albertel 5277:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 5278:     return $file;
                   5279: }
                   5280: 
1.559     banghart 5281: # ------------------------------------------------------------- Mark as Read Only
                   5282: 
                   5283: sub mark_as_readonly {
                   5284:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 5285:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5286:     my ($tmp)=keys(%current_permissions);
                   5287:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 5288:     foreach my $file (@{$files}) {
1.759     albertel 5289: 	$file = &declutter_portfile($file);
1.561     banghart 5290:         push(@{$current_permissions{$file}},$what);
1.559     banghart 5291:     }
1.613     albertel 5292:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5293:     return;
                   5294: }
                   5295: 
1.572     banghart 5296: # ------------------------------------------------------------Save Selected Files
                   5297: 
                   5298: sub save_selected_files {
                   5299:     my ($user, $path, @files) = @_;
                   5300:     my $filename = $user."savedfiles";
1.573     banghart 5301:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 5302:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 5303:     foreach my $file (@files) {
1.620     albertel 5304:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 5305:     }
                   5306:     foreach my $file (@other_files) {
1.574     banghart 5307:         print (OUT $file."\n");
1.572     banghart 5308:     }
1.574     banghart 5309:     close (OUT);
1.572     banghart 5310:     return 'ok';
                   5311: }
                   5312: 
1.574     banghart 5313: sub clear_selected_files {
                   5314:     my ($user) = @_;
                   5315:     my $filename = $user."savedfiles";
                   5316:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5317:     print (OUT undef);
                   5318:     close (OUT);
                   5319:     return ("ok");    
                   5320: }
                   5321: 
1.572     banghart 5322: sub files_in_path {
                   5323:     my ($user, $path) = @_;
                   5324:     my $filename = $user."savedfiles";
                   5325:     my %return_files;
1.574     banghart 5326:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 5327:     while (my $line_in = <IN>) {
1.574     banghart 5328:         chomp ($line_in);
                   5329:         my @paths_and_file = split (m!/!, $line_in);
                   5330:         my $file_part = pop (@paths_and_file);
                   5331:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 5332:         $path_part.='/';
                   5333:         my $path_and_file = $path_part.$file_part;
                   5334:         if ($path_part eq $path) {
                   5335:             $return_files{$file_part}= 'selected';
                   5336:         }
                   5337:     }
1.574     banghart 5338:     close (IN);
                   5339:     return (\%return_files);
1.572     banghart 5340: }
                   5341: 
                   5342: # called in portfolio select mode, to show files selected NOT in current directory
                   5343: sub files_not_in_path {
                   5344:     my ($user, $path) = @_;
                   5345:     my $filename = $user."savedfiles";
                   5346:     my @return_files;
                   5347:     my $path_part;
1.800     albertel 5348:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5349:     while (my $line = <IN>) {
1.572     banghart 5350:         #ok, I know it's clunky, but I want it to work
1.800     albertel 5351:         my @paths_and_file = split(m|/|, $line);
                   5352:         my $file_part = pop(@paths_and_file);
                   5353:         chomp($file_part);
                   5354:         my $path_part = join('/', @paths_and_file);
1.572     banghart 5355:         $path_part .= '/';
                   5356:         my $path_and_file = $path_part.$file_part;
                   5357:         if ($path_part ne $path) {
1.800     albertel 5358:             push(@return_files, ($path_and_file));
1.572     banghart 5359:         }
                   5360:     }
1.800     albertel 5361:     close(OUT);
1.574     banghart 5362:     return (@return_files);
1.572     banghart 5363: }
                   5364: 
1.745     raeburn  5365: #----------------------------------------------Get portfolio file permissions
1.629     banghart 5366: 
1.745     raeburn  5367: sub get_portfile_permissions {
                   5368:     my ($domain,$user) = @_;
1.613     albertel 5369:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5370:     my ($tmp)=keys(%current_permissions);
                   5371:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5372:     return \%current_permissions;
                   5373: }
                   5374: 
                   5375: #---------------------------------------------Get portfolio file access controls
                   5376: 
1.749     raeburn  5377: sub get_access_controls {
1.745     raeburn  5378:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 5379:     my %access;
                   5380:     my $real_file = $file;
                   5381:     $file =~ s/\.meta$//;
1.745     raeburn  5382:     if (defined($file)) {
1.749     raeburn  5383:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   5384:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 5385:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  5386:             }
                   5387:         }
1.745     raeburn  5388:     } else {
1.749     raeburn  5389:         foreach my $key (keys(%{$current_permissions})) {
                   5390:             if ($key =~ /\0accesscontrol$/) {
                   5391:                 if (defined($group)) {
                   5392:                     if ($key !~ m-^\Q$group\E/-) {
                   5393:                         next;
                   5394:                     }
                   5395:                 }
                   5396:                 my ($fullpath) = split(/\0/,$key);
                   5397:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   5398:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   5399:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   5400:                     }
                   5401:                 }
                   5402:             }
                   5403:         }
                   5404:     }
                   5405:     return %access;
                   5406: }
                   5407: 
                   5408: sub modify_access_controls {
                   5409:     my ($file_name,$changes,$domain,$user)=@_;
                   5410:     my ($outcome,$deloutcome);
                   5411:     my %store_permissions;
                   5412:     my %new_values;
                   5413:     my %new_control;
                   5414:     my %translation;
                   5415:     my @deletions = ();
                   5416:     my $now = time;
                   5417:     if (exists($$changes{'activate'})) {
                   5418:         if (ref($$changes{'activate'}) eq 'HASH') {
                   5419:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   5420:             my $numnew = scalar(@newitems);
                   5421:             for (my $i=0; $i<$numnew; $i++) {
                   5422:                 my $newkey = $newitems[$i];
                   5423:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  5424:                 if ($newkey =~ /^\d+:/) { 
                   5425:                     $newkey =~ s/^(\d+)/$newid/;
                   5426:                     $translation{$1} = $newid;
                   5427:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   5428:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   5429:                     $translation{$1} = $newid;
                   5430:                 }
1.749     raeburn  5431:                 $new_values{$file_name."\0".$newkey} = 
                   5432:                                           $$changes{'activate'}{$newitems[$i]};
                   5433:                 $new_control{$newkey} = $now;
                   5434:             }
                   5435:         }
                   5436:     }
                   5437:     my %todelete;
                   5438:     my %changed_items;
                   5439:     foreach my $action ('delete','update') {
                   5440:         if (exists($$changes{$action})) {
                   5441:             if (ref($$changes{$action}) eq 'HASH') {
                   5442:                 foreach my $key (keys(%{$$changes{$action}})) {
                   5443:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   5444:                     if ($action eq 'delete') { 
                   5445:                         $todelete{$itemnum} = 1;
                   5446:                     } else {
                   5447:                         $changed_items{$itemnum} = $key;
                   5448:                     }
                   5449:                 }
1.745     raeburn  5450:             }
                   5451:         }
1.749     raeburn  5452:     }
                   5453:     # get lock on access controls for file.
                   5454:     my $lockhash = {
                   5455:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   5456:                                                        ':'.$env{'user.domain'},
                   5457:                    }; 
                   5458:     my $tries = 0;
                   5459:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5460:    
                   5461:     while (($gotlock ne 'ok') && $tries <3) {
                   5462:         $tries ++;
                   5463:         sleep 1;
                   5464:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5465:     }
                   5466:     if ($gotlock eq 'ok') {
                   5467:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   5468:         my ($tmp)=keys(%curr_permissions);
                   5469:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   5470:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   5471:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   5472:             if (ref($curr_controls) eq 'HASH') {
                   5473:                 foreach my $control_item (keys(%{$curr_controls})) {
                   5474:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   5475:                     if (defined($todelete{$itemnum})) {
                   5476:                         push(@deletions,$file_name."\0".$control_item);
                   5477:                     } else {
                   5478:                         if (defined($changed_items{$itemnum})) {
                   5479:                             $new_control{$changed_items{$itemnum}} = $now;
                   5480:                             push(@deletions,$file_name."\0".$control_item);
                   5481:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   5482:                         } else {
                   5483:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   5484:                         }
                   5485:                     }
1.745     raeburn  5486:                 }
                   5487:             }
                   5488:         }
1.749     raeburn  5489:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   5490:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   5491:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   5492:         #  remove lock
                   5493:         my @del_lock = ($file_name."\0".'locked_access_records');
                   5494:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  5495:         my ($file,$group);
                   5496:         if (&is_course($domain,$user)) {
                   5497:             ($group,$file) = split(/\//,$file_name,2);
                   5498:         } else {
                   5499:             $file = $file_name;
                   5500:         }
                   5501:         my $sqlresult =
                   5502:             &update_portfolio_table($user,$domain,$file,'portfolio_access',
                   5503:                                     $group);
1.749     raeburn  5504:     } else {
                   5505:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  5506:     }
1.749     raeburn  5507:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  5508: }
                   5509: 
1.827     raeburn  5510: sub make_public_indefinitely {
                   5511:     my ($requrl) = @_;
                   5512:     my $now = time;
                   5513:     my $action = 'activate';
                   5514:     my $aclnum = 0;
                   5515:     if (&is_portfolio_url($requrl)) {
                   5516:         my (undef,$udom,$unum,$file_name,$group) =
                   5517:             &parse_portfolio_url($requrl);
                   5518:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   5519:         my %access_controls = &get_access_controls($current_perms,
                   5520:                                                    $group,$file_name);
                   5521:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   5522:             my ($num,$scope,$end,$start) = 
                   5523:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   5524:             if ($scope eq 'public') {
                   5525:                 if ($start <= $now && $end == 0) {
                   5526:                     $action = 'none';
                   5527:                 } else {
                   5528:                     $action = 'update';
                   5529:                     $aclnum = $num;
                   5530:                 }
                   5531:                 last;
                   5532:             }
                   5533:         }
                   5534:         if ($action eq 'none') {
                   5535:              return 'ok';
                   5536:         } else {
                   5537:             my %changes;
                   5538:             my $newend = 0;
                   5539:             my $newstart = $now;
                   5540:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   5541:             $changes{$action}{$newkey} = {
                   5542:                 type => 'public',
                   5543:                 time => {
                   5544:                     start => $newstart,
                   5545:                     end   => $newend,
                   5546:                 },
                   5547:             };
                   5548:             my ($outcome,$deloutcome,$new_values,$translation) =
                   5549:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   5550:             return $outcome;
                   5551:         }
                   5552:     } else {
                   5553:         return 'invalid';
                   5554:     }
                   5555: }
                   5556: 
1.745     raeburn  5557: #------------------------------------------------------Get Marked as Read Only
                   5558: 
                   5559: sub get_marked_as_readonly {
                   5560:     my ($domain,$user,$what,$group) = @_;
                   5561:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 5562:     my @readonly_files;
1.629     banghart 5563:     my $cmp1=$what;
                   5564:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  5565:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5566:         if (defined($group)) {
                   5567:             if ($file_name !~ m-^\Q$group\E/-) {
                   5568:                 next;
                   5569:             }
                   5570:         }
1.561     banghart 5571:         if (ref($value) eq "ARRAY"){
                   5572:             foreach my $stored_what (@{$value}) {
1.629     banghart 5573:                 my $cmp2=$stored_what;
1.759     albertel 5574:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  5575:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  5576:                 }
1.629     banghart 5577:                 if ($cmp1 eq $cmp2) {
1.561     banghart 5578:                     push(@readonly_files, $file_name);
1.745     raeburn  5579:                     last;
1.563     banghart 5580:                 } elsif (!defined($what)) {
                   5581:                     push(@readonly_files, $file_name);
1.745     raeburn  5582:                     last;
1.561     banghart 5583:                 }
                   5584:             }
1.745     raeburn  5585:         }
1.561     banghart 5586:     }
                   5587:     return @readonly_files;
                   5588: }
1.577     banghart 5589: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 5590: 
1.577     banghart 5591: sub get_marked_as_readonly_hash {
1.745     raeburn  5592:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 5593:     my %readonly_files;
1.745     raeburn  5594:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5595:         if (defined($group)) {
                   5596:             if ($file_name !~ m-^\Q$group\E/-) {
                   5597:                 next;
                   5598:             }
                   5599:         }
1.577     banghart 5600:         if (ref($value) eq "ARRAY"){
                   5601:             foreach my $stored_what (@{$value}) {
1.745     raeburn  5602:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 5603:                     foreach my $lock_descriptor(@{$stored_what}) {
                   5604:                         if ($lock_descriptor eq 'graded') {
                   5605:                             $readonly_files{$file_name} = 'graded';
                   5606:                         } elsif ($lock_descriptor eq 'handback') {
                   5607:                             $readonly_files{$file_name} = 'handback';
                   5608:                         } else {
                   5609:                             if (!exists($readonly_files{$file_name})) {
                   5610:                                 $readonly_files{$file_name} = 'locked';
                   5611:                             }
                   5612:                         }
1.745     raeburn  5613:                     }
1.750     banghart 5614:                 } 
1.577     banghart 5615:             }
                   5616:         } 
                   5617:     }
                   5618:     return %readonly_files;
                   5619: }
1.559     banghart 5620: # ------------------------------------------------------------ Unmark as Read Only
                   5621: 
                   5622: sub unmark_as_readonly {
1.629     banghart 5623:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   5624:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  5625:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 5626:     $file_name = &declutter_portfile($file_name);
1.634     albertel 5627:     my $symb_crs = $what;
                   5628:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  5629:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 5630:     my ($tmp)=keys(%current_permissions);
                   5631:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5632:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 5633:     foreach my $file (@readonly_files) {
1.759     albertel 5634: 	my $clean_file = &declutter_portfile($file);
                   5635: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 5636: 	my $current_locks = $current_permissions{$file};
1.563     banghart 5637:         my @new_locks;
                   5638:         my @del_keys;
                   5639:         if (ref($current_locks) eq "ARRAY"){
                   5640:             foreach my $locker (@{$current_locks}) {
1.632     albertel 5641:                 my $compare=$locker;
1.749     raeburn  5642:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  5643:                     $compare=join('',@{$locker});
1.746     raeburn  5644:                     if ($compare ne $symb_crs) {
                   5645:                         push(@new_locks, $locker);
                   5646:                     }
1.563     banghart 5647:                 }
                   5648:             }
1.650     albertel 5649:             if (scalar(@new_locks) > 0) {
1.563     banghart 5650:                 $current_permissions{$file} = \@new_locks;
                   5651:             } else {
                   5652:                 push(@del_keys, $file);
1.613     albertel 5653:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 5654:                 delete($current_permissions{$file});
1.563     banghart 5655:             }
                   5656:         }
1.561     banghart 5657:     }
1.613     albertel 5658:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5659:     return;
                   5660: }
1.512     banghart 5661: 
1.17      www      5662: # ------------------------------------------------------------ Directory lister
                   5663: 
                   5664: sub dirlist {
1.253     stredwic 5665:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
                   5666: 
1.18      www      5667:     $uri=~s/^\///;
                   5668:     $uri=~s/\/$//;
1.253     stredwic 5669:     my ($udom, $uname);
                   5670:     (undef,$udom,$uname)=split(/\//,$uri);
                   5671:     if(defined($userdomain)) {
                   5672:         $udom = $userdomain;
                   5673:     }
                   5674:     if(defined($username)) {
                   5675:         $uname = $username;
                   5676:     }
                   5677: 
                   5678:     my $dirRoot = $perlvar{'lonDocRoot'};
                   5679:     if(defined($alternateDirectoryRoot)) {
                   5680:         $dirRoot = $alternateDirectoryRoot;
                   5681:         $dirRoot =~ s/\/$//;
1.751     banghart 5682:     }
1.253     stredwic 5683: 
                   5684:     if($udom) {
                   5685:         if($uname) {
1.800     albertel 5686:             my $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   5687: 				 &homeserver($uname,$udom));
1.605     matthew  5688:             my @listing_results;
                   5689:             if ($listing eq 'unknown_cmd') {
1.800     albertel 5690:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   5691: 				  &homeserver($uname,$udom));
1.605     matthew  5692:                 @listing_results = split(/:/,$listing);
                   5693:             } else {
                   5694:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   5695:             }
                   5696:             return @listing_results;
1.253     stredwic 5697:         } elsif(!defined($alternateDirectoryRoot)) {
1.800     albertel 5698:             my %allusers;
1.841     albertel 5699: 	    my %servers = &get_servers($udom,'library');
                   5700: 	    foreach my $tryserver (keys(%servers)) {
                   5701: 		my $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   5702: 				     $udom, $tryserver);
                   5703: 		my @listing_results;
                   5704: 		if ($listing eq 'unknown_cmd') {
                   5705: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   5706: 				      $udom, $tryserver);
                   5707: 		    @listing_results = split(/:/,$listing);
                   5708: 		} else {
                   5709: 		    @listing_results =
                   5710: 			map { &unescape($_); } split(/:/,$listing);
                   5711: 		}
                   5712: 		if ($listing_results[0] ne 'no_such_dir' && 
                   5713: 		    $listing_results[0] ne 'empty'       &&
                   5714: 		    $listing_results[0] ne 'con_lost') {
                   5715: 		    foreach my $line (@listing_results) {
                   5716: 			my ($entry) = split(/&/,$line,2);
                   5717: 			$allusers{$entry} = 1;
                   5718: 		    }
                   5719: 		}
1.253     stredwic 5720:             }
                   5721:             my $alluserstr='';
1.800     albertel 5722:             foreach my $user (sort(keys(%allusers))) {
                   5723:                 $alluserstr.=$user.'&user:';
1.253     stredwic 5724:             }
                   5725:             $alluserstr=~s/:$//;
                   5726:             return split(/:/,$alluserstr);
                   5727:         } else {
1.800     albertel 5728:             return ('missing user name');
1.253     stredwic 5729:         }
                   5730:     } elsif(!defined($alternateDirectoryRoot)) {
1.841     albertel 5731:         my @all_domains = sort(&all_domains());
                   5732:          foreach my $domain (@all_domains) {
                   5733:              $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   5734:          }
                   5735:          return @all_domains;
                   5736:      } else {
1.800     albertel 5737:         return ('missing domain');
1.275     stredwic 5738:     }
                   5739: }
                   5740: 
                   5741: # --------------------------------------------- GetFileTimestamp
                   5742: # This function utilizes dirlist and returns the date stamp for
                   5743: # when it was last modified.  It will also return an error of -1
                   5744: # if an error occurs
                   5745: 
1.410     matthew  5746: ##
                   5747: ## FIXME: This subroutine assumes its caller knows something about the
                   5748: ## directory structure of the home server for the student ($root).
                   5749: ## Not a good assumption to make.  Since this is for looking up files
                   5750: ## in user directories, the full path should be constructed by lond, not
                   5751: ## whatever machine we request data from.
                   5752: ##
1.275     stredwic 5753: sub GetFileTimestamp {
                   5754:     my ($studentDomain,$studentName,$filename,$root)=@_;
1.807     albertel 5755:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   5756:     $studentName   = &LONCAPA::clean_username($studentName);
1.275     stredwic 5757:     my $subdir=$studentName.'__';
                   5758:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   5759:     my $proname="$studentDomain/$subdir/$studentName";
                   5760:     $proname .= '/'.$filename;
1.375     matthew  5761:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
                   5762:                                               $studentName, $root);
1.275     stredwic 5763:     my @stats = split('&', $fileStat);
                   5764:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  5765:         # @stats contains first the filename, then the stat output
                   5766:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 5767:     } else {
                   5768:         return -1;
1.253     stredwic 5769:     }
1.26      www      5770: }
                   5771: 
1.712     albertel 5772: sub stat_file {
                   5773:     my ($uri) = @_;
1.787     albertel 5774:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 5775: 
1.712     albertel 5776:     my ($udom,$uname,$file,$dir);
                   5777:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   5778: 	($udom,$uname,$file) =
1.811     albertel 5779: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 5780: 	$file = 'userfiles/'.$file;
1.740     www      5781: 	$dir = &propath($udom,$uname);
1.712     albertel 5782:     }
                   5783:     if ($uri =~ m-^/res/-) {
                   5784: 	($udom,$uname) = 
1.807     albertel 5785: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 5786: 	$file = $uri;
                   5787:     }
                   5788: 
                   5789:     if (!$udom || !$uname || !$file) {
                   5790: 	# unable to handle the uri
                   5791: 	return ();
                   5792:     }
                   5793: 
                   5794:     my ($result) = &dirlist($file,$udom,$uname,$dir);
                   5795:     my @stats = split('&', $result);
1.721     banghart 5796:     
1.712     albertel 5797:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   5798: 	shift(@stats); #filename is first
                   5799: 	return @stats;
                   5800:     }
                   5801:     return ();
                   5802: }
                   5803: 
1.26      www      5804: # -------------------------------------------------------- Value of a Condition
                   5805: 
1.713     albertel 5806: # gets the value of a specific preevaluated condition
                   5807: #    stored in the string  $env{user.state.<cid>}
                   5808: # or looks up a condition reference in the bighash and if if hasn't
                   5809: # already been evaluated recurses into docondval to get the value of
                   5810: # the condition, then memoizing it to 
                   5811: #   $env{user.state.<cid>.<condition>}
1.40      www      5812: sub directcondval {
                   5813:     my $number=shift;
1.620     albertel 5814:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 5815: 	&Apache::lonuserstate::evalstate();
                   5816:     }
1.713     albertel 5817:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   5818: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   5819:     } elsif ($number =~ /^_/) {
                   5820: 	my $sub_condition;
                   5821: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   5822: 		&GDBM_READER(),0640)) {
                   5823: 	    $sub_condition=$bighash{'conditions'.$number};
                   5824: 	    untie(%bighash);
                   5825: 	}
                   5826: 	my $value = &docondval($sub_condition);
                   5827: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
                   5828: 	return $value;
                   5829:     }
1.620     albertel 5830:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   5831:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      5832:     } else {
                   5833:        return 2;
                   5834:     }
                   5835: }
                   5836: 
1.713     albertel 5837: # get the collection of conditions for this resource
1.26      www      5838: sub condval {
                   5839:     my $condidx=shift;
1.54      www      5840:     my $allpathcond='';
1.713     albertel 5841:     foreach my $cond (split(/\|/,$condidx)) {
                   5842: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   5843: 	    $allpathcond.=
                   5844: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   5845: 	}
1.191     harris41 5846:     }
1.54      www      5847:     $allpathcond=~s/\|$//;
1.713     albertel 5848:     return &docondval($allpathcond);
                   5849: }
                   5850: 
                   5851: #evaluates an expression of conditions
                   5852: sub docondval {
                   5853:     my ($allpathcond) = @_;
                   5854:     my $result=0;
                   5855:     if ($env{'request.course.id'}
                   5856: 	&& defined($allpathcond)) {
                   5857: 	my $operand='|';
                   5858: 	my @stack;
                   5859: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   5860: 	    if ($chunk eq '(') {
                   5861: 		push @stack,($operand,$result);
                   5862: 	    } elsif ($chunk eq ')') {
                   5863: 		my $before=pop @stack;
                   5864: 		if (pop @stack eq '&') {
                   5865: 		    $result=$result>$before?$before:$result;
                   5866: 		} else {
                   5867: 		    $result=$result>$before?$result:$before;
                   5868: 		}
                   5869: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   5870: 		$operand=$chunk;
                   5871: 	    } else {
                   5872: 		my $new=directcondval($chunk);
                   5873: 		if ($operand eq '&') {
                   5874: 		    $result=$result>$new?$new:$result;
                   5875: 		} else {
                   5876: 		    $result=$result>$new?$result:$new;
                   5877: 		}
                   5878: 	    }
                   5879: 	}
1.26      www      5880:     }
                   5881:     return $result;
1.421     albertel 5882: }
                   5883: 
                   5884: # ---------------------------------------------------- Devalidate courseresdata
                   5885: 
                   5886: sub devalidatecourseresdata {
                   5887:     my ($coursenum,$coursedomain)=@_;
                   5888:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 5889:     &devalidate_cache_new('courseres',$hashid);
1.28      www      5890: }
                   5891: 
1.763     www      5892: 
1.200     www      5893: # --------------------------------------------------- Course Resourcedata Query
                   5894: 
1.624     albertel 5895: sub get_courseresdata {
                   5896:     my ($coursenum,$coursedomain)=@_;
1.200     www      5897:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   5898:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 5899:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 5900:     my %dumpreply;
1.417     albertel 5901:     unless (defined($cached)) {
1.624     albertel 5902: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 5903: 	$result=\%dumpreply;
1.251     albertel 5904: 	my ($tmp) = keys(%dumpreply);
                   5905: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 5906: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 5907: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   5908: 	    return $tmp;
1.416     albertel 5909: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 5910: 	    $result=undef;
1.599     albertel 5911: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 5912: 	}
                   5913:     }
1.624     albertel 5914:     return $result;
                   5915: }
                   5916: 
1.633     albertel 5917: sub devalidateuserresdata {
                   5918:     my ($uname,$udom)=@_;
                   5919:     my $hashid="$udom:$uname";
                   5920:     &devalidate_cache_new('userres',$hashid);
                   5921: }
                   5922: 
1.624     albertel 5923: sub get_userresdata {
                   5924:     my ($uname,$udom)=@_;
                   5925:     #most student don\'t have any data set, check if there is some data
                   5926:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   5927: 
                   5928:     my $hashid="$udom:$uname";
                   5929:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   5930:     if (!defined($cached)) {
                   5931: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   5932: 	$result=\%resourcedata;
                   5933: 	&do_cache_new('userres',$hashid,$result,600);
                   5934:     }
                   5935:     my ($tmp)=keys(%$result);
                   5936:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   5937: 	return $result;
                   5938:     }
                   5939:     #error 2 occurs when the .db doesn't exist
                   5940:     if ($tmp!~/error: 2 /) {
1.672     albertel 5941: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 5942: 		 " Trying to get resource data for ".
                   5943: 		 $uname." at ".$udom.": ".
                   5944: 		 $tmp."</font>");
                   5945:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 5946: 	#&EXT_cache_set($udom,$uname);
                   5947: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 5948: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 5949:     }
                   5950:     return $tmp;
                   5951: }
                   5952: 
                   5953: sub resdata {
                   5954:     my ($name,$domain,$type,@which)=@_;
                   5955:     my $result;
                   5956:     if ($type eq 'course') {
                   5957: 	$result=&get_courseresdata($name,$domain);
                   5958:     } elsif ($type eq 'user') {
                   5959: 	$result=&get_userresdata($name,$domain);
                   5960:     }
                   5961:     if (!ref($result)) { return $result; }    
1.251     albertel 5962:     foreach my $item (@which) {
1.417     albertel 5963: 	if (defined($result->{$item})) {
                   5964: 	    return $result->{$item};
1.251     albertel 5965: 	}
1.250     albertel 5966:     }
1.291     albertel 5967:     return undef;
1.200     www      5968: }
                   5969: 
1.379     matthew  5970: #
                   5971: # EXT resource caching routines
                   5972: #
                   5973: 
                   5974: sub clear_EXT_cache_status {
1.383     albertel 5975:     &delenv('cache.EXT.');
1.379     matthew  5976: }
                   5977: 
                   5978: sub EXT_cache_status {
                   5979:     my ($target_domain,$target_user) = @_;
1.383     albertel 5980:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 5981:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  5982:         # We know already the user has no data
                   5983:         return 1;
                   5984:     } else {
                   5985:         return 0;
                   5986:     }
                   5987: }
                   5988: 
                   5989: sub EXT_cache_set {
                   5990:     my ($target_domain,$target_user) = @_;
1.383     albertel 5991:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.633     albertel 5992:     #&appenv($cachename => time);
1.379     matthew  5993: }
                   5994: 
1.28      www      5995: # --------------------------------------------------------- Value of a Variable
1.58      www      5996: sub EXT {
1.715     albertel 5997: 
1.395     albertel 5998:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      5999:     unless ($varname) { return ''; }
1.218     albertel 6000:     #get real user name/domain, courseid and symb
                   6001:     my $courseid;
1.359     albertel 6002:     my $publicuser;
1.427     www      6003:     if ($symbparm) {
                   6004: 	$symbparm=&get_symb_from_alias($symbparm);
                   6005:     }
1.218     albertel 6006:     if (!($uname && $udom)) {
1.790     albertel 6007:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 6008:       if (!$symbparm) {	$symbparm=$cursymb; }
                   6009:     } else {
1.620     albertel 6010: 	$courseid=$env{'request.course.id'};
1.218     albertel 6011:     }
1.48      www      6012:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   6013:     my $rest;
1.320     albertel 6014:     if (defined($therest[0])) {
1.48      www      6015:        $rest=join('.',@therest);
                   6016:     } else {
                   6017:        $rest='';
                   6018:     }
1.320     albertel 6019: 
1.57      www      6020:     my $qualifierrest=$qualifier;
                   6021:     if ($rest) { $qualifierrest.='.'.$rest; }
                   6022:     my $spacequalifierrest=$space;
                   6023:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      6024:     if ($realm eq 'user') {
1.48      www      6025: # --------------------------------------------------------------- user.resource
                   6026: 	if ($space eq 'resource') {
1.651     albertel 6027: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   6028: 		  || defined($Apache::lonhomework::parsing_a_task))
                   6029: 		 &&
1.744     albertel 6030: 		 ($symbparm eq &symbread()) ) {	
                   6031: 		# if we are in the middle of processing the resource the
                   6032: 		# get the value we are planning on committing
                   6033:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   6034:                     return $Apache::lonhomework::results{$qualifierrest};
                   6035:                 } else {
                   6036:                     return $Apache::lonhomework::history{$qualifierrest};
                   6037:                 }
1.335     albertel 6038: 	    } else {
1.359     albertel 6039: 		my %restored;
1.620     albertel 6040: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 6041: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   6042: 		} else {
                   6043: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   6044: 		}
1.335     albertel 6045: 		return $restored{$qualifierrest};
                   6046: 	    }
1.48      www      6047: # ----------------------------------------------------------------- user.access
                   6048:         } elsif ($space eq 'access') {
1.218     albertel 6049: 	    # FIXME - not supporting calls for a specific user
1.48      www      6050:             return &allowed($qualifier,$rest);
                   6051: # ------------------------------------------ user.preferences, user.environment
                   6052:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 6053: 	    if (($uname eq $env{'user.name'}) &&
                   6054: 		($udom eq $env{'user.domain'})) {
                   6055: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 6056: 	    } else {
1.359     albertel 6057: 		my %returnhash;
                   6058: 		if (!$publicuser) {
                   6059: 		    %returnhash=&userenvironment($udom,$uname,
                   6060: 						 $qualifierrest);
                   6061: 		}
1.218     albertel 6062: 		return $returnhash{$qualifierrest};
                   6063: 	    }
1.48      www      6064: # ----------------------------------------------------------------- user.course
                   6065:         } elsif ($space eq 'course') {
1.218     albertel 6066: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 6067:             return $env{join('.',('request.course',$qualifier))};
1.48      www      6068: # ------------------------------------------------------------------- user.role
                   6069:         } elsif ($space eq 'role') {
1.218     albertel 6070: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 6071:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      6072:             if ($qualifier eq 'value') {
                   6073: 		return $role;
                   6074:             } elsif ($qualifier eq 'extent') {
                   6075:                 return $where;
                   6076:             }
                   6077: # ----------------------------------------------------------------- user.domain
                   6078:         } elsif ($space eq 'domain') {
1.218     albertel 6079:             return $udom;
1.48      www      6080: # ------------------------------------------------------------------- user.name
                   6081:         } elsif ($space eq 'name') {
1.218     albertel 6082:             return $uname;
1.48      www      6083: # ---------------------------------------------------- Any other user namespace
1.29      www      6084:         } else {
1.359     albertel 6085: 	    my %reply;
                   6086: 	    if (!$publicuser) {
                   6087: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   6088: 	    }
                   6089: 	    return $reply{$qualifierrest};
1.48      www      6090:         }
1.236     www      6091:     } elsif ($realm eq 'query') {
                   6092: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 6093:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   6094: 						[$spacequalifierrest]);
1.620     albertel 6095: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      6096:    } elsif ($realm eq 'request') {
1.48      www      6097: # ------------------------------------------------------------- request.browser
                   6098:         if ($space eq 'browser') {
1.430     www      6099: 	    if ($qualifier eq 'textremote') {
1.676     albertel 6100: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      6101: 		    return 1;
                   6102: 		} else {
                   6103: 		    return 0;
                   6104: 		}
                   6105: 	    } else {
1.620     albertel 6106: 		return $env{'browser.'.$qualifier};
1.430     www      6107: 	    }
1.57      www      6108: # ------------------------------------------------------------ request.filename
                   6109:         } else {
1.620     albertel 6110:             return $env{'request.'.$spacequalifierrest};
1.29      www      6111:         }
1.28      www      6112:     } elsif ($realm eq 'course') {
1.48      www      6113: # ---------------------------------------------------------- course.description
1.620     albertel 6114:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      6115:     } elsif ($realm eq 'resource') {
1.165     www      6116: 
1.620     albertel 6117: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 6118: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   6119: 	}
1.693     albertel 6120: 
                   6121: 	if ($space eq 'title') {
                   6122: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   6123: 	    return &gettitle($symbparm);
                   6124: 	}
                   6125: 	
                   6126: 	if ($space eq 'map') {
                   6127: 	    my ($map) = &decode_symb($symbparm);
                   6128: 	    return &symbread($map);
                   6129: 	}
                   6130: 
                   6131: 	my ($section, $group, @groups);
1.593     albertel 6132: 	my ($courselevelm,$courselevel);
1.539     albertel 6133: 	if ($symbparm && defined($courseid) && 
1.620     albertel 6134: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      6135: 
1.218     albertel 6136: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      6137: 
1.60      www      6138: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 6139: 	    my $symbp=$symbparm;
1.735     albertel 6140: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 6141: 
                   6142: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   6143: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   6144: 
1.620     albertel 6145: 	    if (($env{'user.name'} eq $uname) &&
                   6146: 		($env{'user.domain'} eq $udom)) {
                   6147: 		$section=$env{'request.course.sec'};
1.733     raeburn  6148:                 @groups = split(/:/,$env{'request.course.groups'});  
                   6149:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 6150: 	    } else {
1.539     albertel 6151: 		if (! defined($usection)) {
1.551     albertel 6152: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 6153: 		} else {
                   6154: 		    $section = $usection;
                   6155: 		}
1.733     raeburn  6156:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 6157: 	    }
                   6158: 
                   6159: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   6160: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   6161: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   6162: 
1.593     albertel 6163: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 6164: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 6165: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      6166: 
1.60      www      6167: # ----------------------------------------------------------- first, check user
1.624     albertel 6168: 
                   6169: 	    my $userreply=&resdata($uname,$udom,'user',
                   6170: 				       ($courselevelr,$courselevelm,
                   6171: 					$courselevel));
                   6172: 	    if (defined($userreply)) { return $userreply; }
1.95      www      6173: 
1.594     albertel 6174: # ------------------------------------------------ second, check some of course
1.684     raeburn  6175:             my $coursereply;
1.691     raeburn  6176:             if (@groups > 0) {
                   6177:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   6178:                                        $mapparm,$spacequalifierrest);
1.684     raeburn  6179:                 if (defined($coursereply)) { return $coursereply; }
                   6180:             }
1.96      www      6181: 
1.684     raeburn  6182: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.624     albertel 6183: 				     $env{'course.'.$courseid.'.domain'},
                   6184: 				     'course',
                   6185: 				     ($seclevelr,$seclevelm,$seclevel,
                   6186: 				      $courselevelr));
1.287     albertel 6187: 	    if (defined($coursereply)) { return $coursereply; }
1.200     www      6188: 
1.60      www      6189: # ------------------------------------------------------ third, check map parms
1.218     albertel 6190: 	    my %parmhash=();
                   6191: 	    my $thisparm='';
                   6192: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 6193: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 6194: 		    &GDBM_READER(),0640)) {
1.218     albertel 6195: 		$thisparm=$parmhash{$symbparm};
                   6196: 		untie(%parmhash);
                   6197: 	    }
                   6198: 	    if ($thisparm) { return $thisparm; }
                   6199: 	}
1.594     albertel 6200: # ------------------------------------------ fourth, look in resource metadata
1.71      www      6201: 
1.218     albertel 6202: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 6203: 	my $filename;
                   6204: 	if (!$symbparm) { $symbparm=&symbread(); }
                   6205: 	if ($symbparm) {
1.409     www      6206: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 6207: 	} else {
1.620     albertel 6208: 	    $filename=$env{'request.filename'};
1.282     albertel 6209: 	}
                   6210: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.288     albertel 6211: 	if (defined($metadata)) { return $metadata; }
1.282     albertel 6212: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.288     albertel 6213: 	if (defined($metadata)) { return $metadata; }
1.142     www      6214: 
1.594     albertel 6215: # ---------------------------------------------- fourth, look in rest pf course
1.593     albertel 6216: 	if ($symbparm && defined($courseid) && 
1.620     albertel 6217: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 6218: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   6219: 				     $env{'course.'.$courseid.'.domain'},
                   6220: 				     'course',
                   6221: 				     ($courselevelm,$courselevel));
1.593     albertel 6222: 	    if (defined($coursereply)) { return $coursereply; }
                   6223: 	}
1.145     www      6224: # ------------------------------------------------------------------ Cascade up
1.218     albertel 6225: 	unless ($space eq '0') {
1.336     albertel 6226: 	    my @parts=split(/_/,$space);
                   6227: 	    my $id=pop(@parts);
                   6228: 	    my $part=join('_',@parts);
                   6229: 	    if ($part eq '') { $part='0'; }
                   6230: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 6231: 				 $symbparm,$udom,$uname,$section,1);
1.337     albertel 6232: 	    if (defined($partgeneral)) { return $partgeneral; }
1.218     albertel 6233: 	}
1.395     albertel 6234: 	if ($recurse) { return undef; }
                   6235: 	my $pack_def=&packages_tab_default($filename,$varname);
                   6236: 	if (defined($pack_def)) { return $pack_def; }
1.71      www      6237: 
1.48      www      6238: # ---------------------------------------------------- Any other user namespace
                   6239:     } elsif ($realm eq 'environment') {
                   6240: # ----------------------------------------------------------------- environment
1.620     albertel 6241: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   6242: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 6243: 	} else {
1.770     albertel 6244: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   6245: 		return '';
                   6246: 	    }
1.219     albertel 6247: 	    my %returnhash=&userenvironment($udom,$uname,
                   6248: 					    $spacequalifierrest);
                   6249: 	    return $returnhash{$spacequalifierrest};
                   6250: 	}
1.28      www      6251:     } elsif ($realm eq 'system') {
1.48      www      6252: # ----------------------------------------------------------------- system.time
                   6253: 	if ($space eq 'time') {
                   6254: 	    return time;
                   6255:         }
1.696     albertel 6256:     } elsif ($realm eq 'server') {
                   6257: # ----------------------------------------------------------------- system.time
                   6258: 	if ($space eq 'name') {
                   6259: 	    return $ENV{'SERVER_NAME'};
                   6260:         }
1.28      www      6261:     }
1.48      www      6262:     return '';
1.61      www      6263: }
                   6264: 
1.691     raeburn  6265: sub check_group_parms {
                   6266:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   6267:     my @groupitems = ();
                   6268:     my $resultitem;
                   6269:     my @levels = ($symbparm,$mapparm,$what);
                   6270:     foreach my $group (@{$groups}) {
                   6271:         foreach my $level (@levels) {
                   6272:              my $item = $courseid.'.['.$group.'].'.$level;
                   6273:              push(@groupitems,$item);
                   6274:         }
                   6275:     }
                   6276:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   6277:                             $env{'course.'.$courseid.'.domain'},
                   6278:                                      'course',@groupitems);
                   6279:     return $coursereply;
                   6280: }
                   6281: 
                   6282: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  6283:     my ($courseid,@groups) = @_;
                   6284:     @groups = sort(@groups);
1.691     raeburn  6285:     return @groups;
                   6286: }
                   6287: 
1.395     albertel 6288: sub packages_tab_default {
                   6289:     my ($uri,$varname)=@_;
                   6290:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 6291: 
                   6292:     my (@extension,@specifics,$do_default);
                   6293:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 6294: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 6295: 	if ($pack_type eq 'default') {
                   6296: 	    $do_default=1;
                   6297: 	} elsif ($pack_type eq 'extension') {
                   6298: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.848     albertel 6299: 	} elsif ($pack_part eq $part) {
                   6300: 	    # only look at packages defaults for packages that this id is
1.738     albertel 6301: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   6302: 	}
                   6303:     }
                   6304:     # first look for a package that matches the requested part id
                   6305:     foreach my $package (@specifics) {
                   6306: 	my (undef,$pack_type,$pack_part)=@{$package};
                   6307: 	next if ($pack_part ne $part);
                   6308: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6309: 	    return $packagetab{"$pack_type&$name&default"};
                   6310: 	}
                   6311:     }
                   6312:     # look for any possible matching non extension_ package
                   6313:     foreach my $package (@specifics) {
                   6314: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 6315: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6316: 	    return $packagetab{"$pack_type&$name&default"};
                   6317: 	}
1.585     albertel 6318: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 6319: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   6320: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 6321: 	}
                   6322:     }
1.738     albertel 6323:     # look for any posible extension_ match
                   6324:     foreach my $package (@extension) {
                   6325: 	my ($package,$pack_type)=@{$package};
                   6326: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6327: 	    return $packagetab{"$pack_type&$name&default"};
                   6328: 	}
                   6329: 	if (defined($packagetab{$package."&$name&default"})) {
                   6330: 	    return $packagetab{$package."&$name&default"};
                   6331: 	}
                   6332:     }
                   6333:     # look for a global default setting
                   6334:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   6335: 	return $packagetab{"default&$name&default"};
                   6336:     }
1.395     albertel 6337:     return undef;
                   6338: }
                   6339: 
1.334     albertel 6340: sub add_prefix_and_part {
                   6341:     my ($prefix,$part)=@_;
                   6342:     my $keyroot;
                   6343:     if (defined($prefix) && $prefix !~ /^__/) {
                   6344: 	# prefix that has a part already
                   6345: 	$keyroot=$prefix;
                   6346:     } elsif (defined($prefix)) {
                   6347: 	# prefix that is missing a part
                   6348: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   6349:     } else {
                   6350: 	# no prefix at all
                   6351: 	if (defined($part)) { $keyroot='_'.$part; }
                   6352:     }
                   6353:     return $keyroot;
                   6354: }
                   6355: 
1.71      www      6356: # ---------------------------------------------------------------- Get metadata
                   6357: 
1.599     albertel 6358: my %metaentry;
1.71      www      6359: sub metadata {
1.176     www      6360:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      6361:     $uri=&declutter($uri);
1.288     albertel 6362:     # if it is a non metadata possible uri return quickly
1.529     albertel 6363:     if (($uri eq '') || 
                   6364: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 6365: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.423     albertel 6366:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
1.807     albertel 6367: 	($uri =~ m|home/$match_username/public_html/|)) {
1.468     albertel 6368: 	return undef;
1.288     albertel 6369:     }
1.73      www      6370:     my $filename=$uri;
                   6371:     $uri=~s/\.meta$//;
1.172     www      6372: #
                   6373: # Is the metadata already cached?
1.177     www      6374: # Look at timestamp of caching
1.172     www      6375: # Everything is cached by the main uri, libraries are never directly cached
                   6376: #
1.428     albertel 6377:     if (!defined($liburi)) {
1.599     albertel 6378: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 6379: 	if (defined($cached)) { return $result->{':'.$what}; }
                   6380:     }
                   6381:     {
1.172     www      6382: #
                   6383: # Is this a recursive call for a library?
                   6384: #
1.599     albertel 6385: #	if (! exists($metacache{$uri})) {
                   6386: #	    $metacache{$uri}={};
                   6387: #	}
1.171     www      6388:         if ($liburi) {
                   6389: 	    $liburi=&declutter($liburi);
                   6390:             $filename=$liburi;
1.401     bowersj2 6391:         } else {
1.599     albertel 6392: 	    &devalidate_cache_new('meta',$uri);
                   6393: 	    undef(%metaentry);
1.401     bowersj2 6394: 	}
1.140     www      6395:         my %metathesekeys=();
1.73      www      6396:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 6397: 	my $metastring;
1.768     albertel 6398: 	if ($uri !~ m -^(editupload)/-) {
1.543     albertel 6399: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 6400: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 6401: 	    $metastring=&getfile($file);
1.489     albertel 6402: 	}
1.208     albertel 6403:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      6404:         my $token;
1.140     www      6405:         undef %metathesekeys;
1.71      www      6406:         while ($token=$parser->get_token) {
1.339     albertel 6407: 	    if ($token->[0] eq 'S') {
                   6408: 		if (defined($token->[2]->{'package'})) {
1.172     www      6409: #
                   6410: # This is a package - get package info
                   6411: #
1.339     albertel 6412: 		    my $package=$token->[2]->{'package'};
                   6413: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6414: 		    if (defined($token->[2]->{'id'})) { 
                   6415: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   6416: 		    }
1.599     albertel 6417: 		    if ($metaentry{':packages'}) {
                   6418: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 6419: 		    } else {
1.599     albertel 6420: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 6421: 		    }
1.736     albertel 6422: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 6423: 			my $part=$keyroot;
                   6424: 			$part=~s/^\_//;
1.736     albertel 6425: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   6426: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   6427: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 6428: 			    # ignore package.tab specified default values
                   6429:                             # here &package_tab_default() will fetch those
                   6430: 			    if ($subp eq 'default') { next; }
1.736     albertel 6431: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 6432: 			    my $unikey;
                   6433: 			    if ($pack =~ /_0$/) {
                   6434: 				$unikey='parameter_0_'.$name;
                   6435: 				$part=0;
                   6436: 			    } else {
                   6437: 				$unikey='parameter'.$keyroot.'_'.$name;
                   6438: 			    }
1.339     albertel 6439: 			    if ($subp eq 'display') {
                   6440: 				$value.=' [Part: '.$part.']';
                   6441: 			    }
1.599     albertel 6442: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 6443: 			    $metathesekeys{$unikey}=1;
1.599     albertel 6444: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6445: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 6446: 			    }
1.599     albertel 6447: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   6448: 				$metaentry{':'.$unikey}=
                   6449: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 6450: 			    }
1.339     albertel 6451: 			}
                   6452: 		    }
                   6453: 		} else {
1.172     www      6454: #
                   6455: # This is not a package - some other kind of start tag
1.339     albertel 6456: #
                   6457: 		    my $entry=$token->[1];
                   6458: 		    my $unikey;
                   6459: 		    if ($entry eq 'import') {
                   6460: 			$unikey='';
                   6461: 		    } else {
                   6462: 			$unikey=$entry;
                   6463: 		    }
                   6464: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6465: 
                   6466: 		    if (defined($token->[2]->{'id'})) { 
                   6467: 			$unikey.='_'.$token->[2]->{'id'}; 
                   6468: 		    }
1.175     www      6469: 
1.339     albertel 6470: 		    if ($entry eq 'import') {
1.175     www      6471: #
                   6472: # Importing a library here
1.339     albertel 6473: #
                   6474: 			if ($depthcount<20) {
                   6475: 			    my $location=$parser->get_text('/import');
                   6476: 			    my $dir=$filename;
                   6477: 			    $dir=~s|[^/]*$||;
                   6478: 			    $location=&filelocation($dir,$location);
1.736     albertel 6479: 			    my $metadata = 
                   6480: 				&metadata($uri,'keys', $location,$unikey,
                   6481: 					  $depthcount+1);
                   6482: 			    foreach my $meta (split(',',$metadata)) {
                   6483: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   6484: 				$metathesekeys{$meta}=1;
1.339     albertel 6485: 			    }
                   6486: 			}
                   6487: 		    } else { 
                   6488: 			
                   6489: 			if (defined($token->[2]->{'name'})) { 
                   6490: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   6491: 			}
                   6492: 			$metathesekeys{$unikey}=1;
1.736     albertel 6493: 			foreach my $param (@{$token->[3]}) {
                   6494: 			    $metaentry{':'.$unikey.'.'.$param} =
                   6495: 				$token->[2]->{$param};
1.339     albertel 6496: 			}
                   6497: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 6498: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 6499: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   6500: 		 # only ws inside the tag, and not in default, so use default
                   6501: 		 # as value
1.599     albertel 6502: 			    $metaentry{':'.$unikey}=$default;
1.339     albertel 6503: 			} else {
1.321     albertel 6504: 		  # either something interesting inside the tag or default
                   6505:                   # uninteresting
1.599     albertel 6506: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 6507: 			}
1.172     www      6508: # end of not-a-package not-a-library import
1.339     albertel 6509: 		    }
1.172     www      6510: # end of not-a-package start tag
1.339     albertel 6511: 		}
1.172     www      6512: # the next is the end of "start tag"
1.339     albertel 6513: 	    }
                   6514: 	}
1.483     albertel 6515: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.737     albertel 6516: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 6517: 	    #no specific packages #how's our extension
                   6518: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 6519: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 6520: 					 \%metathesekeys);
                   6521: 	}
1.599     albertel 6522: 	if (!exists($metaentry{':packages'})) {
1.737     albertel 6523: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 6524: 		#no specific packages well let's get default then
                   6525: 		if ($key!~/^default&/) { next; }
1.488     albertel 6526: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 6527: 					     \%metathesekeys);
                   6528: 	    }
                   6529: 	}
1.338     www      6530: # are there custom rights to evaluate
1.599     albertel 6531: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 6532: 
1.338     www      6533:     #
                   6534:     # Importing a rights file here
1.339     albertel 6535:     #
                   6536: 	    unless ($depthcount) {
1.599     albertel 6537: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 6538: 		my $dir=$filename;
                   6539: 		$dir=~s|[^/]*$||;
                   6540: 		$location=&filelocation($dir,$location);
1.736     albertel 6541: 		my $rights_metadata =
                   6542: 		    &metadata($uri,'keys',$location,'_rights',
                   6543: 			      $depthcount+1);
                   6544: 		foreach my $rights (split(',',$rights_metadata)) {
                   6545: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   6546: 		    $metathesekeys{$rights}=1;
1.339     albertel 6547: 		}
                   6548: 	    }
                   6549: 	}
1.737     albertel 6550: 	# uniqifiy package listing
                   6551: 	my %seen;
                   6552: 	my @uniq_packages =
                   6553: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   6554: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   6555: 
                   6556: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 6557: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   6558: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.699     albertel 6559: 	&do_cache_new('meta',$uri,\%metaentry,60*60);
1.177     www      6560: # this is the end of "was not already recently cached
1.71      www      6561:     }
1.599     albertel 6562:     return $metaentry{':'.$what};
1.261     albertel 6563: }
                   6564: 
1.488     albertel 6565: sub metadata_create_package_def {
1.483     albertel 6566:     my ($uri,$key,$package,$metathesekeys)=@_;
                   6567:     my ($pack,$name,$subp)=split(/\&/,$key);
                   6568:     if ($subp eq 'default') { next; }
                   6569:     
1.599     albertel 6570:     if (defined($metaentry{':packages'})) {
                   6571: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 6572:     } else {
1.599     albertel 6573: 	$metaentry{':packages'}=$package;
1.483     albertel 6574:     }
                   6575:     my $value=$packagetab{$key};
                   6576:     my $unikey;
                   6577:     $unikey='parameter_0_'.$name;
1.599     albertel 6578:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 6579:     $$metathesekeys{$unikey}=1;
1.599     albertel 6580:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6581: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 6582:     }
1.599     albertel 6583:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   6584: 	$metaentry{':'.$unikey}=
                   6585: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 6586:     }
                   6587: }
                   6588: 
1.261     albertel 6589: sub metadata_generate_part0 {
                   6590:     my ($metadata,$metacache,$uri) = @_;
                   6591:     my %allnames;
1.737     albertel 6592:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 6593: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 6594: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   6595: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 6596: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 6597: 	    $allnames{$name}=$part;
                   6598: 	  }
                   6599: 	}
                   6600:     }
                   6601:     foreach my $name (keys(%allnames)) {
                   6602:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 6603:       my $key=":parameter_0_$name";
1.261     albertel 6604:       $$metacache{"$key.part"}='0';
                   6605:       $$metacache{"$key.name"}=$name;
1.428     albertel 6606:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 6607: 					   $allnames{$name}.'_'.$name.
                   6608: 					   '.type'};
1.428     albertel 6609:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 6610: 			     '.display'};
1.644     www      6611:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 6612:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 6613:       $$metacache{"$key.display"}=$olddis;
                   6614:     }
1.71      www      6615: }
                   6616: 
1.764     albertel 6617: # ------------------------------------------------------ Devalidate title cache
                   6618: 
                   6619: sub devalidate_title_cache {
                   6620:     my ($url)=@_;
                   6621:     if (!$env{'request.course.id'}) { return; }
                   6622:     my $symb=&symbread($url);
                   6623:     if (!$symb) { return; }
                   6624:     my $key=$env{'request.course.id'}."\0".$symb;
                   6625:     &devalidate_cache_new('title',$key);
                   6626: }
                   6627: 
1.301     www      6628: # ------------------------------------------------- Get the title of a resource
                   6629: 
                   6630: sub gettitle {
                   6631:     my $urlsymb=shift;
                   6632:     my $symb=&symbread($urlsymb);
1.534     albertel 6633:     if ($symb) {
1.620     albertel 6634: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 6635: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 6636: 	if (defined($cached)) { 
                   6637: 	    return $result;
                   6638: 	}
1.534     albertel 6639: 	my ($map,$resid,$url)=&decode_symb($symb);
                   6640: 	my $title='';
                   6641: 	my %bighash;
1.620     albertel 6642: 	if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.534     albertel 6643: 		&GDBM_READER(),0640)) {
                   6644: 	    my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   6645: 	    $title=$bighash{'title_'.$mapid.'.'.$resid};
                   6646: 	    untie %bighash;
                   6647: 	}
                   6648: 	$title=~s/\&colon\;/\:/gs;
                   6649: 	if ($title) {
1.599     albertel 6650: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 6651: 	}
                   6652: 	$urlsymb=$url;
                   6653:     }
                   6654:     my $title=&metadata($urlsymb,'title');
                   6655:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   6656:     return $title;
1.301     www      6657: }
1.613     albertel 6658: 
1.614     albertel 6659: sub get_slot {
                   6660:     my ($which,$cnum,$cdom)=@_;
                   6661:     if (!$cnum || !$cdom) {
1.790     albertel 6662: 	(undef,my $courseid)=&whichuser();
1.620     albertel 6663: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   6664: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 6665:     }
1.703     albertel 6666:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   6667:     my %slotinfo;
                   6668:     if (exists($remembered{$key})) {
                   6669: 	$slotinfo{$which} = $remembered{$key};
                   6670:     } else {
                   6671: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   6672: 	&Apache::lonhomework::showhash(%slotinfo);
                   6673: 	my ($tmp)=keys(%slotinfo);
                   6674: 	if ($tmp=~/^error:/) { return (); }
                   6675: 	$remembered{$key} = $slotinfo{$which};
                   6676:     }
1.616     albertel 6677:     if (ref($slotinfo{$which}) eq 'HASH') {
                   6678: 	return %{$slotinfo{$which}};
                   6679:     }
                   6680:     return $slotinfo{$which};
1.614     albertel 6681: }
1.31      www      6682: # ------------------------------------------------- Update symbolic store links
                   6683: 
                   6684: sub symblist {
                   6685:     my ($mapname,%newhash)=@_;
1.438     www      6686:     $mapname=&deversion(&declutter($mapname));
1.31      www      6687:     my %hash;
1.620     albertel 6688:     if (($env{'request.course.fn'}) && (%newhash)) {
                   6689:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6690:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 6691: 	    foreach my $url (keys %newhash) {
                   6692: 		next if ($url eq 'last_known'
                   6693: 			 && $env{'form.no_update_last_known'});
                   6694: 		$hash{declutter($url)}=&encode_symb($mapname,
                   6695: 						    $newhash{$url}->[1],
                   6696: 						    $newhash{$url}->[0]);
1.191     harris41 6697:             }
1.31      www      6698:             if (untie(%hash)) {
                   6699: 		return 'ok';
                   6700:             }
                   6701:         }
                   6702:     }
                   6703:     return 'error';
1.212     www      6704: }
                   6705: 
                   6706: # --------------------------------------------------------------- Verify a symb
                   6707: 
                   6708: sub symbverify {
1.510     www      6709:     my ($symb,$thisurl)=@_;
                   6710:     my $thisfn=$thisurl;
1.439     www      6711:     $thisfn=&declutter($thisfn);
1.215     www      6712: # direct jump to resource in page or to a sequence - will construct own symbs
                   6713:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   6714: # check URL part
1.409     www      6715:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      6716: 
1.431     www      6717:     unless ($url eq $thisfn) { return 0; }
1.213     www      6718: 
1.216     www      6719:     $symb=&symbclean($symb);
1.510     www      6720:     $thisurl=&deversion($thisurl);
1.439     www      6721:     $thisfn=&deversion($thisfn);
1.213     www      6722: 
                   6723:     my %bighash;
                   6724:     my $okay=0;
1.431     www      6725: 
1.620     albertel 6726:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6727:                             &GDBM_READER(),0640)) {
1.510     www      6728:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      6729:         unless ($ids) { 
1.510     www      6730:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      6731:         }
                   6732:         if ($ids) {
                   6733: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 6734: 	    foreach my $id (split(/\,/,$ids)) {
                   6735: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      6736:                if (
                   6737:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   6738:    eq $symb) { 
1.620     albertel 6739: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 6740: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 6741: 		       $okay=1; 
                   6742: 		   }
                   6743: 	       }
1.216     www      6744: 	   }
                   6745:         }
1.213     www      6746: 	untie(%bighash);
                   6747:     }
                   6748:     return $okay;
1.31      www      6749: }
                   6750: 
1.210     www      6751: # --------------------------------------------------------------- Clean-up symb
                   6752: 
                   6753: sub symbclean {
                   6754:     my $symb=shift;
1.568     albertel 6755:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      6756: # remove version from map
                   6757:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      6758: 
1.210     www      6759: # remove version from URL
                   6760:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      6761: 
1.507     www      6762: # remove wrapper
                   6763: 
1.510     www      6764:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 6765:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      6766:     return $symb;
1.409     www      6767: }
                   6768: 
                   6769: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 6770: 
                   6771: sub encode_symb {
                   6772:     my ($map,$resid,$url)=@_;
                   6773:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   6774: }
1.409     www      6775: 
                   6776: sub decode_symb {
1.568     albertel 6777:     my $symb=shift;
                   6778:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   6779:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      6780:     return (&fixversion($map),$resid,&fixversion($url));
                   6781: }
                   6782: 
                   6783: sub fixversion {
                   6784:     my $fn=shift;
1.609     banghart 6785:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      6786:     my %bighash;
                   6787:     my $uri=&clutter($fn);
1.620     albertel 6788:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      6789: # is this cached?
1.599     albertel 6790:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      6791:     if (defined($cached)) { return $result; }
                   6792: # unfortunately not cached, or expired
1.620     albertel 6793:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      6794: 	    &GDBM_READER(),0640)) {
                   6795:  	if ($bighash{'version_'.$uri}) {
                   6796:  	    my $version=$bighash{'version_'.$uri};
1.444     www      6797:  	    unless (($version eq 'mostrecent') || 
                   6798: 		    ($version==&getversion($uri))) {
1.440     www      6799:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   6800:  	    }
                   6801:  	}
                   6802:  	untie %bighash;
1.413     www      6803:     }
1.599     albertel 6804:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      6805: }
                   6806: 
                   6807: sub deversion {
                   6808:     my $url=shift;
                   6809:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   6810:     return $url;
1.210     www      6811: }
                   6812: 
1.31      www      6813: # ------------------------------------------------------ Return symb list entry
                   6814: 
                   6815: sub symbread {
1.249     www      6816:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 6817:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 6818:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      6819: # no filename provided? try from environment
1.44      www      6820:     unless ($thisfn) {
1.620     albertel 6821:         if ($env{'request.symb'}) {
                   6822: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 6823: 	}
1.620     albertel 6824: 	$thisfn=$env{'request.filename'};
1.44      www      6825:     }
1.569     albertel 6826:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      6827: # is that filename actually a symb? Verify, clean, and return
                   6828:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 6829: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 6830: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 6831: 	}
1.242     www      6832:     }
1.44      www      6833:     $thisfn=declutter($thisfn);
1.31      www      6834:     my %hash;
1.37      www      6835:     my %bighash;
                   6836:     my $syval='';
1.620     albertel 6837:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  6838:         my $targetfn = $thisfn;
1.609     banghart 6839:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  6840:             $targetfn = 'adm/wrapper/'.$thisfn;
                   6841:         }
1.687     albertel 6842: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   6843: 	    $targetfn=$1;
                   6844: 	}
1.620     albertel 6845:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6846:                       &GDBM_READER(),0640)) {
1.481     raeburn  6847: 	    $syval=$hash{$targetfn};
1.37      www      6848:             untie(%hash);
                   6849:         }
                   6850: # ---------------------------------------------------------- There was an entry
                   6851:         if ($syval) {
1.601     albertel 6852: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 6853: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.601     albertel 6854: 		    #&appenv('request.ambiguous' => $thisfn);
1.620     albertel 6855: 		    #return $env{$cache_str}='';
1.601     albertel 6856: 		#}    
                   6857: 		#$syval.=$1;
                   6858: 	    #}
1.37      www      6859:         } else {
                   6860: # ------------------------------------------------------- Was not in symb table
1.620     albertel 6861:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6862:                             &GDBM_READER(),0640)) {
1.37      www      6863: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      6864:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      6865:               unless ($ids) { 
                   6866:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      6867:               }
                   6868:               unless ($ids) {
                   6869: # alias?
                   6870: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      6871:               }
1.37      www      6872:               if ($ids) {
                   6873: # ------------------------------------------------------------------- Has ID(s)
                   6874:                  my @possibilities=split(/\,/,$ids);
1.39      www      6875:                  if ($#possibilities==0) {
                   6876: # ----------------------------------------------- There is only one possibility
1.37      www      6877: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 6878: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6879: 						    $resid,$thisfn);
1.249     www      6880:                  } elsif (!$donotrecurse) {
1.39      www      6881: # ------------------------------------------ There is more than one possibility
                   6882:                      my $realpossible=0;
1.800     albertel 6883:                      foreach my $id (@possibilities) {
                   6884: 			 my $file=$bighash{'src_'.$id};
1.39      www      6885:                          if (&allowed('bre',$file)) {
1.800     albertel 6886:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      6887:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   6888: 				$realpossible++;
1.626     albertel 6889:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6890: 						    $resid,$thisfn);
1.39      www      6891:                             }
                   6892: 			 }
1.191     harris41 6893:                      }
1.39      www      6894: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      6895:                  } else {
                   6896:                      $syval='';
1.37      www      6897:                  }
                   6898: 	      }
                   6899:               untie(%bighash)
1.481     raeburn  6900:            }
1.31      www      6901:         }
1.62      www      6902:         if ($syval) {
1.620     albertel 6903: 	    return $env{$cache_str}=$syval;
1.62      www      6904:         }
1.31      www      6905:     }
1.44      www      6906:     &appenv('request.ambiguous' => $thisfn);
1.620     albertel 6907:     return $env{$cache_str}='';
1.31      www      6908: }
                   6909: 
                   6910: # ---------------------------------------------------------- Return random seed
                   6911: 
1.32      www      6912: sub numval {
                   6913:     my $txt=shift;
                   6914:     $txt=~tr/A-J/0-9/;
                   6915:     $txt=~tr/a-j/0-9/;
                   6916:     $txt=~tr/K-T/0-9/;
                   6917:     $txt=~tr/k-t/0-9/;
                   6918:     $txt=~tr/U-Z/0-5/;
                   6919:     $txt=~tr/u-z/0-5/;
                   6920:     $txt=~s/\D//g;
1.564     albertel 6921:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      6922:     return int($txt);
1.368     albertel 6923: }
                   6924: 
1.484     albertel 6925: sub numval2 {
                   6926:     my $txt=shift;
                   6927:     $txt=~tr/A-J/0-9/;
                   6928:     $txt=~tr/a-j/0-9/;
                   6929:     $txt=~tr/K-T/0-9/;
                   6930:     $txt=~tr/k-t/0-9/;
                   6931:     $txt=~tr/U-Z/0-5/;
                   6932:     $txt=~tr/u-z/0-5/;
                   6933:     $txt=~s/\D//g;
                   6934:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   6935:     my $total;
                   6936:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 6937:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 6938:     return int($total);
                   6939: }
                   6940: 
1.575     albertel 6941: sub numval3 {
                   6942:     use integer;
                   6943:     my $txt=shift;
                   6944:     $txt=~tr/A-J/0-9/;
                   6945:     $txt=~tr/a-j/0-9/;
                   6946:     $txt=~tr/K-T/0-9/;
                   6947:     $txt=~tr/k-t/0-9/;
                   6948:     $txt=~tr/U-Z/0-5/;
                   6949:     $txt=~tr/u-z/0-5/;
                   6950:     $txt=~s/\D//g;
                   6951:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   6952:     my $total;
                   6953:     foreach my $val (@txts) { $total+=$val; }
                   6954:     if ($_64bit) { $total=(($total<<32)>>32); }
                   6955:     return $total;
                   6956: }
                   6957: 
1.675     albertel 6958: sub digest {
                   6959:     my ($data)=@_;
                   6960:     my $digest=&Digest::MD5::md5($data);
                   6961:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   6962:     my ($e,$f);
                   6963:     {
                   6964:         use integer;
                   6965:         $e=($a+$b);
                   6966:         $f=($c+$d);
                   6967:         if ($_64bit) {
                   6968:             $e=(($e<<32)>>32);
                   6969:             $f=(($f<<32)>>32);
                   6970:         }
                   6971:     }
                   6972:     if (wantarray) {
                   6973: 	return ($e,$f);
                   6974:     } else {
                   6975: 	my $g;
                   6976: 	{
                   6977: 	    use integer;
                   6978: 	    $g=($e+$f);
                   6979: 	    if ($_64bit) {
                   6980: 		$g=(($g<<32)>>32);
                   6981: 	    }
                   6982: 	}
                   6983: 	return $g;
                   6984:     }
                   6985: }
                   6986: 
1.368     albertel 6987: sub latest_rnd_algorithm_id {
1.675     albertel 6988:     return '64bit5';
1.366     albertel 6989: }
1.32      www      6990: 
1.503     albertel 6991: sub get_rand_alg {
                   6992:     my ($courseid)=@_;
1.790     albertel 6993:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 6994:     if ($courseid) {
1.620     albertel 6995: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 6996:     }
                   6997:     return &latest_rnd_algorithm_id();
                   6998: }
                   6999: 
1.562     albertel 7000: sub validCODE {
                   7001:     my ($CODE)=@_;
                   7002:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   7003:     return 0;
                   7004: }
                   7005: 
1.491     albertel 7006: sub getCODE {
1.620     albertel 7007:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 7008:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   7009: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   7010: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 7011: 	return $Apache::lonhomework::history{'resource.CODE'};
                   7012:     }
                   7013:     return undef;
                   7014: }
                   7015: 
1.31      www      7016: sub rndseed {
1.155     albertel 7017:     my ($symb,$courseid,$domain,$username)=@_;
1.790     albertel 7018:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.155     albertel 7019:     if (!$symb) {
1.366     albertel 7020: 	unless ($symb=$wsymb) { return time; }
                   7021:     }
                   7022:     if (!$courseid) { $courseid=$wcourseid; }
                   7023:     if (!$domain) { $domain=$wdomain; }
                   7024:     if (!$username) { $username=$wusername }
1.503     albertel 7025:     my $which=&get_rand_alg();
1.803     albertel 7026: 
1.491     albertel 7027:     if (defined(&getCODE())) {
1.675     albertel 7028: 	if ($which eq '64bit5') {
                   7029: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   7030: 	} elsif ($which eq '64bit4') {
1.575     albertel 7031: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   7032: 	} else {
                   7033: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   7034: 	}
1.675     albertel 7035:     } elsif ($which eq '64bit5') {
                   7036: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 7037:     } elsif ($which eq '64bit4') {
                   7038: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 7039:     } elsif ($which eq '64bit3') {
                   7040: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 7041:     } elsif ($which eq '64bit2') {
                   7042: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 7043:     } elsif ($which eq '64bit') {
                   7044: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   7045:     }
                   7046:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   7047: }
                   7048: 
                   7049: sub rndseed_32bit {
                   7050:     my ($symb,$courseid,$domain,$username)=@_;
                   7051:     {
                   7052: 	use integer;
                   7053: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   7054: 	my $symbseed=numval($symb) << 22;
                   7055: 	my $namechck=unpack("%32C*",$username) << 17;
                   7056: 	my $nameseed=numval($username) << 12;
                   7057: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   7058: 	my $courseseed=unpack("%32C*",$courseid);
                   7059: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 7060: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7061: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 7062: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 7063: 	return $num;
                   7064:     }
                   7065: }
                   7066: 
                   7067: sub rndseed_64bit {
                   7068:     my ($symb,$courseid,$domain,$username)=@_;
                   7069:     {
                   7070: 	use integer;
                   7071: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   7072: 	my $symbseed=numval($symb) << 10;
                   7073: 	my $namechck=unpack("%32S*",$username);
                   7074: 	
                   7075: 	my $nameseed=numval($username) << 21;
                   7076: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   7077: 	my $courseseed=unpack("%32S*",$courseid);
                   7078: 	
                   7079: 	my $num1=$symbchck+$symbseed+$namechck;
                   7080: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7081: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7082: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 7083: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 7084: 	return "$num1,$num2";
1.155     albertel 7085:     }
1.366     albertel 7086: }
                   7087: 
1.443     albertel 7088: sub rndseed_64bit2 {
                   7089:     my ($symb,$courseid,$domain,$username)=@_;
                   7090:     {
                   7091: 	use integer;
                   7092: 	# strings need to be an even # of cahracters long, it it is odd the
                   7093:         # last characters gets thrown away
                   7094: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7095: 	my $symbseed=numval($symb) << 10;
                   7096: 	my $namechck=unpack("%32S*",$username.' ');
                   7097: 	
                   7098: 	my $nameseed=numval($username) << 21;
1.501     albertel 7099: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7100: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7101: 	
                   7102: 	my $num1=$symbchck+$symbseed+$namechck;
                   7103: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7104: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7105: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 7106: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 7107: 	return "$num1,$num2";
                   7108:     }
                   7109: }
                   7110: 
                   7111: sub rndseed_64bit3 {
                   7112:     my ($symb,$courseid,$domain,$username)=@_;
                   7113:     {
                   7114: 	use integer;
                   7115: 	# strings need to be an even # of cahracters long, it it is odd the
                   7116:         # last characters gets thrown away
                   7117: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7118: 	my $symbseed=numval2($symb) << 10;
                   7119: 	my $namechck=unpack("%32S*",$username.' ');
                   7120: 	
                   7121: 	my $nameseed=numval2($username) << 21;
1.443     albertel 7122: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7123: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7124: 	
                   7125: 	my $num1=$symbchck+$symbseed+$namechck;
                   7126: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7127: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7128: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 7129: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   7130: 	
1.503     albertel 7131: 	return "$num1:$num2";
1.443     albertel 7132:     }
                   7133: }
                   7134: 
1.575     albertel 7135: sub rndseed_64bit4 {
                   7136:     my ($symb,$courseid,$domain,$username)=@_;
                   7137:     {
                   7138: 	use integer;
                   7139: 	# strings need to be an even # of cahracters long, it it is odd the
                   7140:         # last characters gets thrown away
                   7141: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7142: 	my $symbseed=numval3($symb) << 10;
                   7143: 	my $namechck=unpack("%32S*",$username.' ');
                   7144: 	
                   7145: 	my $nameseed=numval3($username) << 21;
                   7146: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7147: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7148: 	
                   7149: 	my $num1=$symbchck+$symbseed+$namechck;
                   7150: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7151: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7152: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 7153: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   7154: 	
                   7155: 	return "$num1:$num2";
                   7156:     }
                   7157: }
                   7158: 
1.675     albertel 7159: sub rndseed_64bit5 {
                   7160:     my ($symb,$courseid,$domain,$username)=@_;
                   7161:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   7162:     return "$num1:$num2";
                   7163: }
                   7164: 
1.366     albertel 7165: sub rndseed_CODE_64bit {
                   7166:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 7167:     {
1.366     albertel 7168: 	use integer;
1.443     albertel 7169: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 7170: 	my $symbseed=numval2($symb);
1.491     albertel 7171: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   7172: 	my $CODEseed=numval(&getCODE());
1.443     albertel 7173: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 7174: 	my $num1=$symbseed+$CODEchck;
                   7175: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 7176: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   7177: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 7178: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   7179: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 7180: 	return "$num1:$num2";
1.366     albertel 7181:     }
                   7182: }
                   7183: 
1.575     albertel 7184: sub rndseed_CODE_64bit4 {
                   7185:     my ($symb,$courseid,$domain,$username)=@_;
                   7186:     {
                   7187: 	use integer;
                   7188: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   7189: 	my $symbseed=numval3($symb);
                   7190: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   7191: 	my $CODEseed=numval3(&getCODE());
                   7192: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7193: 	my $num1=$symbseed+$CODEchck;
                   7194: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 7195: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   7196: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 7197: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   7198: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   7199: 	return "$num1:$num2";
                   7200:     }
                   7201: }
                   7202: 
1.675     albertel 7203: sub rndseed_CODE_64bit5 {
                   7204:     my ($symb,$courseid,$domain,$username)=@_;
                   7205:     my $code = &getCODE();
                   7206:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   7207:     return "$num1:$num2";
                   7208: }
                   7209: 
1.366     albertel 7210: sub setup_random_from_rndseed {
                   7211:     my ($rndseed)=@_;
1.503     albertel 7212:     if ($rndseed =~/([,:])/) {
                   7213: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 7214: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   7215:     } else {
                   7216: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 7217:     }
1.36      albertel 7218: }
                   7219: 
1.474     albertel 7220: sub latest_receipt_algorithm_id {
1.835     albertel 7221:     return 'receipt3';
1.474     albertel 7222: }
                   7223: 
1.480     www      7224: sub recunique {
                   7225:     my $fucourseid=shift;
                   7226:     my $unique;
1.835     albertel 7227:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   7228: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 7229: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      7230:     } else {
                   7231: 	$unique=$perlvar{'lonReceipt'};
                   7232:     }
                   7233:     return unpack("%32C*",$unique);
                   7234: }
                   7235: 
                   7236: sub recprefix {
                   7237:     my $fucourseid=shift;
                   7238:     my $prefix;
1.835     albertel 7239:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   7240: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 7241: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      7242:     } else {
                   7243: 	$prefix=$perlvar{'lonHostID'};
                   7244:     }
                   7245:     return unpack("%32C*",$prefix);
                   7246: }
                   7247: 
1.76      www      7248: sub ireceipt {
1.474     albertel 7249:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 7250: 
                   7251:     my $return =&recprefix($fucourseid).'-';
                   7252: 
                   7253:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   7254: 	$env{'request.state'} eq 'construct') {
                   7255: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   7256: 	return $return;
                   7257:     }
                   7258: 
1.76      www      7259:     my $cuname=unpack("%32C*",$funame);
                   7260:     my $cudom=unpack("%32C*",$fudom);
                   7261:     my $cucourseid=unpack("%32C*",$fucourseid);
                   7262:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      7263:     my $cunique=&recunique($fucourseid);
1.474     albertel 7264:     my $cpart=unpack("%32S*",$part);
1.835     albertel 7265:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   7266: 
1.790     albertel 7267: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 7268: 			       
                   7269: 	$return.= ($cunique%$cuname+
                   7270: 		   $cunique%$cudom+
                   7271: 		   $cusymb%$cuname+
                   7272: 		   $cusymb%$cudom+
                   7273: 		   $cucourseid%$cuname+
                   7274: 		   $cucourseid%$cudom+
                   7275: 		   $cpart%$cuname+
                   7276: 		   $cpart%$cudom);
                   7277:     } else {
                   7278: 	$return.= ($cunique%$cuname+
                   7279: 		   $cunique%$cudom+
                   7280: 		   $cusymb%$cuname+
                   7281: 		   $cusymb%$cudom+
                   7282: 		   $cucourseid%$cuname+
                   7283: 		   $cucourseid%$cudom);
                   7284:     }
                   7285:     return $return;
1.76      www      7286: }
                   7287: 
                   7288: sub receipt {
1.474     albertel 7289:     my ($part)=@_;
1.790     albertel 7290:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 7291:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      7292: }
1.260     ng       7293: 
1.790     albertel 7294: sub whichuser {
                   7295:     my ($passedsymb)=@_;
                   7296:     my ($symb,$courseid,$domain,$name,$publicuser);
                   7297:     if (defined($env{'form.grade_symb'})) {
                   7298: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   7299: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   7300: 	if (!$allowed &&
                   7301: 	    exists($env{'request.course.sec'}) &&
                   7302: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   7303: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   7304: 			      '/'.$env{'request.course.sec'});
                   7305: 	}
                   7306: 	if ($allowed) {
                   7307: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   7308: 	    $courseid=$tmp_courseid;
                   7309: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   7310: 	    ($name)=&get_env_multiple('form.grade_username');
                   7311: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   7312: 	}
                   7313:     }
                   7314:     if (!$passedsymb) {
                   7315: 	$symb=&symbread();
                   7316:     } else {
                   7317: 	$symb=$passedsymb;
                   7318:     }
                   7319:     $courseid=$env{'request.course.id'};
                   7320:     $domain=$env{'user.domain'};
                   7321:     $name=$env{'user.name'};
                   7322:     if ($name eq 'public' && $domain eq 'public') {
                   7323: 	if (!defined($env{'form.username'})) {
                   7324: 	    $env{'form.username'}.=time.rand(10000000);
                   7325: 	}
                   7326: 	$name.=$env{'form.username'};
                   7327:     }
                   7328:     return ($symb,$courseid,$domain,$name,$publicuser);
                   7329: 
                   7330: }
                   7331: 
1.36      albertel 7332: # ------------------------------------------------------------ Serves up a file
1.472     albertel 7333: # returns either the contents of the file or 
                   7334: # -1 if the file doesn't exist
1.481     raeburn  7335: #
                   7336: # if the target is a file that was uploaded via DOCS, 
                   7337: # a check will be made to see if a current copy exists on the local server,
                   7338: # if it does this will be served, otherwise a copy will be retrieved from
                   7339: # the home server for the course and stored in /home/httpd/html/userfiles on
                   7340: # the local server.   
1.472     albertel 7341: 
1.36      albertel 7342: sub getfile {
1.538     albertel 7343:     my ($file) = @_;
1.609     banghart 7344:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 7345:     &repcopy($file);
                   7346:     return &readfile($file);
                   7347: }
                   7348: 
                   7349: sub repcopy_userfile {
                   7350:     my ($file)=@_;
1.609     banghart 7351:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 7352:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 7353:     my ($cdom,$cnum,$filename) = 
1.811     albertel 7354: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 7355:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   7356:     if (-e "$file") {
1.828     www      7357: # we already have a local copy, check it out
1.538     albertel 7358: 	my @fileinfo = stat($file);
1.828     www      7359: 	my $rtncode;
                   7360: 	my $info;
1.538     albertel 7361: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 7362: 	if ($lwpresp ne 'ok') {
1.828     www      7363: # there is no such file anymore, even though we had a local copy
1.482     albertel 7364: 	    if ($rtncode eq '404') {
1.538     albertel 7365: 		unlink($file);
1.482     albertel 7366: 	    }
                   7367: 	    return -1;
                   7368: 	}
                   7369: 	if ($info < $fileinfo[9]) {
1.828     www      7370: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  7371: 	    return 'ok';
1.828     www      7372: 	} else {
                   7373: # the file is outdated, get rid of it
                   7374: 	    unlink($file);
1.482     albertel 7375: 	}
1.828     www      7376:     }
                   7377: # one way or the other, at this point, we don't have the file
                   7378: # construct the correct path for the file
                   7379:     my @parts = ($cdom,$cnum); 
                   7380:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   7381: 	push @parts, split(/\//,$1);
                   7382:     }
                   7383:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   7384:     foreach my $part (@parts) {
                   7385: 	$path .= '/'.$part;
                   7386: 	if (!-e $path) {
                   7387: 	    mkdir($path,0770);
1.482     albertel 7388: 	}
                   7389:     }
1.828     www      7390: # now the path exists for sure
                   7391: # get a user agent
                   7392:     my $ua=new LWP::UserAgent;
                   7393:     my $transferfile=$file.'.in.transfer';
                   7394: # FIXME: this should flock
                   7395:     if (-e $transferfile) { return 'ok'; }
                   7396:     my $request;
                   7397:     $uri=~s/^\///;
1.838     albertel 7398:     $request=new HTTP::Request('GET','http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri);
1.828     www      7399:     my $response=$ua->request($request,$transferfile);
                   7400: # did it work?
                   7401:     if ($response->is_error()) {
                   7402: 	unlink($transferfile);
                   7403: 	&logthis("Userfile repcopy failed for $uri");
                   7404: 	return -1;
                   7405:     }
                   7406: # worked, rename the transfer file
                   7407:     rename($transferfile,$file);
1.607     raeburn  7408:     return 'ok';
1.481     raeburn  7409: }
                   7410: 
1.517     albertel 7411: sub tokenwrapper {
                   7412:     my $uri=shift;
1.552     albertel 7413:     $uri=~s|^http\://([^/]+)||;
                   7414:     $uri=~s|^/||;
1.620     albertel 7415:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 7416:     my $token=$1;
1.552     albertel 7417:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   7418:     if ($udom && $uname && $file) {
                   7419: 	$file=~s|(\?\.*)*$||;
1.620     albertel 7420:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
1.838     albertel 7421:         return 'http://'.&hostname(&homeserver($uname,$udom)).'/'.$uri.
1.517     albertel 7422:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   7423:                                '&tokenissued='.$perlvar{'lonHostID'};
                   7424:     } else {
                   7425:         return '/adm/notfound.html';
                   7426:     }
                   7427: }
                   7428: 
1.828     www      7429: # call with reqtype HEAD: get last modification time
                   7430: # call with reqtype GET: get the file contents
                   7431: # Do not call this with reqtype GET for large files! It loads everything into memory
                   7432: #
1.481     raeburn  7433: sub getuploaded {
                   7434:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   7435:     $uri=~s/^\///;
1.838     albertel 7436:     $uri = 'http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri;
1.481     raeburn  7437:     my $ua=new LWP::UserAgent;
                   7438:     my $request=new HTTP::Request($reqtype,$uri);
                   7439:     my $response=$ua->request($request);
                   7440:     $$rtncode = $response->code;
1.482     albertel 7441:     if (! $response->is_success()) {
                   7442: 	return 'failed';
                   7443:     }      
                   7444:     if ($reqtype eq 'HEAD') {
1.486     www      7445: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 7446:     } elsif ($reqtype eq 'GET') {
                   7447: 	$$info = $response->content;
1.472     albertel 7448:     }
1.482     albertel 7449:     return 'ok';
1.36      albertel 7450: }
                   7451: 
1.481     raeburn  7452: sub readfile {
                   7453:     my $file = shift;
                   7454:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   7455:     my $fh;
                   7456:     open($fh,"<$file");
                   7457:     my $a='';
1.800     albertel 7458:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  7459:     return $a;
                   7460: }
                   7461: 
1.36      albertel 7462: sub filelocation {
1.590     banghart 7463:     my ($dir,$file) = @_;
                   7464:     my $location;
                   7465:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 7466: 
                   7467:     if ($file =~ m-^/adm/-) {
                   7468: 	$file=~s-^/adm/wrapper/-/-;
                   7469: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   7470:     }
1.590     banghart 7471:     if ($file=~m:^/~:) { # is a contruction space reference
                   7472:         $location = $file;
                   7473:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 7474:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 7475: 	# is a correct contruction space reference
                   7476:         $location = $file;
1.609     banghart 7477:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 7478:         my ($udom,$uname,$filename)=
1.811     albertel 7479:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 7480:         my $home=&homeserver($uname,$udom);
                   7481:         my $is_me=0;
                   7482:         my @ids=&current_machine_ids();
                   7483:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   7484:         if ($is_me) {
1.740     www      7485:   	    $location=&propath($udom,$uname).
1.590     banghart 7486:   	      '/userfiles/'.$filename;
                   7487:         } else {
                   7488:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   7489:   	      $udom.'/'.$uname.'/'.$filename;
                   7490:         }
                   7491:     } else {
                   7492:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   7493:         $file=~s:^/res/:/:;
                   7494:         if ( !( $file =~ m:^/:) ) {
                   7495:             $location = $dir. '/'.$file;
                   7496:         } else {
                   7497:             $location = '/home/httpd/html/res'.$file;
                   7498:         }
1.59      albertel 7499:     }
1.590     banghart 7500:     $location=~s://+:/:g; # remove duplicate /
                   7501:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
                   7502:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   7503:     return $location;
1.46      www      7504: }
1.36      albertel 7505: 
1.46      www      7506: sub hreflocation {
                   7507:     my ($dir,$file)=@_;
1.460     albertel 7508:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666     albertel 7509: 	$file=filelocation($dir,$file);
1.700     albertel 7510:     } elsif ($file=~m-^/adm/-) {
                   7511: 	$file=~s-^/adm/wrapper/-/-;
                   7512: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 7513:     }
                   7514:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   7515: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 7516:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   7517: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 7518:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 7519: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 7520: 	    -/uploaded/$1/$2/-x;
1.46      www      7521:     }
1.462     albertel 7522:     return $file;
1.465     albertel 7523: }
                   7524: 
                   7525: sub current_machine_domains {
1.853     albertel 7526:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   7527: }
                   7528: 
                   7529: sub machine_domains {
                   7530:     my ($hostname) = @_;
1.465     albertel 7531:     my @domains;
1.838     albertel 7532:     my %hostname = &all_hostnames();
1.465     albertel 7533:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  7534: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 7535: 	if ($hostname eq $name) {
1.844     albertel 7536: 	    push(@domains,&host_domain($id));
1.465     albertel 7537: 	}
                   7538:     }
                   7539:     return @domains;
                   7540: }
                   7541: 
                   7542: sub current_machine_ids {
1.853     albertel 7543:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   7544: }
                   7545: 
                   7546: sub machine_ids {
                   7547:     my ($hostname) = @_;
                   7548:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 7549:     my @ids;
1.838     albertel 7550:     my %hostname = &all_hostnames();
1.465     albertel 7551:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  7552: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 7553: 	if ($hostname eq $name) {
                   7554: 	    push(@ids,$id);
                   7555: 	}
                   7556:     }
                   7557:     return @ids;
1.31      www      7558: }
                   7559: 
1.824     raeburn  7560: sub additional_machine_domains {
                   7561:     my @domains;
                   7562:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   7563:     while( my $line = <$fh>) {
                   7564:         $line =~ s/\s//g;
                   7565:         push(@domains,$line);
                   7566:     }
                   7567:     return @domains;
                   7568: }
                   7569: 
                   7570: sub default_login_domain {
                   7571:     my $domain = $perlvar{'lonDefDomain'};
                   7572:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   7573:     foreach my $posdom (&current_machine_domains(),
                   7574:                         &additional_machine_domains()) {
                   7575:         if (lc($posdom) eq lc($testdomain)) {
                   7576:             $domain=$posdom;
                   7577:             last;
                   7578:         }
                   7579:     }
                   7580:     return $domain;
                   7581: }
                   7582: 
1.31      www      7583: # ------------------------------------------------------------- Declutters URLs
                   7584: 
                   7585: sub declutter {
                   7586:     my $thisfn=shift;
1.569     albertel 7587:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 7588:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      7589:     $thisfn=~s/^\///;
1.697     albertel 7590:     $thisfn=~s|^adm/wrapper/||;
                   7591:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      7592:     $thisfn=~s/^res\///;
1.235     www      7593:     $thisfn=~s/\?.+$//;
1.268     www      7594:     return $thisfn;
                   7595: }
                   7596: 
                   7597: # ------------------------------------------------------------- Clutter up URLs
                   7598: 
                   7599: sub clutter {
                   7600:     my $thisfn='/'.&declutter(shift);
1.609     banghart 7601:     unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) { 
1.270     www      7602:        $thisfn='/res'.$thisfn; 
                   7603:     }
1.694     albertel 7604:     if ($thisfn !~m|/adm|) {
1.695     albertel 7605: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 7606: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 7607: 	} else {
                   7608: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   7609: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 7610: 	    if ($embstyle eq 'ssi'
                   7611: 		|| ($embstyle eq 'hdn')
                   7612: 		|| ($embstyle eq 'rat')
                   7613: 		|| ($embstyle eq 'prv')
                   7614: 		|| ($embstyle eq 'ign')) {
                   7615: 		#do nothing with these
                   7616: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 7617: 		|| ($embstyle eq 'emb')
                   7618: 		|| ($embstyle eq 'wrp')) {
                   7619: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 7620: 	    } elsif ($embstyle eq 'unk'
                   7621: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 7622: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 7623: 	    } else {
1.718     www      7624: #		&logthis("Got a blank emb style");
1.695     albertel 7625: 	    }
1.694     albertel 7626: 	}
                   7627:     }
1.31      www      7628:     return $thisfn;
1.12      www      7629: }
                   7630: 
1.787     albertel 7631: sub clutter_with_no_wrapper {
                   7632:     my $uri = &clutter(shift);
                   7633:     if ($uri =~ m-^/adm/-) {
                   7634: 	$uri =~ s-^/adm/wrapper/-/-;
                   7635: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   7636:     }
                   7637:     return $uri;
                   7638: }
                   7639: 
1.557     albertel 7640: sub freeze_escape {
                   7641:     my ($value)=@_;
                   7642:     if (ref($value)) {
                   7643: 	$value=&nfreeze($value);
                   7644: 	return '__FROZEN__'.&escape($value);
                   7645:     }
                   7646:     return &escape($value);
                   7647: }
                   7648: 
1.11      www      7649: 
1.557     albertel 7650: sub thaw_unescape {
                   7651:     my ($value)=@_;
                   7652:     if ($value =~ /^__FROZEN__/) {
                   7653: 	substr($value,0,10,undef);
                   7654: 	$value=&unescape($value);
                   7655: 	return &thaw($value);
                   7656:     }
                   7657:     return &unescape($value);
                   7658: }
                   7659: 
1.436     albertel 7660: sub correct_line_ends {
                   7661:     my ($result)=@_;
                   7662:     $$result =~s/\r\n/\n/mg;
                   7663:     $$result =~s/\r/\n/mg;
1.415     albertel 7664: }
1.1       albertel 7665: # ================================================================ Main Program
                   7666: 
1.184     www      7667: sub goodbye {
1.204     albertel 7668:    &logthis("Starting Shut down");
1.443     albertel 7669: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 7670:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 7671: #converted
1.599     albertel 7672: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 7673:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   7674: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   7675: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 7676: #1.1 only
1.870     albertel 7677: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   7678: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   7679: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   7680: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   7681:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 7682:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   7683:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      7684:    &flushcourselogs();
                   7685:    &logthis("Shutting down");
                   7686: }
                   7687: 
1.852     albertel 7688: sub get_dns {
1.869     albertel 7689:     my ($url,$func,$ignore_cache) = @_;
                   7690:     if (!$ignore_cache) {
                   7691: 	my ($content,$cached)=
                   7692: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   7693: 	if ($cached) {
                   7694: 	    &$func($content);
                   7695: 	    return;
                   7696: 	}
                   7697:     }
                   7698: 
                   7699:     my %alldns;
1.852     albertel 7700:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   7701:     foreach my $dns (<$config>) {
                   7702: 	next if ($dns !~ /^\^(\S*)/x);
1.869     albertel 7703: 	$alldns{$1} = 1;
                   7704:     }
                   7705:     while (%alldns) {
                   7706: 	my ($dns) = keys(%alldns);
                   7707: 	delete($alldns{$dns});
1.852     albertel 7708: 	my $ua=new LWP::UserAgent;
                   7709: 	my $request=new HTTP::Request('GET',"http://$dns$url");
                   7710: 	my $response=$ua->request($request);
                   7711: 	next if ($response->is_error());
                   7712: 	my @content = split("\n",$response->content);
1.869     albertel 7713: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 7714: 	&$func(\@content);
1.869     albertel 7715: 	return;
1.852     albertel 7716:     }
                   7717:     close($config);
1.871     albertel 7718:     my $which = (split('/',$url))[3];
                   7719:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   7720:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 7721:     my @content = <$config>;
                   7722:     &$func(\@content);
                   7723:     return;
1.852     albertel 7724: }
1.327     albertel 7725: # ------------------------------------------------------------ Read domain file
                   7726: {
1.852     albertel 7727:     my $loaded;
1.846     albertel 7728:     my %domain;
                   7729: 
1.852     albertel 7730:     sub parse_domain_tab {
                   7731: 	my ($lines) = @_;
                   7732: 	foreach my $line (@$lines) {
                   7733: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      7734: 
1.846     albertel 7735: 	    chomp($line);
1.852     albertel 7736: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 7737: 	    my %this_domain;
                   7738: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   7739: 			       'lang_def', 'city', 'longi', 'lati',
                   7740: 			       'primary') {
                   7741: 		$this_domain{$field} = shift(@elements);
                   7742: 	    }
                   7743: 	    $domain{$name} = \%this_domain;
1.852     albertel 7744: 	}
                   7745:     }
1.864     albertel 7746: 
                   7747:     sub reset_domain_info {
                   7748: 	undef($loaded);
                   7749: 	undef(%domain);
                   7750:     }
                   7751: 
1.852     albertel 7752:     sub load_domain_tab {
1.869     albertel 7753: 	my ($ignore_cache) = @_;
                   7754: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 7755: 	my $fh;
                   7756: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   7757: 	    my @lines = <$fh>;
                   7758: 	    &parse_domain_tab(\@lines);
1.448     albertel 7759: 	}
1.852     albertel 7760: 	close($fh);
                   7761: 	$loaded = 1;
1.327     albertel 7762:     }
1.846     albertel 7763: 
                   7764:     sub domain {
1.852     albertel 7765: 	&load_domain_tab() if (!$loaded);
                   7766: 
1.846     albertel 7767: 	my ($name,$what) = @_;
                   7768: 	return if ( !exists($domain{$name}) );
                   7769: 
                   7770: 	if (!$what) {
                   7771: 	    return $domain{$name}{'description'};
                   7772: 	}
                   7773: 	return $domain{$name}{$what};
                   7774:     }
1.327     albertel 7775: }
                   7776: 
                   7777: 
1.1       albertel 7778: # ------------------------------------------------------------- Read hosts file
                   7779: {
1.838     albertel 7780:     my %hostname;
1.844     albertel 7781:     my %hostdom;
1.845     albertel 7782:     my %libserv;
1.852     albertel 7783:     my $loaded;
                   7784: 
                   7785:     sub parse_hosts_tab {
                   7786: 	my ($file) = @_;
                   7787: 	foreach my $configline (@$file) {
                   7788: 	    next if ($configline =~ /^(\#|\s*$ )/x);
                   7789: 	    next if ($configline =~ /^\^/);
                   7790: 	    chomp($configline);
                   7791: 	    my ($id,$domain,$role,$name)=split(/:/,$configline);
                   7792: 	    $name=~s/\s//g;
                   7793: 	    if ($id && $domain && $role && $name) {
                   7794: 		$hostname{$id}=$name;
                   7795: 		$hostdom{$id}=$domain;
                   7796: 		if ($role eq 'library') { $libserv{$id}=$name; }
                   7797: 	    }
                   7798: 	}
                   7799:     }
1.864     albertel 7800:     
                   7801:     sub reset_hosts_info {
                   7802: 	&reset_domain_info();
                   7803: 	&reset_hosts_ip_info();
                   7804: 	undef(%hostname);
                   7805: 	undef(%hostdom);
                   7806: 	undef(%libserv);
                   7807: 	undef($loaded);
                   7808:     }
1.1       albertel 7809: 
1.852     albertel 7810:     sub load_hosts_tab {
1.869     albertel 7811: 	my ($ignore_cache) = @_;
                   7812: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 7813: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   7814: 	my @config = <$config>;
                   7815: 	&parse_hosts_tab(\@config);
                   7816: 	close($config);
                   7817: 	$loaded=1;
1.1       albertel 7818:     }
1.852     albertel 7819: 
1.838     albertel 7820:     sub hostname {
1.852     albertel 7821: 	&load_hosts_tab() if (!$loaded);
                   7822: 
1.838     albertel 7823: 	my ($lonid) = @_;
                   7824: 	return $hostname{$lonid};
                   7825:     }
1.845     albertel 7826: 
1.838     albertel 7827:     sub all_hostnames {
1.852     albertel 7828: 	&load_hosts_tab() if (!$loaded);
                   7829: 
1.838     albertel 7830: 	return %hostname;
                   7831:     }
1.845     albertel 7832: 
                   7833:     sub is_library {
1.852     albertel 7834: 	&load_hosts_tab() if (!$loaded);
                   7835: 
1.845     albertel 7836: 	return exists($libserv{$_[0]});
                   7837:     }
                   7838: 
                   7839:     sub all_library {
1.852     albertel 7840: 	&load_hosts_tab() if (!$loaded);
                   7841: 
1.845     albertel 7842: 	return %libserv;
                   7843:     }
                   7844: 
1.841     albertel 7845:     sub get_servers {
1.852     albertel 7846: 	&load_hosts_tab() if (!$loaded);
                   7847: 
1.841     albertel 7848: 	my ($domain,$type) = @_;
                   7849: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   7850: 	                                          : %hostname;
                   7851: 	my %result;
1.842     albertel 7852: 	if (ref($domain) eq 'ARRAY') {
                   7853: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 7854: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 7855: 		    $result{$host} = $hostname;
                   7856: 		}
                   7857: 	    }
                   7858: 	} else {
                   7859: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   7860: 		if ($hostdom{$host} eq $domain) {
                   7861: 		    $result{$host} = $hostname;
                   7862: 		}
1.841     albertel 7863: 	    }
                   7864: 	}
                   7865: 	return %result;
                   7866:     }
1.845     albertel 7867: 
1.844     albertel 7868:     sub host_domain {
1.852     albertel 7869: 	&load_hosts_tab() if (!$loaded);
                   7870: 
1.844     albertel 7871: 	my ($lonid) = @_;
                   7872: 	return $hostdom{$lonid};
                   7873:     }
                   7874: 
1.841     albertel 7875:     sub all_domains {
1.852     albertel 7876: 	&load_hosts_tab() if (!$loaded);
                   7877: 
1.841     albertel 7878: 	my %seen;
                   7879: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   7880: 	return @uniq;
                   7881:     }
1.1       albertel 7882: }
                   7883: 
1.847     albertel 7884: { 
                   7885:     my %iphost;
1.856     albertel 7886:     my %name_to_ip;
                   7887:     my %lonid_to_ip;
1.869     albertel 7888: 
                   7889:     my %valid_ip;
                   7890:     sub valid_ip {
                   7891: 	my ($ip) = @_;
                   7892: 	if (exists($iphost{$ip}) || exists($valid_ip{$ip})) {
                   7893: 	    return 1;	
                   7894: 	}
                   7895: 	my $name = gethostbyip($ip);
                   7896: 	my $lonid = &hostname($name);
                   7897: 	if (defined($lonid)) {
                   7898: 	    $valid_ip{$ip} = $lonid;
                   7899: 	    return 1;
                   7900: 	}
                   7901: 	my %iphosts = &get_iphost();
                   7902: 	if (ref($iphost{$ip})) {
                   7903: 	    return 1;	
                   7904: 	}
                   7905:     }
                   7906: 
1.847     albertel 7907:     sub get_hosts_from_ip {
                   7908: 	my ($ip) = @_;
                   7909: 	my %iphosts = &get_iphost();
                   7910: 	if (ref($iphosts{$ip})) {
                   7911: 	    return @{$iphosts{$ip}};
                   7912: 	}
                   7913: 	return;
1.839     albertel 7914:     }
1.864     albertel 7915:     
                   7916:     sub reset_hosts_ip_info {
                   7917: 	undef(%iphost);
                   7918: 	undef(%name_to_ip);
                   7919: 	undef(%lonid_to_ip);
                   7920:     }
1.856     albertel 7921: 
                   7922:     sub get_host_ip {
                   7923: 	my ($lonid) = @_;
                   7924: 	if (exists($lonid_to_ip{$lonid})) {
                   7925: 	    return $lonid_to_ip{$lonid};
                   7926: 	}
                   7927: 	my $name=&hostname($lonid);
                   7928:    	my $ip = gethostbyname($name);
                   7929: 	return if (!$ip || length($ip) ne 4);
                   7930: 	$ip=inet_ntoa($ip);
                   7931: 	$name_to_ip{$name}   = $ip;
                   7932: 	$lonid_to_ip{$lonid} = $ip;
                   7933: 	return $ip;
                   7934:     }
1.847     albertel 7935:     
                   7936:     sub get_iphost {
1.869     albertel 7937: 	my ($ignore_cache) = @_;
                   7938: 	if (!$ignore_cache) {
                   7939: 	    if (%iphost) {
                   7940: 		return %iphost;
                   7941: 	    }
                   7942: 	    my ($ip_info,$cached)=
                   7943: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   7944: 	    if ($cached) {
                   7945: 		%iphost      = %{$ip_info->[0]};
                   7946: 		%name_to_ip  = %{$ip_info->[1]};
                   7947: 		%lonid_to_ip = %{$ip_info->[2]};
                   7948: 		return %iphost;
                   7949: 	    }
                   7950: 	}
1.847     albertel 7951: 	my %hostname = &all_hostnames();
                   7952: 	foreach my $id (keys(%hostname)) {
1.864     albertel 7953: 	    my $name=&hostname($id);
1.847     albertel 7954: 	    my $ip;
                   7955: 	    if (!exists($name_to_ip{$name})) {
                   7956: 		$ip = gethostbyname($name);
                   7957: 		if (!$ip || length($ip) ne 4) {
                   7958: 		    &logthis("Skipping host $id name $name no IP found");
                   7959: 		    next;
                   7960: 		}
                   7961: 		$ip=inet_ntoa($ip);
                   7962: 		$name_to_ip{$name} = $ip;
                   7963: 	    } else {
                   7964: 		$ip = $name_to_ip{$name};
1.653     albertel 7965: 	    }
1.856     albertel 7966: 	    $lonid_to_ip{$id} = $ip;
1.847     albertel 7967: 	    push(@{$iphost{$ip}},$id);
1.598     albertel 7968: 	}
1.869     albertel 7969: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   7970: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   7971: 				      24*60*60);
                   7972: 
1.847     albertel 7973: 	return %iphost;
1.598     albertel 7974:     }
                   7975: }
                   7976: 
1.862     albertel 7977: BEGIN {
                   7978: 
                   7979: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   7980:     unless ($readit) {
                   7981: {
                   7982:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   7983:     %perlvar = (%perlvar,%{$configvars});
                   7984: }
                   7985: 
                   7986: 
1.1       albertel 7987: # ------------------------------------------------------ Read spare server file
                   7988: {
1.448     albertel 7989:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 7990: 
                   7991:     while (my $configline=<$config>) {
                   7992:        chomp($configline);
1.284     matthew  7993:        if ($configline) {
1.784     albertel 7994: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 7995: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 7996: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 7997:        }
                   7998:     }
1.448     albertel 7999:     close($config);
1.1       albertel 8000: }
1.11      www      8001: # ------------------------------------------------------------ Read permissions
                   8002: {
1.448     albertel 8003:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      8004: 
                   8005:     while (my $configline=<$config>) {
1.448     albertel 8006: 	chomp($configline);
                   8007: 	if ($configline) {
                   8008: 	    my ($role,$perm)=split(/ /,$configline);
                   8009: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   8010: 	}
1.11      www      8011:     }
1.448     albertel 8012:     close($config);
1.11      www      8013: }
                   8014: 
                   8015: # -------------------------------------------- Read plain texts for permissions
                   8016: {
1.448     albertel 8017:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      8018: 
                   8019:     while (my $configline=<$config>) {
1.448     albertel 8020: 	chomp($configline);
                   8021: 	if ($configline) {
1.742     raeburn  8022: 	    my ($short,@plain)=split(/:/,$configline);
                   8023:             %{$prp{$short}} = ();
                   8024: 	    if (@plain > 0) {
                   8025:                 $prp{$short}{'std'} = $plain[0];
                   8026:                 for (my $i=1; $i<@plain; $i++) {
                   8027:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   8028:                 }
                   8029:             }
1.448     albertel 8030: 	}
1.135     www      8031:     }
1.448     albertel 8032:     close($config);
1.135     www      8033: }
                   8034: 
                   8035: # ---------------------------------------------------------- Read package table
                   8036: {
1.448     albertel 8037:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      8038: 
                   8039:     while (my $configline=<$config>) {
1.483     albertel 8040: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 8041: 	chomp($configline);
                   8042: 	my ($short,$plain)=split(/:/,$configline);
                   8043: 	my ($pack,$name)=split(/\&/,$short);
                   8044: 	if ($plain ne '') {
                   8045: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   8046: 	    $packagetab{$short}=$plain; 
                   8047: 	}
1.11      www      8048:     }
1.448     albertel 8049:     close($config);
1.329     matthew  8050: }
                   8051: 
                   8052: # ------------- set up temporary directory
                   8053: {
                   8054:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   8055: 
1.11      www      8056: }
                   8057: 
1.794     albertel 8058: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   8059: 				'compress_threshold'=> 20_000,
                   8060:  			        });
1.185     www      8061: 
1.281     www      8062: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      8063: $dumpcount=0;
1.22      www      8064: 
1.163     harris41 8065: &logtouch();
1.672     albertel 8066: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      8067: $readit=1;
1.564     albertel 8068:     {
                   8069: 	use integer;
                   8070: 	my $test=(2**32)+1;
1.568     albertel 8071: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 8072: 	&logthis(" Detected 64bit platform ($_64bit)");
                   8073:     }
1.195     www      8074: }
1.1       albertel 8075: }
1.179     www      8076: 
1.1       albertel 8077: 1;
1.191     harris41 8078: __END__
                   8079: 
1.243     albertel 8080: =pod
                   8081: 
1.191     harris41 8082: =head1 NAME
                   8083: 
1.243     albertel 8084: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 8085: 
                   8086: =head1 SYNOPSIS
                   8087: 
1.243     albertel 8088: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 8089: 
                   8090:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   8091: 
1.243     albertel 8092: Common parameters:
                   8093: 
                   8094: =over 4
                   8095: 
                   8096: =item *
                   8097: 
                   8098: $uname : an internal username (if $cname expecting a course Id specifically)
                   8099: 
                   8100: =item *
                   8101: 
                   8102: $udom : a domain (if $cdom expecting a course's domain specifically)
                   8103: 
                   8104: =item *
                   8105: 
                   8106: $symb : a resource instance identifier
                   8107: 
                   8108: =item *
                   8109: 
                   8110: $namespace : the name of a .db file that contains the data needed or
                   8111: being set.
                   8112: 
                   8113: =back
                   8114: 
1.394     bowersj2 8115: =head1 OVERVIEW
1.191     harris41 8116: 
1.394     bowersj2 8117: lonnet provides subroutines which interact with the
                   8118: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   8119: about classes, users, and resources.
1.243     albertel 8120: 
                   8121: For many of these objects you can also use this to store data about
                   8122: them or modify them in various ways.
1.191     harris41 8123: 
1.394     bowersj2 8124: =head2 Symbs
1.191     harris41 8125: 
1.394     bowersj2 8126: To identify a specific instance of a resource, LON-CAPA uses symbols
                   8127: or "symbs"X<symb>. These identifiers are built from the URL of the
                   8128: map, the resource number of the resource in the map, and the URL of
                   8129: the resource itself. The latter is somewhat redundant, but might help
                   8130: if maps change.
                   8131: 
                   8132: An example is
                   8133: 
                   8134:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   8135: 
                   8136: The respective map entry is
                   8137: 
                   8138:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   8139:   title="Problem 2">
                   8140:  </resource>
                   8141: 
                   8142: Symbs are used by the random number generator, as well as to store and
                   8143: restore data specific to a certain instance of for example a problem.
                   8144: 
                   8145: =head2 Storing And Retrieving Data
                   8146: 
                   8147: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   8148: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   8149: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   8150: is is the non-critical message twin of cstore. These functions are for
                   8151: handlers to store a perl hash to a user's permanent data space in an
                   8152: easy manner, and to retrieve it again on another call. It is expected
                   8153: that a handler would use this once at the beginning to retrieve data,
                   8154: and then again once at the end to send only the new data back.
                   8155: 
                   8156: The data is stored in the user's data directory on the user's
                   8157: homeserver under the ID of the course.
                   8158: 
                   8159: The hash that is returned by restore will have all of the previous
                   8160: value for all of the elements of the hash.
                   8161: 
                   8162: Example:
                   8163: 
                   8164:  #creating a hash
                   8165:  my %hash;
                   8166:  $hash{'foo'}='bar';
                   8167: 
                   8168:  #storing it
                   8169:  &Apache::lonnet::cstore(\%hash);
                   8170: 
                   8171:  #changing a value
                   8172:  $hash{'foo'}='notbar';
                   8173: 
                   8174:  #adding a new value
                   8175:  $hash{'bar'}='foo';
                   8176:  &Apache::lonnet::cstore(\%hash);
                   8177: 
                   8178:  #retrieving the hash
                   8179:  my %history=&Apache::lonnet::restore();
                   8180: 
                   8181:  #print the hash
                   8182:  foreach my $key (sort(keys(%history))) {
                   8183:    print("\%history{$key} = $history{$key}");
                   8184:  }
                   8185: 
                   8186: Will print out:
1.191     harris41 8187: 
1.394     bowersj2 8188:  %history{1:foo} = bar
                   8189:  %history{1:keys} = foo:timestamp
                   8190:  %history{1:timestamp} = 990455579
                   8191:  %history{2:bar} = foo
                   8192:  %history{2:foo} = notbar
                   8193:  %history{2:keys} = foo:bar:timestamp
                   8194:  %history{2:timestamp} = 990455580
                   8195:  %history{bar} = foo
                   8196:  %history{foo} = notbar
                   8197:  %history{timestamp} = 990455580
                   8198:  %history{version} = 2
                   8199: 
                   8200: Note that the special hash entries C<keys>, C<version> and
                   8201: C<timestamp> were added to the hash. C<version> will be equal to the
                   8202: total number of versions of the data that have been stored. The
                   8203: C<timestamp> attribute will be the UNIX time the hash was
                   8204: stored. C<keys> is available in every historical section to list which
                   8205: keys were added or changed at a specific historical revision of a
                   8206: hash.
                   8207: 
                   8208: B<Warning>: do not store the hash that restore returns directly. This
                   8209: will cause a mess since it will restore the historical keys as if the
                   8210: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 8211: 
1.394     bowersj2 8212: Calling convention:
1.191     harris41 8213: 
1.394     bowersj2 8214:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   8215:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 8216: 
1.394     bowersj2 8217: For more detailed information, see lonnet specific documentation.
1.191     harris41 8218: 
1.394     bowersj2 8219: =head1 RETURN MESSAGES
1.191     harris41 8220: 
1.394     bowersj2 8221: =over 4
1.191     harris41 8222: 
1.394     bowersj2 8223: =item * B<con_lost>: unable to contact remote host
1.191     harris41 8224: 
1.394     bowersj2 8225: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   8226: when the connection is brought back up
1.191     harris41 8227: 
1.394     bowersj2 8228: =item * B<con_failed>: unable to contact remote host and unable to save message
                   8229: for later delivery
1.191     harris41 8230: 
1.394     bowersj2 8231: =item * B<error:>: an error a occured, a description of the error follows the :
1.191     harris41 8232: 
1.394     bowersj2 8233: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 8234: that was requested
1.191     harris41 8235: 
1.243     albertel 8236: =back
1.191     harris41 8237: 
1.243     albertel 8238: =head1 PUBLIC SUBROUTINES
1.191     harris41 8239: 
1.243     albertel 8240: =head2 Session Environment Functions
1.191     harris41 8241: 
1.243     albertel 8242: =over 4
1.191     harris41 8243: 
1.394     bowersj2 8244: =item * 
                   8245: X<appenv()>
                   8246: B<appenv(%hash)>: the value of %hash is written to
                   8247: the user envirnoment file, and will be restored for each access this
1.620     albertel 8248: user makes during this session, also modifies the %env for the current
1.394     bowersj2 8249: process
1.191     harris41 8250: 
                   8251: =item *
1.394     bowersj2 8252: X<delenv()>
                   8253: B<delenv($regexp)>: removes all items from the session
                   8254: environment file that matches the regular expression in $regexp. The
1.620     albertel 8255: values are also delted from the current processes %env.
1.191     harris41 8256: 
1.795     albertel 8257: =item * get_env_multiple($name) 
                   8258: 
                   8259: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   8260: values may be defined and end up as an array ref.
                   8261: 
                   8262: returns an array of values
                   8263: 
1.243     albertel 8264: =back
                   8265: 
                   8266: =head2 User Information
1.191     harris41 8267: 
1.243     albertel 8268: =over 4
1.191     harris41 8269: 
                   8270: =item *
1.394     bowersj2 8271: X<queryauthenticate()>
                   8272: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 8273: authentication scheme
                   8274: 
                   8275: =item *
1.394     bowersj2 8276: X<authenticate()>
                   8277: B<authenticate($uname,$upass,$udom)>: try to
                   8278: authenticate user from domain's lib servers (first use the current
                   8279: one). C<$upass> should be the users password.
1.191     harris41 8280: 
                   8281: =item *
1.394     bowersj2 8282: X<homeserver()>
                   8283: B<homeserver($uname,$udom)>: find the server which has
                   8284: the user's directory and files (there must be only one), this caches
                   8285: the answer, and also caches if there is a borken connection.
1.191     harris41 8286: 
                   8287: =item *
1.394     bowersj2 8288: X<idget()>
                   8289: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   8290: (IDs are a unique resource in a domain, there must be only 1 ID per
                   8291: username, and only 1 username per ID in a specific domain) (returns
                   8292: hash: id=>name,id=>name)
1.191     harris41 8293: 
                   8294: =item *
1.394     bowersj2 8295: X<idrget()>
                   8296: B<idrget($udom,@unames)>: find the IDs behind a list of
                   8297: usernames (returns hash: name=>id,name=>id)
1.191     harris41 8298: 
                   8299: =item *
1.394     bowersj2 8300: X<idput()>
                   8301: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 8302: 
                   8303: =item *
1.394     bowersj2 8304: X<rolesinit()>
                   8305: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 8306: 
                   8307: =item *
1.551     albertel 8308: X<getsection()>
                   8309: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 8310: course $cname, return section name/number or '' for "not in course"
                   8311: and '-1' for "no section"
                   8312: 
                   8313: =item *
1.394     bowersj2 8314: X<userenvironment()>
                   8315: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 8316: passed in @what from the requested user's environment, returns a hash
                   8317: 
1.858     raeburn  8318: =item * 
                   8319: X<userlog_query()>
1.859     albertel 8320: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   8321: activity.log file. %filters defines filters applied when parsing the
                   8322: log file. These can be start or end timestamps, or the type of action
                   8323: - log to look for Login or Logout events, check for Checkin or
                   8324: Checkout, role for role selection. The response is in the form
                   8325: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   8326: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  8327: 
1.243     albertel 8328: =back
                   8329: 
                   8330: =head2 User Roles
                   8331: 
                   8332: =over 4
                   8333: 
                   8334: =item *
                   8335: 
1.810     raeburn  8336: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 8337:  F: full access
                   8338:  U,I,K: authentication modes (cxx only)
                   8339:  '': forbidden
                   8340:  1: user needs to choose course
                   8341:  2: browse allowed
1.766     albertel 8342:  A: passphrase authentication needed
1.243     albertel 8343: 
                   8344: =item *
                   8345: 
                   8346: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   8347: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   8348: and course level
                   8349: 
                   8350: =item *
                   8351: 
                   8352: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   8353: explanation of a user role term
                   8354: 
1.832     raeburn  8355: =item *
                   8356: 
1.858     raeburn  8357: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms) :
                   8358: All arguments are optional. Returns a hash of a roles, either for
                   8359: co-author/assistant author roles for a user's Construction Space
                   8360: (default), or if $context is 'user', roles for the user himself,
                   8361: In the hash, keys are set to colon-sparated $uname,$udom,and $role,
                   8362: and value is set to colon-separated start and end times for the role.
                   8363: If no username and domain are specified, will default to current
                   8364: user/domain. Types, roles, and roledoms are references to arrays,
                   8365: of role statuses (active, future or previous), roles 
                   8366: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   8367: to restrict the list of roles reported. If no array ref is 
                   8368: provided for types, will default to return only active roles.
1.834     albertel 8369: 
1.243     albertel 8370: =back
                   8371: 
                   8372: =head2 User Modification
                   8373: 
                   8374: =over 4
                   8375: 
                   8376: =item *
                   8377: 
                   8378: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
                   8379: user for the level given by URL.  Optional start and end dates (leave empty
                   8380: string or zero for "no date")
1.191     harris41 8381: 
                   8382: =item *
                   8383: 
1.243     albertel 8384: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   8385: change a users, password, possible return values are: ok,
                   8386: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   8387: refused
1.191     harris41 8388: 
                   8389: =item *
                   8390: 
1.243     albertel 8391: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 8392: 
                   8393: =item *
                   8394: 
1.243     albertel 8395: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
                   8396: modify user
1.191     harris41 8397: 
                   8398: =item *
                   8399: 
1.286     matthew  8400: modifystudent
                   8401: 
                   8402: modify a students enrollment and identification information.
                   8403: The course id is resolved based on the current users environment.  
                   8404: This means the envoking user must be a course coordinator or otherwise
                   8405: associated with a course.
                   8406: 
1.297     matthew  8407: This call is essentially a wrapper for lonnet::modifyuser and
                   8408: lonnet::modify_student_enrollment
1.286     matthew  8409: 
                   8410: Inputs: 
                   8411: 
                   8412: =over 4
                   8413: 
                   8414: =item B<$udom> Students loncapa domain
                   8415: 
                   8416: =item B<$uname> Students loncapa login name
                   8417: 
                   8418: =item B<$uid> Students id/student number
                   8419: 
                   8420: =item B<$umode> Students authentication mode
                   8421: 
                   8422: =item B<$upass> Students password
                   8423: 
                   8424: =item B<$first> Students first name
                   8425: 
                   8426: =item B<$middle> Students middle name
                   8427: 
                   8428: =item B<$last> Students last name
                   8429: 
                   8430: =item B<$gene> Students generation
                   8431: 
                   8432: =item B<$usec> Students section in course
                   8433: 
                   8434: =item B<$end> Unix time of the roles expiration
                   8435: 
                   8436: =item B<$start> Unix time of the roles start date
                   8437: 
                   8438: =item B<$forceid> If defined, allow $uid to be changed
                   8439: 
                   8440: =item B<$desiredhome> server to use as home server for student
                   8441: 
                   8442: =back
1.297     matthew  8443: 
                   8444: =item *
                   8445: 
                   8446: modify_student_enrollment
                   8447: 
                   8448: Change a students enrollment status in a class.  The environment variable
                   8449: 'role.request.course' must be defined for this function to proceed.
                   8450: 
                   8451: Inputs:
                   8452: 
                   8453: =over 4
                   8454: 
                   8455: =item $udom, students domain
                   8456: 
                   8457: =item $uname, students name
                   8458: 
                   8459: =item $uid, students user id
                   8460: 
                   8461: =item $first, students first name
                   8462: 
                   8463: =item $middle
                   8464: 
                   8465: =item $last
                   8466: 
                   8467: =item $gene
                   8468: 
                   8469: =item $usec
                   8470: 
                   8471: =item $end
                   8472: 
                   8473: =item $start
                   8474: 
                   8475: =back
                   8476: 
1.191     harris41 8477: 
                   8478: =item *
                   8479: 
1.243     albertel 8480: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   8481: custom role; give a custom role to a user for the level given by URL.  Specify
                   8482: name and domain of role author, and role name
1.191     harris41 8483: 
                   8484: =item *
                   8485: 
1.243     albertel 8486: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 8487: 
                   8488: =item *
                   8489: 
1.243     albertel 8490: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   8491: 
                   8492: =back
                   8493: 
                   8494: =head2 Course Infomation
                   8495: 
                   8496: =over 4
1.191     harris41 8497: 
                   8498: =item *
                   8499: 
1.631     albertel 8500: coursedescription($courseid) : returns a hash of information about the
                   8501: specified course id, including all environment settings for the
                   8502: course, the description of the course will be in the hash under the
                   8503: key 'description'
1.191     harris41 8504: 
                   8505: =item *
                   8506: 
1.624     albertel 8507: resdata($name,$domain,$type,@which) : request for current parameter
                   8508: setting for a specific $type, where $type is either 'course' or 'user',
                   8509: @what should be a list of parameters to ask about. This routine caches
                   8510: answers for 5 minutes.
1.243     albertel 8511: 
                   8512: =back
                   8513: 
                   8514: =head2 Course Modification
                   8515: 
                   8516: =over 4
1.191     harris41 8517: 
                   8518: =item *
                   8519: 
1.243     albertel 8520: writecoursepref($courseid,%prefs) : write preferences (environment
                   8521: database) for a course
1.191     harris41 8522: 
                   8523: =item *
                   8524: 
1.243     albertel 8525: createcourse($udom,$description,$url) : make/modify course
                   8526: 
                   8527: =back
                   8528: 
                   8529: =head2 Resource Subroutines
                   8530: 
                   8531: =over 4
1.191     harris41 8532: 
                   8533: =item *
                   8534: 
1.243     albertel 8535: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 8536: 
                   8537: =item *
                   8538: 
1.243     albertel 8539: repcopy($filename) : subscribes to the requested file, and attempts to
                   8540: replicate from the owning library server, Might return
1.607     raeburn  8541: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   8542: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 8543: resource. Expects the local filesystem pathname
                   8544: (/home/httpd/html/res/....)
                   8545: 
                   8546: =back
                   8547: 
                   8548: =head2 Resource Information
                   8549: 
                   8550: =over 4
1.191     harris41 8551: 
                   8552: =item *
                   8553: 
1.243     albertel 8554: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   8555: a vairety of different possible values, $varname should be a request
                   8556: string, and the other parameters can be used to specify who and what
                   8557: one is asking about.
                   8558: 
                   8559: Possible values for $varname are environment.lastname (or other item
                   8560: from the envirnment hash), user.name (or someother aspect about the
                   8561: user), resource.0.maxtries (or some other part and parameter of a
                   8562: resource)
1.204     albertel 8563: 
                   8564: =item *
                   8565: 
1.243     albertel 8566: directcondval($number) : get current value of a condition; reads from a state
                   8567: string
1.204     albertel 8568: 
                   8569: =item *
                   8570: 
1.243     albertel 8571: condval($condidx) : value of condition index based on state
1.204     albertel 8572: 
                   8573: =item *
                   8574: 
1.243     albertel 8575: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   8576: resource's metadata, $what should be either a specific key, or either
                   8577: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   8578: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   8579: 
                   8580: this function automatically caches all requests
1.191     harris41 8581: 
                   8582: =item *
                   8583: 
1.243     albertel 8584: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   8585: network of library servers; returns file handle of where SQL and regex results
                   8586: will be stored for query
1.191     harris41 8587: 
                   8588: =item *
                   8589: 
1.243     albertel 8590: symbread($filename) : return symbolic list entry (filename argument optional);
                   8591: returns the data handle
1.191     harris41 8592: 
                   8593: =item *
                   8594: 
1.243     albertel 8595: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 8596: a possible symb for the URL in $thisfn, and if is an encryypted
                   8597: resource that the user accessed using /enc/ returns a 1 on success, 0
                   8598: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 8599: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 8600: 
1.191     harris41 8601: 
                   8602: =item *
                   8603: 
1.243     albertel 8604: symbclean($symb) : removes versions numbers from a symb, returns the
                   8605: cleaned symb
1.191     harris41 8606: 
                   8607: =item *
                   8608: 
1.243     albertel 8609: is_on_map($uri) : checks if the $uri is somewhere on the current
                   8610: course map, user must be in a course for it to work.
1.191     harris41 8611: 
                   8612: =item *
                   8613: 
1.243     albertel 8614: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 8615: 
                   8616: =item *
                   8617: 
1.243     albertel 8618: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   8619: a random seed, all arguments are optional, if they aren't sent it uses the
                   8620: environment to derive them. Note: if symb isn't sent and it can't get one
                   8621: from &symbread it will use the current time as its return value
1.191     harris41 8622: 
                   8623: =item *
                   8624: 
1.243     albertel 8625: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   8626: unfakeable, receipt
1.191     harris41 8627: 
                   8628: =item *
                   8629: 
1.620     albertel 8630: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 8631: 
                   8632: =item *
                   8633: 
1.243     albertel 8634: countacc($url) : count the number of accesses to a given URL
1.191     harris41 8635: 
                   8636: =item *
                   8637: 
1.243     albertel 8638: 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 8639: 
                   8640: =item *
                   8641: 
1.243     albertel 8642: 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 8643: 
                   8644: =item *
                   8645: 
1.243     albertel 8646: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 8647: 
                   8648: =item *
                   8649: 
1.243     albertel 8650: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   8651: forcing spreadsheet to reevaluate the resource scores next time.
                   8652: 
                   8653: =back
                   8654: 
                   8655: =head2 Storing/Retreiving Data
                   8656: 
                   8657: =over 4
1.191     harris41 8658: 
                   8659: =item *
                   8660: 
1.243     albertel 8661: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   8662: for this url; hashref needs to be given and should be a \%hashname; the
                   8663: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 8664: be derived from the env
1.191     harris41 8665: 
                   8666: =item *
                   8667: 
1.243     albertel 8668: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   8669: uses critical subroutine
1.191     harris41 8670: 
                   8671: =item *
                   8672: 
1.243     albertel 8673: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   8674: all args are optional
1.191     harris41 8675: 
                   8676: =item *
                   8677: 
1.717     albertel 8678: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   8679: dumps the complete (or key matching regexp) namespace into a hash
                   8680: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   8681: normally &store()ed into
                   8682: 
                   8683: $range should be either an integer '100' (give me the first 100
                   8684:                                            matching records)
                   8685:               or be  two integers sperated by a - with no spaces
                   8686:                  '30-50' (give me the 30th through the 50th matching
                   8687:                           records)
                   8688: 
                   8689: 
                   8690: =item *
                   8691: 
                   8692: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   8693: replaces a &store() version of data with a replacement set of data
                   8694: for a particular resource in a namespace passed in the $storehash hash 
                   8695: reference
                   8696: 
                   8697: =item *
                   8698: 
1.243     albertel 8699: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   8700: works very similar to store/cstore, but all data is stored in a
                   8701: temporary location and can be reset using tmpreset, $storehash should
                   8702: be a hash reference, returns nothing on success
1.191     harris41 8703: 
                   8704: =item *
                   8705: 
1.243     albertel 8706: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   8707: similar to restore, but all data is stored in a temporary location and
                   8708: can be reset using tmpreset. Returns a hash of values on success,
                   8709: error string otherwise.
1.191     harris41 8710: 
                   8711: =item *
                   8712: 
1.243     albertel 8713: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   8714: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 8715: 
                   8716: =item *
                   8717: 
1.243     albertel 8718: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   8719: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 8720: 
                   8721: =item *
                   8722: 
1.243     albertel 8723: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   8724: namesp ($udom and $uname are optional)
1.191     harris41 8725: 
                   8726: =item *
                   8727: 
1.702     albertel 8728: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 8729: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 8730: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  8731: 
1.702     albertel 8732: $range should be either an integer '100' (give me the first 100
                   8733:                                            matching records)
                   8734:               or be  two integers sperated by a - with no spaces
                   8735:                  '30-50' (give me the 30th through the 50th matching
                   8736:                           records)
1.449     matthew  8737: =item *
                   8738: 
                   8739: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   8740: $store can be a scalar, an array reference, or if the amount to be 
                   8741: incremented is > 1, a hash reference.
                   8742: 
                   8743: ($udom and $uname are optional)
1.191     harris41 8744: 
                   8745: =item *
                   8746: 
1.243     albertel 8747: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   8748: ($udom and $uname are optional)
1.191     harris41 8749: 
                   8750: =item *
                   8751: 
1.243     albertel 8752: cput($namespace,$storehash,$udom,$uname) : critical put
                   8753: ($udom and $uname are optional)
1.191     harris41 8754: 
                   8755: =item *
                   8756: 
1.748     albertel 8757: newput($namespace,$storehash,$udom,$uname) :
                   8758: 
                   8759: Attempts to store the items in the $storehash, but only if they don't
                   8760: currently exist, if this succeeds you can be certain that you have 
                   8761: successfully created a new key value pair in the $namespace db.
                   8762: 
                   8763: 
                   8764: Args:
                   8765:  $namespace: name of database to store values to
                   8766:  $storehash: hashref to store to the db
                   8767:  $udom: (optional) domain of user containing the db
                   8768:  $uname: (optional) name of user caontaining the db
                   8769: 
                   8770: Returns:
                   8771:  'ok' -> succeeded in storing all keys of $storehash
                   8772:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   8773:                         least <key> already existed in the db (other
                   8774:                         requested keys may also already exist)
                   8775:  'error: <msg>' -> unable to tie the DB or other erorr occured
                   8776:  'con_lost' -> unable to contact request server
                   8777:  'refused' -> action was not allowed by remote machine
                   8778: 
                   8779: 
                   8780: =item *
                   8781: 
1.243     albertel 8782: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   8783: reference filled in from namesp (encrypts the return communication)
                   8784: ($udom and $uname are optional)
1.191     harris41 8785: 
                   8786: =item *
                   8787: 
1.243     albertel 8788: log($udom,$name,$home,$message) : write to permanent log for user; use
                   8789: critical subroutine
                   8790: 
1.806     raeburn  8791: =item *
                   8792: 
1.860     raeburn  8793: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   8794: array reference filled in from namespace found in domain level on either
                   8795: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  8796: 
                   8797: =item *
                   8798: 
1.860     raeburn  8799: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   8800: domain level either on specified domain server ($uhome) or primary domain 
                   8801: server ($udom and $uhome are optional)
1.806     raeburn  8802: 
1.243     albertel 8803: =back
                   8804: 
                   8805: =head2 Network Status Functions
                   8806: 
                   8807: =over 4
1.191     harris41 8808: 
                   8809: =item *
                   8810: 
                   8811: dirlist($uri) : return directory list based on URI
                   8812: 
                   8813: =item *
                   8814: 
1.243     albertel 8815: spareserver() : find server with least workload from spare.tab
                   8816: 
                   8817: =back
                   8818: 
                   8819: =head2 Apache Request
                   8820: 
                   8821: =over 4
1.191     harris41 8822: 
                   8823: =item *
                   8824: 
1.243     albertel 8825: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   8826: localhost, posts hash
                   8827: 
                   8828: =back
                   8829: 
                   8830: =head2 Data to String to Data
                   8831: 
                   8832: =over 4
1.191     harris41 8833: 
                   8834: =item *
                   8835: 
1.243     albertel 8836: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   8837: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 8838: 
                   8839: =item *
                   8840: 
1.243     albertel 8841: hashref2str($hashref) : convert a hashref into a string complete with
                   8842: escaping and '=' and '&' separators, supports elements that are
                   8843: arrayrefs and hashrefs
1.191     harris41 8844: 
                   8845: =item *
                   8846: 
1.243     albertel 8847: arrayref2str($arrayref) : convert an arrayref into a string complete
                   8848: with escaping and '&' separators, supports elements that are arrayrefs
                   8849: and hashrefs
1.191     harris41 8850: 
                   8851: =item *
                   8852: 
1.243     albertel 8853: str2hash($string) : convert string to hash using unescaping and
                   8854: splitting on '=' and '&', supports elements that are arrayrefs and
                   8855: hashrefs
1.191     harris41 8856: 
                   8857: =item *
                   8858: 
1.243     albertel 8859: str2array($string) : convert string to hash using unescaping and
                   8860: splitting on '&', supports elements that are arrayrefs and hashrefs
                   8861: 
                   8862: =back
                   8863: 
                   8864: =head2 Logging Routines
                   8865: 
                   8866: =over 4
                   8867: 
                   8868: These routines allow one to make log messages in the lonnet.log and
                   8869: lonnet.perm logfiles.
1.191     harris41 8870: 
                   8871: =item *
                   8872: 
1.243     albertel 8873: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 8874: 
                   8875: =item *
                   8876: 
1.243     albertel 8877: logthis() : append message to the normal lonnet.log file, it gets
                   8878: preiodically rolled over and deleted.
1.191     harris41 8879: 
                   8880: =item *
                   8881: 
1.243     albertel 8882: logperm() : append a permanent message to lonnet.perm.log, this log
                   8883: file never gets deleted by any automated portion of the system, only
                   8884: messages of critical importance should go in here.
                   8885: 
                   8886: =back
                   8887: 
                   8888: =head2 General File Helper Routines
                   8889: 
                   8890: =over 4
1.191     harris41 8891: 
                   8892: =item *
                   8893: 
1.481     raeburn  8894: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   8895: (a) files in /uploaded
                   8896:   (i) If a local copy of the file exists - 
                   8897:       compares modification date of local copy with last-modified date for 
                   8898:       definitive version stored on home server for course. If local copy is 
                   8899:       stale, requests a new version from the home server and stores it. 
                   8900:       If the original has been removed from the home server, then local copy 
                   8901:       is unlinked.
                   8902:   (ii) If local copy does not exist -
                   8903:       requests the file from the home server and stores it. 
                   8904:   
                   8905:   If $caller is 'uploadrep':  
                   8906:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   8907:     for request for files originally uploaded via DOCS. 
                   8908:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   8909:   
                   8910:   Otherwise:
                   8911:      This indicates a call from the content generation phase of the request.
                   8912:      -  returns the entire contents of the file or -1.
                   8913:      
                   8914: (b) files in /res
                   8915:    - returns the entire contents of a file or -1; 
                   8916:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 8917: 
1.712     albertel 8918: 
                   8919: =item *
                   8920: 
                   8921: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   8922:                   reference
                   8923: 
                   8924: returns either a stat() list of data about the file or an empty list
                   8925: if the file doesn't exist or couldn't find out about it (connection
                   8926: problems or user unknown)
                   8927: 
1.191     harris41 8928: =item *
                   8929: 
1.243     albertel 8930: filelocation($dir,$file) : returns file system location of a file
                   8931: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   8932: directory that relative $file lookups are to looked in ($dir of /a/dir
                   8933: and a file of ../bob will become /a/bob)
1.191     harris41 8934: 
                   8935: =item *
                   8936: 
                   8937: hreflocation($dir,$file) : returns file system location or a URL; same as
                   8938: filelocation except for hrefs
                   8939: 
                   8940: =item *
                   8941: 
                   8942: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   8943: 
1.243     albertel 8944: =back
                   8945: 
1.608     albertel 8946: =head2 Usererfile file routines (/uploaded*)
                   8947: 
                   8948: =over 4
                   8949: 
                   8950: =item *
                   8951: 
                   8952: userfileupload(): main rotine for putting a file in a user or course's
                   8953:                   filespace, arguments are,
                   8954: 
1.620     albertel 8955:  formname - required - this is the name of the element in $env where the
1.608     albertel 8956:            filename, and the contents of the file to create/modifed exist
1.620     albertel 8957:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   8958:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 8959:  coursedoc - if true, store the file in the course of the active role
                   8960:              of the current user
                   8961:  subdir - required - subdirectory to put the file in under ../userfiles/
                   8962:          if undefined, it will be placed in "unknown"
                   8963: 
                   8964:  (This routine calls clean_filename() to remove any dangerous
                   8965:  characters from the filename, and then calls finuserfileupload() to
                   8966:  complete the transaction)
                   8967: 
                   8968:  returns either the url of the uploaded file (/uploaded/....) if successful
                   8969:  and /adm/notfound.html if unsuccessful
                   8970: 
                   8971: =item *
                   8972: 
                   8973: clean_filename(): routine for cleaing a filename up for storage in
                   8974:                  userfile space, argument is:
                   8975: 
                   8976:  filename - proposed filename
                   8977: 
                   8978: returns: the new clean filename
                   8979: 
                   8980: =item *
                   8981: 
                   8982: finishuserfileupload(): routine that creaes and sends the file to
                   8983: userspace, probably shouldn't be called directly
                   8984: 
                   8985:   docuname: username or courseid of destination for the file
                   8986:   docudom: domain of user/course of destination for the file
                   8987:   formname: same as for userfileupload()
                   8988:   fname: filename (inculding subdirectories) for the file
                   8989: 
                   8990:  returns either the url of the uploaded file (/uploaded/....) if successful
                   8991:  and /adm/notfound.html if unsuccessful
                   8992: 
                   8993: =item *
                   8994: 
                   8995: renameuserfile(): renames an existing userfile to a new name
                   8996: 
                   8997:   Args:
                   8998:    docuname: username or courseid of destination for the file
                   8999:    docudom: domain of user/course of destination for the file
                   9000:    old: current file name (including any subdirs under userfiles)
                   9001:    new: desired file name (including any subdirs under userfiles)
                   9002: 
                   9003: =item *
                   9004: 
                   9005: mkdiruserfile(): creates a directory is a userfiles dir
                   9006: 
                   9007:   Args:
                   9008:    docuname: username or courseid of destination for the file
                   9009:    docudom: domain of user/course of destination for the file
                   9010:    dir: dir to create (including any subdirs under userfiles)
                   9011: 
                   9012: =item *
                   9013: 
                   9014: removeuserfile(): removes a file that exists in userfiles
                   9015: 
                   9016:   Args:
                   9017:    docuname: username or courseid of destination for the file
                   9018:    docudom: domain of user/course of destination for the file
                   9019:    fname: filname to delete (including any subdirs under userfiles)
                   9020: 
                   9021: =item *
                   9022: 
                   9023: removeuploadedurl(): convience function for removeuserfile()
                   9024: 
                   9025:   Args:
                   9026:    url:  a full /uploaded/... url to delete
                   9027: 
1.747     albertel 9028: =item * 
                   9029: 
                   9030: get_portfile_permissions():
                   9031:   Args:
                   9032:     domain: domain of user or course contain the portfolio files
                   9033:     user: name of user or num of course contain the portfolio files
                   9034:   Returns:
                   9035:     hashref of a dump of the proper file_permissions.db
                   9036:    
                   9037: 
                   9038: =item * 
                   9039: 
                   9040: get_access_controls():
                   9041: 
                   9042: Args:
                   9043:   current_permissions: the hash ref returned from get_portfile_permissions()
                   9044:   group: (optional) the group you want the files associated with
                   9045:   file: (optional) the file you want access info on
                   9046: 
                   9047: Returns:
1.749     raeburn  9048:     a hash (keys are file names) of hashes containing
                   9049:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   9050:         values are XML containing access control settings (see below) 
1.747     albertel 9051: 
                   9052: Internal notes:
                   9053: 
1.749     raeburn  9054:  access controls are stored in file_permissions.db as key=value pairs.
                   9055:     key -> path to file/file_name\0uniqueID:scope_end_start
                   9056:         where scope -> public,guest,course,group,domains or users.
                   9057:               end -> UNIX time for end of access (0 -> no end date)
                   9058:               start -> UNIX time for start of access
                   9059: 
                   9060:     value -> XML description of access control
                   9061:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   9062:             <start></start>
                   9063:             <end></end>
                   9064: 
                   9065:             <password></password>  for scope type = guest
                   9066: 
                   9067:             <domain></domain>     for scope type = course or group
                   9068:             <number></number>
                   9069:             <roles id="">
                   9070:              <role></role>
                   9071:              <access></access>
                   9072:              <section></section>
                   9073:              <group></group>
                   9074:             </roles>
                   9075: 
                   9076:             <dom></dom>         for scope type = domains
                   9077: 
                   9078:             <users>             for scope type = users
                   9079:              <user>
                   9080:               <uname></uname>
                   9081:               <udom></udom>
                   9082:              </user>
                   9083:             </users>
                   9084:            </scope> 
                   9085:               
                   9086:  Access data is also aggregated for each file in an additional key=value pair:
                   9087:  key -> path to file/file_name\0accesscontrol 
                   9088:  value -> reference to hash
                   9089:           hash contains key = value pairs
                   9090:           where key = uniqueID:scope_end_start
                   9091:                 value = UNIX time record was last updated
                   9092: 
                   9093:           Used to improve speed of look-ups of access controls for each file.  
                   9094:  
                   9095:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   9096: 
                   9097: modify_access_controls():
                   9098: 
                   9099: Modifies access controls for a portfolio file
                   9100: Args
                   9101: 1. file name
                   9102: 2. reference to hash of required changes,
                   9103: 3. domain
                   9104: 4. username
                   9105:   where domain,username are the domain of the portfolio owner 
                   9106:   (either a user or a course) 
                   9107: 
                   9108: Returns:
                   9109: 1. result of additions or updates ('ok' or 'error', with error message). 
                   9110: 2. result of deletions ('ok' or 'error', with error message).
                   9111: 3. reference to hash of any new or updated access controls.
                   9112: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   9113:    key = integer (inbound ID)
                   9114:    value = uniqueID  
1.747     albertel 9115: 
1.608     albertel 9116: =back
                   9117: 
1.243     albertel 9118: =head2 HTTP Helper Routines
                   9119: 
                   9120: =over 4
                   9121: 
1.191     harris41 9122: =item *
                   9123: 
                   9124: escape() : unpack non-word characters into CGI-compatible hex codes
                   9125: 
                   9126: =item *
                   9127: 
                   9128: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   9129: 
1.243     albertel 9130: =back
                   9131: 
                   9132: =head1 PRIVATE SUBROUTINES
                   9133: 
                   9134: =head2 Underlying communication routines (Shouldn't call)
                   9135: 
                   9136: =over 4
                   9137: 
                   9138: =item *
                   9139: 
                   9140: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   9141: 
                   9142: =item *
                   9143: 
                   9144: reply() : uses subreply to send a message to remote machine, logs all failures
                   9145: 
                   9146: =item *
                   9147: 
                   9148: critical() : passes a critical message to another server; if cannot
                   9149: get through then place message in connection buffer directory and
                   9150: returns con_delayed, if incapable of saving message, returns
                   9151: con_failed
                   9152: 
                   9153: =item *
                   9154: 
                   9155: reconlonc() : tries to reconnect lonc client processes.
                   9156: 
                   9157: =back
                   9158: 
                   9159: =head2 Resource Access Logging
                   9160: 
                   9161: =over 4
                   9162: 
                   9163: =item *
                   9164: 
                   9165: flushcourselogs() : flush (save) buffer logs and access logs
                   9166: 
                   9167: =item *
                   9168: 
                   9169: courselog($what) : save message for course in hash
                   9170: 
                   9171: =item *
                   9172: 
                   9173: courseacclog($what) : save message for course using &courselog().  Perform
                   9174: special processing for specific resource types (problems, exams, quizzes, etc).
                   9175: 
1.191     harris41 9176: =item *
                   9177: 
                   9178: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   9179: as a PerlChildExitHandler
1.243     albertel 9180: 
                   9181: =back
                   9182: 
                   9183: =head2 Other
                   9184: 
                   9185: =over 4
                   9186: 
                   9187: =item *
                   9188: 
                   9189: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 9190: 
                   9191: =back
                   9192: 
                   9193: =cut

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