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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.824.2.2! albertel    4: # $Id: lonnet.pm,v 1.824.2.1 2007/01/25 21:10:51 albertel Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.1       albertel   30: package Apache::lonnet;
                     31: 
                     32: use strict;
1.8       www        33: use LWP::UserAgent();
1.15      www        34: use HTTP::Headers;
1.486     www        35: use HTTP::Date;
                     36: # use Date::Parse;
1.11      www        37: use vars 
1.599     albertel   38: qw(%perlvar %hostname %badServerCache %iphost %spareid %hostdom 
                     39:    %libserv %pr %prp $memcache %packagetab 
1.662     raeburn    40:    %courselogs %accesshash %userrolehash %domainrolehash $processmarker $dumpcount 
1.741     raeburn    41:    %coursedombuf %coursenumbuf %coursehombuf %coursedescrbuf %courseinstcodebuf %courseownerbuf %coursetypebuf
1.599     albertel   42:    %domaindescription %domain_auth_def %domain_auth_arg_def 
1.685     raeburn    43:    %domain_lang_def %domain_city %domain_longi %domain_lati %domain_primary
                     44:    $tmpdir $_64bit %env);
1.403     www        45: 
1.1       albertel   46: use IO::Socket;
1.31      www        47: use GDBM_File;
1.208     albertel   48: use HTML::LCParser;
1.637     raeburn    49: use HTML::Parser;
1.88      www        50: use Fcntl qw(:flock);
1.557     albertel   51: use Storable qw(lock_store lock_nstore lock_retrieve freeze thaw nfreeze);
1.539     albertel   52: use Time::HiRes qw( gettimeofday tv_interval );
1.599     albertel   53: use Cache::Memcached;
1.676     albertel   54: use Digest::MD5;
1.790     albertel   55: use Math::Random;
1.807     albertel   56: use LONCAPA qw(:DEFAULT :match);
1.740     www        57: use LONCAPA::Configuration;
1.676     albertel   58: 
1.195     www        59: my $readit;
1.550     foxr       60: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel   61: 
1.619     albertel   62: require Exporter;
                     63: 
                     64: our @ISA = qw (Exporter);
                     65: our @EXPORT = qw(%env);
                     66: 
1.449     matthew    67: =pod
                     68: 
                     69: =head1 Package Variables
                     70: 
                     71: These are largely undocumented, so if you decipher one please note it here.
                     72: 
                     73: =over 4
                     74: 
                     75: =item $processmarker
                     76: 
                     77: Contains the time this process was started and this servers host id.
                     78: 
                     79: =item $dumpcount
                     80: 
                     81: Counts the number of times a message log flush has been attempted (regardless
                     82: of success) by this process.  Used as part of the filename when messages are
                     83: delayed.
                     84: 
                     85: =back
                     86: 
                     87: =cut
                     88: 
                     89: 
1.1       albertel   90: # --------------------------------------------------------------------- Logging
1.729     www        91: {
                     92:     my $logid;
                     93:     sub instructor_log {
                     94: 	my ($hash_name,$storehash,$delflag,$uname,$udom)=@_;
                     95: 	$logid++;
                     96: 	my $id=time().'00000'.$$.'00000'.$logid;
                     97: 	return &Apache::lonnet::put('nohist_'.$hash_name,
1.730     www        98: 				    { $id => {
                     99: 					'exe_uname' => $env{'user.name'},
                    100: 					'exe_udom'  => $env{'user.domain'},
                    101: 					'exe_time'  => time(),
                    102: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    103: 					'delflag'   => $delflag,
                    104: 					'logentry'  => $storehash,
                    105: 					'uname'     => $uname,
                    106: 					'udom'      => $udom,
                    107: 				    }
                    108: 				  },
1.729     www       109: 				    $env{'course.'.$env{'request.course.id'}.'.domain'},
                    110: 				    $env{'course.'.$env{'request.course.id'}.'.num'}
                    111: 				    );
                    112:     }
                    113: }
1.1       albertel  114: 
1.163     harris41  115: sub logtouch {
                    116:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  117:     unless (-e "$execdir/logs/lonnet.log") {	
                    118: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  119: 	close $fh;
                    120:     }
                    121:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    122:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    123: }
                    124: 
1.1       albertel  125: sub logthis {
                    126:     my $message=shift;
                    127:     my $execdir=$perlvar{'lonDaemons'};
                    128:     my $now=time;
                    129:     my $local=localtime($now);
1.448     albertel  130:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
                    131: 	print $fh "$local ($$): $message\n";
                    132: 	close($fh);
                    133:     }
1.1       albertel  134:     return 1;
                    135: }
                    136: 
                    137: sub logperm {
                    138:     my $message=shift;
                    139:     my $execdir=$perlvar{'lonDaemons'};
                    140:     my $now=time;
                    141:     my $local=localtime($now);
1.448     albertel  142:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    143: 	print $fh "$now:$message:$local\n";
                    144: 	close($fh);
                    145:     }
1.1       albertel  146:     return 1;
                    147: }
                    148: 
                    149: # -------------------------------------------------- Non-critical communication
                    150: sub subreply {
                    151:     my ($cmd,$server)=@_;
1.704     albertel  152:     my $peerfile="$perlvar{'lonSockDir'}/".$hostname{$server};
1.549     foxr      153:     #
                    154:     #  With loncnew process trimming, there's a timing hole between lonc server
                    155:     #  process exit and the master server picking up the listen on the AF_UNIX
                    156:     #  socket.  In that time interval, a lock file will exist:
                    157: 
                    158:     my $lockfile=$peerfile.".lock";
                    159:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    160: 	sleep(1);
                    161:     }
                    162:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      163:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      164:     #
1.550     foxr      165:     #   We'll give the connection a few tries before abandoning it.  If
                    166:     #   connection is not possible, we'll con_lost back to the client.
                    167:     #   
                    168:     my $client;
                    169:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    170: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    171: 				      Type    => SOCK_STREAM,
                    172: 				      Timeout => 10);
                    173: 	if($client) {
                    174: 	    last;		# Connected!
                    175: 	}
                    176: 	sleep(1);		# Try again later if failed connection.
                    177:     }
                    178:     my $answer;
                    179:     if ($client) {
1.704     albertel  180: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      181: 	$answer=<$client>;
                    182: 	if (!$answer) { $answer="con_lost"; }
                    183: 	chomp($answer);
                    184:     } else {
                    185: 	$answer = 'con_lost';	# Failed connection.
                    186:     }
1.1       albertel  187:     return $answer;
                    188: }
                    189: 
                    190: sub reply {
                    191:     my ($cmd,$server)=@_;
1.205     www       192:     unless (defined($hostname{$server})) { return 'no_such_host'; }
1.1       albertel  193:     my $answer=subreply($cmd,$server);
1.65      www       194:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  195:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       196:                 " $cmd to $server returned $answer</font>");
                    197:     }
1.1       albertel  198:     return $answer;
                    199: }
                    200: 
                    201: # ----------------------------------------------------------- Send USR1 to lonc
                    202: 
                    203: sub reconlonc {
                    204:     my $peerfile=shift;
                    205:     &logthis("Trying to reconnect for $peerfile");
                    206:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  207:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  208: 	my $loncpid=<$fh>;
                    209:         chomp($loncpid);
                    210:         if (kill 0 => $loncpid) {
                    211: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    212:             kill USR1 => $loncpid;
                    213:             sleep 1;
                    214:             if (-e "$peerfile") { return; }
                    215:             &logthis("$peerfile still not there, give it another try");
                    216:             sleep 5;
                    217:             if (-e "$peerfile") { return; }
1.12      www       218:             &logthis(
1.672     albertel  219:   "<font color=\"blue\">WARNING: $peerfile still not there, giving up</font>");
1.1       albertel  220:         } else {
1.12      www       221: 	    &logthis(
1.672     albertel  222:                "<font color=\"blue\">WARNING:".
1.12      www       223:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  224:         }
                    225:     } else {
1.672     albertel  226:      &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  227:     }
                    228: }
                    229: 
                    230: # ------------------------------------------------------ Critical communication
1.12      www       231: 
1.1       albertel  232: sub critical {
                    233:     my ($cmd,$server)=@_;
1.89      www       234:     unless ($hostname{$server}) {
1.672     albertel  235:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       236:                " Critical message to unknown server ($server)</font>");
                    237:         return 'no_such_host';
                    238:     }
1.1       albertel  239:     my $answer=reply($cmd,$server);
                    240:     if ($answer eq 'con_lost') {
                    241: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  242: 	my $answer=reply($cmd,$server);
1.1       albertel  243:         if ($answer eq 'con_lost') {
                    244:             my $now=time;
                    245:             my $middlename=$cmd;
1.5       www       246:             $middlename=substr($middlename,0,16);
1.1       albertel  247:             $middlename=~s/\W//g;
                    248:             my $dfilename=
1.305     www       249:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    250:             $dumpcount++;
1.1       albertel  251:             {
1.448     albertel  252: 		my $dfh;
                    253: 		if (open($dfh,">$dfilename")) {
                    254: 		    print $dfh "$cmd\n"; 
                    255: 		    close($dfh);
                    256: 		}
1.1       albertel  257:             }
                    258:             sleep 2;
                    259:             my $wcmd='';
                    260:             {
1.448     albertel  261: 		my $dfh;
                    262: 		if (open($dfh,"<$dfilename")) {
                    263: 		    $wcmd=<$dfh>; 
                    264: 		    close($dfh);
                    265: 		}
1.1       albertel  266:             }
                    267:             chomp($wcmd);
1.7       www       268:             if ($wcmd eq $cmd) {
1.672     albertel  269: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       270:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  271:                 &logperm("D:$server:$cmd");
                    272: 	        return 'con_delayed';
                    273:             } else {
1.672     albertel  274:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       275:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  276:                 &logperm("F:$server:$cmd");
                    277:                 return 'con_failed';
                    278:             }
                    279:         }
                    280:     }
                    281:     return $answer;
1.405     albertel  282: }
                    283: 
1.755     albertel  284: # ------------------------------------------- check if return value is an error
                    285: 
                    286: sub error {
                    287:     my ($result) = @_;
1.756     albertel  288:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  289: 	if ($2 == 2) { return undef; }
                    290: 	return $1;
                    291:     }
                    292:     return undef;
                    293: }
                    294: 
1.783     albertel  295: sub convert_and_load_session_env {
                    296:     my ($lonidsdir,$handle)=@_;
                    297:     my @profile;
                    298:     {
                    299: 	open(my $idf,"$lonidsdir/$handle.id");
                    300: 	flock($idf,LOCK_SH);
                    301: 	@profile=<$idf>;
                    302: 	close($idf);
                    303:     }
                    304:     my %temp_env;
                    305:     foreach my $line (@profile) {
1.786     albertel  306: 	if ($line !~ m/=/) {
                    307: 	    return 0;
                    308: 	}
1.783     albertel  309: 	chomp($line);
                    310: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    311: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    312:     }
                    313:     unlink("$lonidsdir/$handle.id");
                    314:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    315: 	    0640)) {
                    316: 	%disk_env = %temp_env;
                    317: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    318: 	untie(%disk_env);
                    319:     }
1.786     albertel  320:     return 1;
1.783     albertel  321: }
                    322: 
1.374     www       323: # ------------------------------------------- Transfer profile into environment
1.780     albertel  324: my $env_loaded;
                    325: sub transfer_profile_to_env {
1.788     albertel  326:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    327:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       328: 
1.720     albertel  329:     if (!defined($lonidsdir)) {
                    330: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    331:     }
                    332:     if (!defined($handle)) {
                    333:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    334:     }
                    335: 
1.786     albertel  336:     my $convert;
                    337:     {
                    338:     	open(my $idf,"$lonidsdir/$handle.id");
                    339: 	flock($idf,LOCK_SH);
                    340: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    341: 		&GDBM_READER(),0640)) {
                    342: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    343: 	    untie(%disk_env);
                    344: 	} else {
                    345: 	    $convert = 1;
                    346: 	}
                    347:     }
                    348:     if ($convert) {
                    349: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    350: 	    &logthis("Failed to load session, or convert session.");
                    351: 	}
1.374     www       352:     }
1.783     albertel  353: 
1.786     albertel  354:     my %remove;
1.783     albertel  355:     while ( my $envname = each(%env) ) {
1.433     matthew   356:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    357:             if ($time < time-300) {
1.783     albertel  358:                 $remove{$key}++;
1.433     matthew   359:             }
                    360:         }
                    361:     }
1.783     albertel  362: 
1.619     albertel  363:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  364:     $env_loaded=1;
1.783     albertel  365:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   366:         &delenv($expired_key);
1.374     www       367:     }
1.1       albertel  368: }
                    369: 
1.824.2.1  albertel  370: sub timed_flock {
                    371:     my ($file,$lock_type) = @_;
                    372:     my $failed=0;
                    373:     eval {
                    374: 	local $SIG{__DIE__}='DEFAULT';
                    375: 	local $SIG{ALRM}=sub {
                    376: 	    $failed=1;
                    377: 	    die("failed lock");
                    378: 	};
                    379: 	alarm(13);
                    380: 	flock($file,$lock_type);
                    381: 	alarm(0);
                    382:     };
                    383:     if ($failed) {
                    384: 	return undef;
                    385:     } else {
                    386: 	return 1;
                    387:     }
                    388: }
                    389: 
1.5       www       390: # ---------------------------------------------------------- Append Environment
                    391: 
                    392: sub appenv {
1.6       www       393:     my %newenv=@_;
1.692     albertel  394:     foreach my $key (keys(%newenv)) {
                    395: 	if (($newenv{$key}=~/^user\.role/) || ($newenv{$key}=~/^user\.priv/)) {
1.672     albertel  396:             &logthis("<font color=\"blue\">WARNING: ".
1.692     albertel  397:                 "Attempt to modify environment ".$key." to ".$newenv{$key}
1.151     www       398:                 .'</font>');
1.692     albertel  399: 	    delete($newenv{$key});
1.35      www       400:         } else {
1.692     albertel  401:             $env{$key}=$newenv{$key};
1.35      www       402:         }
1.191     harris41  403:     }
1.824.2.1  albertel  404:     open(my $env_file,$env{'user.environment'});
                    405:     if (&timed_flock($env_file,LOCK_EX)
                    406: 	&&
                    407: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    408: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  409: 	while (my ($key,$value) = each(%newenv)) {
                    410: 	    $disk_env{$key} = $value;
1.448     albertel  411: 	}
1.783     albertel  412: 	untie(%disk_env);
1.56      www       413:     }
                    414:     return 'ok';
                    415: }
                    416: # ----------------------------------------------------- Delete from Environment
                    417: 
                    418: sub delenv {
                    419:     my $delthis=shift;
                    420:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672     albertel  421:         &logthis("<font color=\"blue\">WARNING: ".
1.56      www       422:                 "Attempt to delete from environment ".$delthis);
                    423:         return 'error';
                    424:     }
1.824.2.1  albertel  425:     open(my $env_file,$env{'user.environment'});
                    426:     if (&timed_flock($env_file,LOCK_EX)
                    427: 	&&
                    428: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    429: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  430: 	foreach my $key (keys(%disk_env)) {
                    431: 	    if ($key=~/^$delthis/) { 
1.619     albertel  432:                 delete($env{$key});
1.783     albertel  433:                 delete($disk_env{$key});
1.473     matthew   434:             }
1.448     albertel  435: 	}
1.783     albertel  436: 	untie(%disk_env);
1.5       www       437:     }
                    438:     return 'ok';
1.369     albertel  439: }
                    440: 
1.790     albertel  441: sub get_env_multiple {
                    442:     my ($name) = @_;
                    443:     my @values;
                    444:     if (defined($env{$name})) {
                    445:         # exists is it an array
                    446:         if (ref($env{$name})) {
                    447:             @values=@{ $env{$name} };
                    448:         } else {
                    449:             $values[0]=$env{$name};
                    450:         }
                    451:     }
                    452:     return(@values);
                    453: }
                    454: 
1.369     albertel  455: # ------------------------------------------ Find out current server userload
                    456: # there is a copy in lond
                    457: sub userload {
                    458:     my $numusers=0;
                    459:     {
                    460: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    461: 	my $filename;
                    462: 	my $curtime=time;
                    463: 	while ($filename=readdir(LONIDS)) {
                    464: 	    if ($filename eq '.' || $filename eq '..') {next;}
1.404     albertel  465: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  466: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  467: 	}
                    468: 	closedir(LONIDS);
                    469:     }
                    470:     my $userloadpercent=0;
                    471:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    472:     if ($maxuserload) {
1.371     albertel  473: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  474:     }
1.372     albertel  475:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  476:     return $userloadpercent;
1.283     www       477: }
                    478: 
                    479: # ------------------------------------------ Fight off request when overloaded
                    480: 
                    481: sub overloaderror {
                    482:     my ($r,$checkserver)=@_;
                    483:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
                    484:     my $loadavg;
                    485:     if ($checkserver eq $perlvar{'lonHostID'}) {
1.448     albertel  486:        open(my $loadfile,'/proc/loadavg');
1.283     www       487:        $loadavg=<$loadfile>;
                    488:        $loadavg =~ s/\s.*//g;
1.285     matthew   489:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448     albertel  490:        close($loadfile);
1.283     www       491:     } else {
                    492:        $loadavg=&reply('load',$checkserver);
                    493:     }
1.285     matthew   494:     my $overload=$loadavg-100;
1.283     www       495:     if ($overload>0) {
1.285     matthew   496: 	$r->err_headers_out->{'Retry-After'}=$overload;
1.283     www       497:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554     www       498:         return 413;
1.283     www       499:     }    
                    500:     return '';
1.5       www       501: }
1.1       albertel  502: 
                    503: # ------------------------------ Find server with least workload from spare.tab
1.11      www       504: 
1.1       albertel  505: sub spareserver {
1.670     albertel  506:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.784     albertel  507:     my $spare_server;
1.370     albertel  508:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  509:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    510:                                                      :  $userloadpercent;
                    511:     
                    512:     foreach my $try_server (@{ $spareid{'primary'} }) {
                    513: 	($spare_server, $lowest_load) =
                    514: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
                    515:     }
                    516: 
                    517:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    518: 
                    519:     if (!$found_server) {
                    520: 	foreach my $try_server (@{ $spareid{'default'} }) {
                    521: 	    ($spare_server, $lowest_load) =
                    522: 		&compare_server_load($try_server, $spare_server, $lowest_load);
                    523: 	}
                    524:     }
                    525: 
                    526:     if (!$want_server_name) {
                    527: 	$spare_server="http://$hostname{$spare_server}";
                    528:     }
                    529:     return $spare_server;
                    530: }
                    531: 
                    532: sub compare_server_load {
                    533:     my ($try_server, $spare_server, $lowest_load) = @_;
                    534: 
                    535:     my $loadans     = &reply('load',    $try_server);
                    536:     my $userloadans = &reply('userload',$try_server);
                    537: 
                    538:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
                    539: 	next; #didn't get a number from the server
                    540:     }
                    541: 
                    542:     my $load;
                    543:     if ($loadans =~ /\d/) {
                    544: 	if ($userloadans =~ /\d/) {
                    545: 	    #both are numbers, pick the bigger one
                    546: 	    $load = ($loadans > $userloadans) ? $loadans 
                    547: 		                              : $userloadans;
1.411     albertel  548: 	} else {
1.784     albertel  549: 	    $load = $loadans;
1.411     albertel  550: 	}
1.784     albertel  551:     } else {
                    552: 	$load = $userloadans;
                    553:     }
                    554: 
                    555:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    556: 	$spare_server = $try_server;
                    557: 	$lowest_load  = $load;
1.370     albertel  558:     }
1.784     albertel  559:     return ($spare_server,$lowest_load);
1.202     matthew   560: }
                    561: # --------------------------------------------- Try to change a user's password
                    562: 
                    563: sub changepass {
1.799     raeburn   564:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   565:     $currentpass = &escape($currentpass);
                    566:     $newpass     = &escape($newpass);
1.799     raeburn   567:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
1.202     matthew   568: 		       $server);
                    569:     if (! $answer) {
                    570: 	&logthis("No reply on password change request to $server ".
                    571: 		 "by $uname in domain $udom.");
                    572:     } elsif ($answer =~ "^ok") {
                    573:         &logthis("$uname in $udom successfully changed their password ".
                    574: 		 "on $server.");
                    575:     } elsif ($answer =~ "^pwchange_failure") {
                    576: 	&logthis("$uname in $udom was unable to change their password ".
                    577: 		 "on $server.  The action was blocked by either lcpasswd ".
                    578: 		 "or pwchange");
                    579:     } elsif ($answer =~ "^non_authorized") {
                    580:         &logthis("$uname in $udom did not get their password correct when ".
                    581: 		 "attempting to change it on $server.");
                    582:     } elsif ($answer =~ "^auth_mode_error") {
                    583:         &logthis("$uname in $udom attempted to change their password despite ".
                    584: 		 "not being locally or internally authenticated on $server.");
                    585:     } elsif ($answer =~ "^unknown_user") {
                    586:         &logthis("$uname in $udom attempted to change their password ".
                    587: 		 "on $server but were unable to because $server is not ".
                    588: 		 "their home server.");
                    589:     } elsif ($answer =~ "^refused") {
                    590: 	&logthis("$server refused to change $uname in $udom password because ".
                    591: 		 "it was sent an unencrypted request to change the password.");
                    592:     }
                    593:     return $answer;
1.1       albertel  594: }
                    595: 
1.169     harris41  596: # ----------------------- Try to determine user's current authentication scheme
                    597: 
                    598: sub queryauthenticate {
                    599:     my ($uname,$udom)=@_;
1.456     albertel  600:     my $uhome=&homeserver($uname,$udom);
                    601:     if (!$uhome) {
                    602: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                    603: 	return 'no_host';
                    604:     }
                    605:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                    606:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                    607: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41  608:     }
1.456     albertel  609:     return $answer;
1.169     harris41  610: }
                    611: 
1.1       albertel  612: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       613: 
1.1       albertel  614: sub authenticate {
                    615:     my ($uname,$upass,$udom)=@_;
1.807     albertel  616:     $upass=&escape($upass);
                    617:     $uname= &LONCAPA::clean_username($uname);
1.471     albertel  618:     my $uhome=&homeserver($uname,$udom);
                    619:     if (!$uhome) {
                    620: 	&logthis("User $uname at $udom is unknown in authenticate");
                    621: 	return 'no_host';
1.1       albertel  622:     }
1.471     albertel  623:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
                    624:     if ($answer eq 'authorized') {
                    625: 	&logthis("User $uname at $udom authorized by $uhome"); 
                    626: 	return $uhome; 
                    627:     }
                    628:     if ($answer eq 'non_authorized') {
                    629: 	&logthis("User $uname at $udom rejected by $uhome");
                    630: 	return 'no_host'; 
1.9       www       631:     }
1.471     albertel  632:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel  633:     return 'no_host';
                    634: }
                    635: 
                    636: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www       637: 
1.599     albertel  638: my %homecache;
1.1       albertel  639: sub homeserver {
1.230     stredwic  640:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel  641:     my $index="$uname:$udom";
1.426     albertel  642: 
1.599     albertel  643:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.1       albertel  644:     my $tryserver;
                    645:     foreach $tryserver (keys %libserv) {
1.230     stredwic  646:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic  647: 		 exists($badServerCache{$tryserver}));
1.1       albertel  648: 	if ($hostdom{$tryserver} eq $udom) {
                    649:            my $answer=reply("home:$udom:$uname",$tryserver);
                    650:            if ($answer eq 'found') { 
1.599     albertel  651: 	       return $homecache{$index}=$tryserver;
1.231     stredwic  652:            } elsif ($answer eq 'no_host') {
                    653: 	       $badServerCache{$tryserver}=1;
1.221     matthew   654:            }
1.1       albertel  655:        }
                    656:     }    
                    657:     return 'no_host';
1.70      www       658: }
                    659: 
                    660: # ------------------------------------- Find the usernames behind a list of IDs
                    661: 
                    662: sub idget {
                    663:     my ($udom,@ids)=@_;
                    664:     my %returnhash=();
                    665:     
                    666:     my $tryserver;
                    667:     foreach $tryserver (keys %libserv) {
                    668:        if ($hostdom{$tryserver} eq $udom) {
                    669: 	  my $idlist=join('&',@ids);
                    670:           $idlist=~tr/A-Z/a-z/; 
                    671: 	  my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                    672:           my @answer=();
1.76      www       673:           if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1.70      www       674: 	      @answer=split(/\&/,$reply);
                    675:           }                    ;
                    676:           my $i;
                    677:           for ($i=0;$i<=$#ids;$i++) {
                    678:               if ($answer[$i]) {
                    679: 		  $returnhash{$ids[$i]}=$answer[$i];
                    680:               } 
                    681:           }
                    682:        }
                    683:     }    
                    684:     return %returnhash;
                    685: }
                    686: 
                    687: # ------------------------------------- Find the IDs behind a list of usernames
                    688: 
                    689: sub idrget {
                    690:     my ($udom,@unames)=@_;
                    691:     my %returnhash=();
1.800     albertel  692:     foreach my $uname (@unames) {
                    693:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41  694:     }
1.70      www       695:     return %returnhash;
                    696: }
                    697: 
                    698: # ------------------------------- Store away a list of names and associated IDs
                    699: 
                    700: sub idput {
                    701:     my ($udom,%ids)=@_;
                    702:     my %servers=();
1.800     albertel  703:     foreach my $uname (keys(%ids)) {
                    704: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                    705:         my $uhom=&homeserver($uname,$udom);
1.70      www       706:         if ($uhom ne 'no_host') {
1.800     albertel  707:             my $id=&escape($ids{$uname});
1.70      www       708:             $id=~tr/A-Z/a-z/;
1.800     albertel  709:             my $esc_unam=&escape($uname);
1.70      www       710: 	    if ($servers{$uhom}) {
1.800     albertel  711: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www       712:             } else {
1.800     albertel  713:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www       714:             }
                    715:         }
1.191     harris41  716:     }
1.800     albertel  717:     foreach my $server (keys(%servers)) {
                    718:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41  719:     }
1.344     www       720: }
                    721: 
1.806     raeburn   722: # ------------------------------------------- get items from domain db files   
                    723: 
                    724: sub get_dom {
                    725:     my ($namespace,$storearr,$udom)=@_;
                    726:     my $items='';
                    727:     foreach my $item (@$storearr) {
                    728:         $items.=&escape($item).'&';
                    729:     }
                    730:     $items=~s/\&$//;
                    731:     if (!$udom) { $udom=$env{'user.domain'}; }
                    732:     if (exists($domain_primary{$udom})) {
                    733:         my $uhome=$domain_primary{$udom};
                    734:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
                    735:         my @pairs=split(/\&/,$rep);
                    736:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                    737:             return @pairs;
                    738:         }
                    739:         my %returnhash=();
                    740:         my $i=0;
                    741:         foreach my $item (@$storearr) {
                    742:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                    743:             $i++;
                    744:         }
                    745:         return %returnhash;
                    746:     } else {
                    747:         &logthis("get_dom failed - no primary domain server for $udom");
                    748:     }
                    749: }
                    750: 
                    751: # -------------------------------------------- put items in domain db files 
                    752: 
                    753: sub put_dom {
                    754:     my ($namespace,$storehash,$udom)=@_;
                    755:     if (!$udom) { $udom=$env{'user.domain'}; }
                    756:     if (exists($domain_primary{$udom})) {
                    757:         my $uhome=$domain_primary{$udom};
                    758:         my $items='';
                    759:         foreach my $item (keys(%$storehash)) {
                    760:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                    761:         }
                    762:         $items=~s/\&$//;
                    763:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                    764:     } else {
                    765:         &logthis("put_dom failed - no primary domain server for $udom");
                    766:     }
                    767: }
                    768: 
1.344     www       769: # --------------------------------------------------- Assign a key to a student
                    770: 
                    771: sub assign_access_key {
1.364     www       772: #
                    773: # a valid key looks like uname:udom#comments
                    774: # comments are being appended
                    775: #
1.498     www       776:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                    777:     $kdom=
1.620     albertel  778:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www       779:     $knum=
1.620     albertel  780:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www       781:     $cdom=
1.620     albertel  782:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       783:     $cnum=
1.620     albertel  784:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    785:     $udom=$env{'user.name'} unless (defined($udom));
                    786:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www       787:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www       788:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel  789:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www       790:                                                   # assigned to this person
                    791:                                                   # - this should not happen,
1.345     www       792:                                                   # unless something went wrong
                    793:                                                   # the first time around
                    794: # ready to assign
1.364     www       795:         $logentry=$1.'; '.$logentry;
1.496     www       796:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www       797:                                                  $kdom,$knum) eq 'ok') {
1.345     www       798: # key now belongs to user
1.346     www       799: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www       800:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
                    801:                 &appenv('environment.'.$envkey => $ckey);
                    802:                 return 'ok';
                    803:             } else {
                    804:                 return 
                    805:   'error: Count not permanently assign key, will need to be re-entered later.';
                    806: 	    }
                    807:         } else {
                    808:             return 'error: Could not assign key, try again later.';
                    809:         }
1.364     www       810:     } elsif (!$existing{$ckey}) {
1.345     www       811: # the key does not exist
                    812: 	return 'error: The key does not exist';
                    813:     } else {
                    814: # the key is somebody else's
                    815: 	return 'error: The key is already in use';
                    816:     }
1.344     www       817: }
                    818: 
1.364     www       819: # ------------------------------------------ put an additional comment on a key
                    820: 
                    821: sub comment_access_key {
                    822: #
                    823: # a valid key looks like uname:udom#comments
                    824: # comments are being appended
                    825: #
                    826:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                    827:     $cdom=
1.620     albertel  828:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www       829:     $cnum=
1.620     albertel  830:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www       831:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                    832:     if ($existing{$ckey}) {
                    833:         $existing{$ckey}.='; '.$logentry;
                    834: # ready to assign
1.367     www       835:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www       836:                                                  $cdom,$cnum) eq 'ok') {
                    837: 	    return 'ok';
                    838:         } else {
                    839: 	    return 'error: Count not store comment.';
                    840:         }
                    841:     } else {
                    842: # the key does not exist
                    843: 	return 'error: The key does not exist';
                    844:     }
                    845: }
                    846: 
1.344     www       847: # ------------------------------------------------------ Generate a set of keys
                    848: 
                    849: sub generate_access_keys {
1.364     www       850:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www       851:     $cdom=
1.620     albertel  852:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       853:     $cnum=
1.620     albertel  854:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www       855:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www       856:     unless (($cdom) && ($cnum)) { return 0; }
                    857:     if ($number>10000) { return 0; }
                    858:     sleep(2); # make sure don't get same seed twice
                    859:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                    860:     my $total=0;
                    861:     for (my $i=1;$i<=$number;$i++) {
                    862:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                    863:                   sprintf("%lx",int(100000*rand)).'-'.
                    864:                   sprintf("%lx",int(100000*rand));
                    865:        $newkey=~s/1/g/g; # folks mix up 1 and l
                    866:        $newkey=~s/0/h/g; # and also 0 and O
                    867:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                    868:        if ($existing{$newkey}) {
                    869:            $i--;
                    870:        } else {
1.364     www       871: 	  if (&put('accesskeys',
                    872:               { $newkey => '# generated '.localtime().
1.620     albertel  873:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www       874:                            '; '.$logentry },
                    875: 		   $cdom,$cnum) eq 'ok') {
1.344     www       876:               $total++;
                    877: 	  }
                    878:        }
                    879:     }
1.620     albertel  880:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www       881:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                    882:     return $total;
                    883: }
                    884: 
                    885: # ------------------------------------------------------- Validate an accesskey
                    886: 
                    887: sub validate_access_key {
                    888:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                    889:     $cdom=
1.620     albertel  890:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       891:     $cnum=
1.620     albertel  892:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    893:     $udom=$env{'user.domain'} unless (defined($udom));
                    894:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www       895:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel  896:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www       897: }
                    898: 
                    899: # ------------------------------------- Find the section of student in a course
1.652     albertel  900: sub devalidate_getsection_cache {
                    901:     my ($udom,$unam,$courseid)=@_;
                    902:     my $hashid="$udom:$unam:$courseid";
                    903:     &devalidate_cache_new('getsection',$hashid);
                    904: }
1.298     matthew   905: 
1.815     albertel  906: sub courseid_to_courseurl {
                    907:     my ($courseid) = @_;
                    908:     #already url style courseid
                    909:     return $courseid if ($courseid =~ m{^/});
                    910: 
                    911:     if (exists($env{'course.'.$courseid.'.num'})) {
                    912: 	my $cnum = $env{'course.'.$courseid.'.num'};
                    913: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                    914: 	return "/$cdom/$cnum";
                    915:     }
                    916: 
                    917:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                    918:     if (exists($courseinfo{'num'})) {
                    919: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                    920:     }
                    921: 
                    922:     return undef;
                    923: }
                    924: 
1.298     matthew   925: sub getsection {
                    926:     my ($udom,$unam,$courseid)=@_;
1.599     albertel  927:     my $cachetime=1800;
1.551     albertel  928: 
                    929:     my $hashid="$udom:$unam:$courseid";
1.599     albertel  930:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel  931:     if (defined($cached)) { return $result; }
                    932: 
1.298     matthew   933:     my %Pending; 
                    934:     my %Expired;
                    935:     #
                    936:     # Each role can either have not started yet (pending), be active, 
                    937:     #    or have expired.
                    938:     #
                    939:     # If there is an active role, we are done.
                    940:     #
                    941:     # If there is more than one role which has not started yet, 
                    942:     #     choose the one which will start sooner
                    943:     # If there is one role which has not started yet, return it.
                    944:     #
                    945:     # If there is more than one expired role, choose the one which ended last.
                    946:     # If there is a role which has expired, return it.
                    947:     #
1.815     albertel  948:     $courseid = &courseid_to_courseurl($courseid);
1.817     raeburn   949:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
                    950:     foreach my $key (keys(%roleshash)) {
1.479     albertel  951:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew   952:         my $section=$1;
                    953:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn   954:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew   955:         my $now=time;
1.548     albertel  956:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew   957:             $Expired{$end}=$section;
                    958:             next;
                    959:         }
1.548     albertel  960:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew   961:             $Pending{$start}=$section;
                    962:             next;
                    963:         }
1.599     albertel  964:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew   965:     }
                    966:     #
                    967:     # Presumedly there will be few matching roles from the above
                    968:     # loop and the sorting time will be negligible.
                    969:     if (scalar(keys(%Pending))) {
                    970:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel  971:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew   972:     } 
                    973:     if (scalar(keys(%Expired))) {
                    974:         my @sorted = sort {$a <=> $b} keys(%Expired);
                    975:         my $time = pop(@sorted);
1.599     albertel  976:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew   977:     }
1.599     albertel  978:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew   979: }
1.70      www       980: 
1.599     albertel  981: sub save_cache {
                    982:     &purge_remembered();
1.722     albertel  983:     #&Apache::loncommon::validate_page();
1.620     albertel  984:     undef(%env);
1.780     albertel  985:     undef($env_loaded);
1.599     albertel  986: }
1.452     albertel  987: 
1.599     albertel  988: my $to_remember=-1;
                    989: my %remembered;
                    990: my %accessed;
                    991: my $kicks=0;
                    992: my $hits=0;
                    993: sub devalidate_cache_new {
                    994:     my ($name,$id,$debug) = @_;
                    995:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
                    996:     $id=&escape($name.':'.$id);
                    997:     $memcache->delete($id);
                    998:     delete($remembered{$id});
                    999:     delete($accessed{$id});
                   1000: }
                   1001: 
                   1002: sub is_cached_new {
                   1003:     my ($name,$id,$debug) = @_;
                   1004:     $id=&escape($name.':'.$id);
                   1005:     if (exists($remembered{$id})) {
                   1006: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                   1007: 	$accessed{$id}=[&gettimeofday()];
                   1008: 	$hits++;
                   1009: 	return ($remembered{$id},1);
                   1010:     }
                   1011:     my $value = $memcache->get($id);
                   1012:     if (!(defined($value))) {
                   1013: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 1014: 	return (undef,undef);
1.416     albertel 1015:     }
1.599     albertel 1016:     if ($value eq '__undef__') {
                   1017: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   1018: 	$value=undef;
                   1019:     }
                   1020:     &make_room($id,$value,$debug);
                   1021:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   1022:     return ($value,1);
                   1023: }
                   1024: 
                   1025: sub do_cache_new {
                   1026:     my ($name,$id,$value,$time,$debug) = @_;
                   1027:     $id=&escape($name.':'.$id);
                   1028:     my $setvalue=$value;
                   1029:     if (!defined($setvalue)) {
                   1030: 	$setvalue='__undef__';
                   1031:     }
1.623     albertel 1032:     if (!defined($time) ) {
                   1033: 	$time=600;
                   1034:     }
1.599     albertel 1035:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.600     albertel 1036:     $memcache->set($id,$setvalue,$time);
                   1037:     # need to make a copy of $value
                   1038:     #&make_room($id,$value,$debug);
1.599     albertel 1039:     return $value;
                   1040: }
                   1041: 
                   1042: sub make_room {
                   1043:     my ($id,$value,$debug)=@_;
                   1044:     $remembered{$id}=$value;
                   1045:     if ($to_remember<0) { return; }
                   1046:     $accessed{$id}=[&gettimeofday()];
                   1047:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   1048:     my $to_kick;
                   1049:     my $max_time=0;
                   1050:     foreach my $other (keys(%accessed)) {
                   1051: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   1052: 	    $to_kick=$other;
                   1053: 	    $max_time=&tv_interval($accessed{$other});
                   1054: 	}
                   1055:     }
                   1056:     delete($remembered{$to_kick});
                   1057:     delete($accessed{$to_kick});
                   1058:     $kicks++;
                   1059:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 1060:     return;
                   1061: }
                   1062: 
1.599     albertel 1063: sub purge_remembered {
1.604     albertel 1064:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   1065:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 1066:     undef(%remembered);
                   1067:     undef(%accessed);
1.428     albertel 1068: }
1.70      www      1069: # ------------------------------------- Read an entry from a user's environment
                   1070: 
                   1071: sub userenvironment {
                   1072:     my ($udom,$unam,@what)=@_;
                   1073:     my %returnhash=();
                   1074:     my @answer=split(/\&/,
                   1075:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
                   1076:                       &homeserver($unam,$udom)));
                   1077:     my $i;
                   1078:     for ($i=0;$i<=$#what;$i++) {
                   1079: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                   1080:     }
                   1081:     return %returnhash;
1.1       albertel 1082: }
                   1083: 
1.617     albertel 1084: # ---------------------------------------------------------- Get a studentphoto
                   1085: sub studentphoto {
                   1086:     my ($udom,$unam,$ext) = @_;
                   1087:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1088:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1089:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1090:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1091:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1092:             } else {
                   1093:                 my ($result,$perm_reqd)=
1.707     albertel 1094: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1095:                 if ($result eq 'ok') {
                   1096:                     if (!($perm_reqd eq 'yes')) {
                   1097:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1098:                     }
                   1099:                 }
                   1100:             }
                   1101:         }
                   1102:     } else {
                   1103:         my ($result,$perm_reqd) = 
1.707     albertel 1104: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1105:         if ($result eq 'ok') {
                   1106:             if (!($perm_reqd eq 'yes')) {
                   1107:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1108:             }
                   1109:         }
                   1110:     }
                   1111:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1112: }
                   1113: 
                   1114: sub retrievestudentphoto {
                   1115:     my ($udom,$unam,$ext,$type) = @_;
                   1116:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1117:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1118:     if ($ret eq 'ok') {
                   1119:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1120:         if ($type eq 'thumbnail') {
                   1121:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1122:         }
                   1123:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1124:         return $tokenurl;
                   1125:     } else {
                   1126:         if ($type eq 'thumbnail') {
                   1127:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1128:         } else { 
                   1129:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1130:         }
1.617     albertel 1131:     }
                   1132: }
                   1133: 
1.263     www      1134: # -------------------------------------------------------------------- New chat
                   1135: 
                   1136: sub chatsend {
1.724     raeburn  1137:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1138:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1139:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1140:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1141:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1142: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1143: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1144: }
                   1145: 
                   1146: # ------------------------------------------ Find current version of a resource
                   1147: 
                   1148: sub getversion {
                   1149:     my $fname=&clutter(shift);
                   1150:     unless ($fname=~/^\/res\//) { return -1; }
                   1151:     return &currentversion(&filelocation('',$fname));
                   1152: }
                   1153: 
                   1154: sub currentversion {
                   1155:     my $fname=shift;
1.599     albertel 1156:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1157:     if (defined($cached)) { return $result; }
1.292     www      1158:     my $author=$fname;
                   1159:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1160:     my ($udom,$uname)=split(/\//,$author);
                   1161:     my $home=homeserver($uname,$udom);
                   1162:     if ($home eq 'no_host') { 
                   1163:         return -1; 
                   1164:     }
                   1165:     my $answer=reply("currentversion:$fname",$home);
                   1166:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1167: 	return -1;
                   1168:     }
1.599     albertel 1169:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1170: }
                   1171: 
1.1       albertel 1172: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1173: 
1.1       albertel 1174: sub subscribe {
                   1175:     my $fname=shift;
1.761     raeburn  1176:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1177:     $fname=~s/[\n\r]//g;
1.1       albertel 1178:     my $author=$fname;
                   1179:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1180:     my ($udom,$uname)=split(/\//,$author);
                   1181:     my $home=homeserver($uname,$udom);
1.335     albertel 1182:     if ($home eq 'no_host') {
                   1183:         return 'not_found';
1.1       albertel 1184:     }
                   1185:     my $answer=reply("sub:$fname",$home);
1.64      www      1186:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1187: 	$answer.=' by '.$home;
                   1188:     }
1.1       albertel 1189:     return $answer;
                   1190: }
                   1191:     
1.8       www      1192: # -------------------------------------------------------------- Replicate file
                   1193: 
                   1194: sub repcopy {
                   1195:     my $filename=shift;
1.23      www      1196:     $filename=~s/\/+/\//g;
1.607     raeburn  1197:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1198:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1199:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1200: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1201: 	return &repcopy_userfile($filename);
                   1202:     }
1.532     albertel 1203:     $filename=~s/[\n\r]//g;
1.8       www      1204:     my $transname="$filename.in.transfer";
1.607     raeburn  1205:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1206:     my $remoteurl=subscribe($filename);
1.64      www      1207:     if ($remoteurl =~ /^con_lost by/) {
                   1208: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1209:            return 'unavailable';
1.8       www      1210:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1211: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1212: 	   return 'not_found';
1.64      www      1213:     } elsif ($remoteurl =~ /^rejected by/) {
                   1214: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1215:            return 'forbidden';
1.20      www      1216:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1217:            return 'ok';
1.8       www      1218:     } else {
1.290     www      1219:         my $author=$filename;
                   1220:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1221:         my ($udom,$uname)=split(/\//,$author);
                   1222:         my $home=homeserver($uname,$udom);
                   1223:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1224:            my @parts=split(/\//,$filename);
                   1225:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1226:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1227:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1228: 	       return 'bad_request';
1.8       www      1229:            }
                   1230:            my $count;
                   1231:            for ($count=5;$count<$#parts;$count++) {
                   1232:                $path.="/$parts[$count]";
                   1233:                if ((-e $path)!=1) {
                   1234: 		   mkdir($path,0777);
                   1235:                }
                   1236:            }
                   1237:            my $ua=new LWP::UserAgent;
                   1238:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1239:            my $response=$ua->request($request,$transname);
                   1240:            if ($response->is_error()) {
                   1241: 	       unlink($transname);
                   1242:                my $message=$response->status_line;
1.672     albertel 1243:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      1244:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1245:                return 'unavailable';
1.8       www      1246:            } else {
1.16      www      1247: 	       if ($remoteurl!~/\.meta$/) {
                   1248:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1249:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1250:                   if ($mresponse->is_error()) {
                   1251: 		      unlink($filename.'.meta');
                   1252:                       &logthis(
1.672     albertel 1253:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      1254:                   }
                   1255: 	       }
1.8       www      1256:                rename($transname,$filename);
1.607     raeburn  1257:                return 'ok';
1.8       www      1258:            }
1.290     www      1259:        }
1.8       www      1260:     }
1.330     www      1261: }
                   1262: 
                   1263: # ------------------------------------------------ Get server side include body
                   1264: sub ssi_body {
1.381     albertel 1265:     my ($filelink,%form)=@_;
1.606     matthew  1266:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1267:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1268:     }
1.330     www      1269:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
1.381     albertel 1270:                                      &ssi($filelink,%form));
1.778     albertel 1271:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1272:     $output=~s/^.*?\<body[^\>]*\>//si;
                   1273:     $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
1.330     www      1274:     return $output;
1.8       www      1275: }
                   1276: 
1.15      www      1277: # --------------------------------------------------------- Server Side Include
                   1278: 
1.782     albertel 1279: sub absolute_url {
                   1280:     my ($host_name) = @_;
                   1281:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   1282:     if ($host_name eq '') {
                   1283: 	$host_name = $ENV{'SERVER_NAME'};
                   1284:     }
                   1285:     return $protocol.$host_name;
                   1286: }
                   1287: 
1.15      www      1288: sub ssi {
                   1289: 
1.23      www      1290:     my ($fn,%form)=@_;
1.15      www      1291: 
                   1292:     my $ua=new LWP::UserAgent;
1.23      www      1293:     
                   1294:     my $request;
1.711     albertel 1295: 
                   1296:     $form{'no_update_last_known'}=1;
                   1297: 
1.23      www      1298:     if (%form) {
1.782     albertel 1299:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.201     albertel 1300:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www      1301:     } else {
1.782     albertel 1302:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      1303:     }
                   1304: 
1.15      www      1305:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1306:     my $response=$ua->request($request);
                   1307: 
1.324     www      1308:     return $response->content;
                   1309: }
                   1310: 
                   1311: sub externalssi {
                   1312:     my ($url)=@_;
                   1313:     my $ua=new LWP::UserAgent;
                   1314:     my $request=new HTTP::Request('GET',$url);
                   1315:     my $response=$ua->request($request);
1.15      www      1316:     return $response->content;
                   1317: }
1.254     www      1318: 
1.492     albertel 1319: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1320: 
                   1321: sub allowuploaded {
                   1322:     my ($srcurl,$url)=@_;
                   1323:     $url=&clutter(&declutter($url));
                   1324:     my $dir=$url;
                   1325:     $dir=~s/\/[^\/]+$//;
                   1326:     my %httpref=();
                   1327:     my $httpurl=&hreflocation('',$url);
                   1328:     $httpref{'httpref.'.$httpurl}=$srcurl;
                   1329:     &Apache::lonnet::appenv(%httpref);
1.254     www      1330: }
1.477     raeburn  1331: 
1.478     albertel 1332: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 1333: # input: action, courseID, current domain, intended
1.637     raeburn  1334: #        path to file, source of file, instruction to parse file for objects,
                   1335: #        ref to hash for embedded objects,
                   1336: #        ref to hash for codebase of java objects.
                   1337: #
1.485     raeburn  1338: # output: url to file (if action was uploaddoc), 
                   1339: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  1340: #
1.478     albertel 1341: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   1342: # course.
1.477     raeburn  1343: #
1.478     albertel 1344: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1345: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   1346: #          course's home server.
1.477     raeburn  1347: #
1.478     albertel 1348: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   1349: #          be copied from $source (current location) to 
                   1350: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1351: #         and will then be copied to
                   1352: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   1353: #         course's home server.
1.485     raeburn  1354: #
1.481     raeburn  1355: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 1356: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  1357: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1358: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   1359: #         in course's home server.
1.637     raeburn  1360: #
1.477     raeburn  1361: 
                   1362: sub process_coursefile {
1.638     albertel 1363:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  1364:     my $fetchresult;
1.638     albertel 1365:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  1366:     if ($action eq 'propagate') {
1.638     albertel 1367:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1368: 			     $home);
1.481     raeburn  1369:     } else {
1.477     raeburn  1370:         my $fpath = '';
                   1371:         my $fname = $file;
1.478     albertel 1372:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  1373:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  1374:         my $filepath = &build_filepath($fpath);
1.481     raeburn  1375:         if ($action eq 'copy') {
                   1376:             if ($source eq '') {
                   1377:                 $fetchresult = 'no source file';
                   1378:                 return $fetchresult;
                   1379:             } else {
                   1380:                 my $destination = $filepath.'/'.$fname;
                   1381:                 rename($source,$destination);
                   1382:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1383:                                  $home);
1.481     raeburn  1384:             }
                   1385:         } elsif ($action eq 'uploaddoc') {
                   1386:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 1387:             print $fh $env{'form.'.$source};
1.481     raeburn  1388:             close($fh);
1.637     raeburn  1389:             if ($parser eq 'parse') {
                   1390:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
                   1391:                 unless ($parse_result eq 'ok') {
                   1392:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   1393:                 }
                   1394:             }
1.477     raeburn  1395:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1396:                                  $home);
1.481     raeburn  1397:             if ($fetchresult eq 'ok') {
                   1398:                 return '/uploaded/'.$fpath.'/'.$fname;
                   1399:             } else {
                   1400:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1401:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  1402:                 return '/adm/notfound.html';
                   1403:             }
1.477     raeburn  1404:         }
                   1405:     }
1.485     raeburn  1406:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  1407:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1408:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  1409:     }
                   1410:     return $fetchresult;
                   1411: }
                   1412: 
1.637     raeburn  1413: sub build_filepath {
                   1414:     my ($fpath) = @_;
                   1415:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   1416:     unless ($fpath eq '') {
                   1417:         my @parts=split('/',$fpath);
                   1418:         foreach my $part (@parts) {
                   1419:             $filepath.= '/'.$part;
                   1420:             if ((-e $filepath)!=1) {
                   1421:                 mkdir($filepath,0777);
                   1422:             }
                   1423:         }
                   1424:     }
                   1425:     return $filepath;
                   1426: }
                   1427: 
                   1428: sub store_edited_file {
1.638     albertel 1429:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  1430:     my $file = $primary_url;
                   1431:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   1432:     my $fpath = '';
                   1433:     my $fname = $file;
                   1434:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   1435:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   1436:     my $filepath = &build_filepath($fpath);
                   1437:     open(my $fh,'>'.$filepath.'/'.$fname);
                   1438:     print $fh $content;
                   1439:     close($fh);
1.638     albertel 1440:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  1441:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1442: 			  $home);
1.637     raeburn  1443:     if ($$fetchresult eq 'ok') {
                   1444:         return '/uploaded/'.$fpath.'/'.$fname;
                   1445:     } else {
1.638     albertel 1446:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   1447: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  1448:         return '/adm/notfound.html';
                   1449:     }
                   1450: }
                   1451: 
1.531     albertel 1452: sub clean_filename {
                   1453:     my ($fname)=@_;
1.315     www      1454: # Replace Windows backslashes by forward slashes
1.257     www      1455:     $fname=~s/\\/\//g;
1.315     www      1456: # Get rid of everything but the actual filename
1.257     www      1457:     $fname=~s/^.*\/([^\/]+)$/$1/;
1.315     www      1458: # Replace spaces by underscores
                   1459:     $fname=~s/\s+/\_/g;
                   1460: # Replace all other weird characters by nothing
1.317     www      1461:     $fname=~s/[^\w\.\-]//g;
1.540     albertel 1462: # Replace all .\d. sequences with _\d. so they no longer look like version
                   1463: # numbers
                   1464:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 1465:     return $fname;
                   1466: }
                   1467: 
1.608     albertel 1468: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 1469: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 1470: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 1471: #        $coursedoc - if true up to the current course
                   1472: #                     if false
                   1473: #        $subdir - directory in userfile to store the file into
                   1474: #        $parser, $allfiles, $codebase - unknown
                   1475: #
                   1476: # output: url of file in userspace, or error: <message> 
                   1477: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 1478: 
                   1479: 
1.531     albertel 1480: sub userfileupload {
1.719     banghart 1481:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,$destudom)=@_;
1.531     albertel 1482:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 1483:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 1484:     $fname=&clean_filename($fname);
1.315     www      1485: # See if there is anything left
1.257     www      1486:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 1487:     chop($env{'form.'.$formname});
1.523     raeburn  1488:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   1489:         my $now = time;
                   1490:         my $filepath = 'tmp/helprequests/'.$now;
                   1491:         my @parts=split(/\//,$filepath);
                   1492:         my $fullpath = $perlvar{'lonDaemons'};
                   1493:         for (my $i=0;$i<@parts;$i++) {
                   1494:             $fullpath .= '/'.$parts[$i];
                   1495:             if ((-e $fullpath)!=1) {
                   1496:                 mkdir($fullpath,0777);
                   1497:             }
                   1498:         }
                   1499:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 1500:         print $fh $env{'form.'.$formname};
1.523     raeburn  1501:         close($fh);
1.741     raeburn  1502:         return $fullpath.'/'.$fname;
                   1503:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   1504:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   1505:                        '_'.$env{'user.domain'}.'/pending';
                   1506:         my @parts=split(/\//,$filepath);
                   1507:         my $fullpath = $perlvar{'lonDaemons'};
                   1508:         for (my $i=0;$i<@parts;$i++) {
                   1509:             $fullpath .= '/'.$parts[$i];
                   1510:             if ((-e $fullpath)!=1) {
                   1511:                 mkdir($fullpath,0777);
                   1512:             }
                   1513:         }
                   1514:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   1515:         print $fh $env{'form.'.$formname};
                   1516:         close($fh);
                   1517:         return $fullpath.'/'.$fname;
1.523     raeburn  1518:     }
1.719     banghart 1519:     
1.258     www      1520: # Create the directory if not present
1.493     albertel 1521:     $fname="$subdir/$fname";
1.259     www      1522:     if ($coursedoc) {
1.638     albertel 1523: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1524: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  1525:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 1526:             return &finishuserfileupload($docuname,$docudom,
                   1527: 					 $formname,$fname,$parser,$allfiles,
                   1528: 					 $codebase);
1.481     raeburn  1529:         } else {
1.620     albertel 1530:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 1531:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   1532: 				       $fname,$formname,$parser,
                   1533: 				       $allfiles,$codebase);
1.481     raeburn  1534:         }
1.719     banghart 1535:     } elsif (defined($destuname)) {
                   1536:         my $docuname=$destuname;
                   1537:         my $docudom=$destudom;
                   1538: 	return &finishuserfileupload($docuname,$docudom,$formname,
                   1539: 				     $fname,$parser,$allfiles,$codebase);
                   1540:         
1.259     www      1541:     } else {
1.638     albertel 1542:         my $docuname=$env{'user.name'};
                   1543:         my $docudom=$env{'user.domain'};
1.714     raeburn  1544:         if (exists($env{'form.group'})) {
                   1545:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1546:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1547:         }
1.638     albertel 1548: 	return &finishuserfileupload($docuname,$docudom,$formname,
                   1549: 				     $fname,$parser,$allfiles,$codebase);
1.259     www      1550:     }
1.271     www      1551: }
                   1552: 
                   1553: sub finishuserfileupload {
1.638     albertel 1554:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase) = @_;
1.477     raeburn  1555:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      1556:     my $filepath=$perlvar{'lonDocRoot'};
1.494     albertel 1557:     my ($fnamepath,$file);
                   1558:     $file=$fname;
                   1559:     if ($fname=~m|/|) {
                   1560:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   1561: 	$path.=$fnamepath.'/';
                   1562:     }
1.259     www      1563:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      1564:     my $count;
                   1565:     for ($count=4;$count<=$#parts;$count++) {
                   1566:         $filepath.="/$parts[$count]";
                   1567:         if ((-e $filepath)!=1) {
                   1568: 	    mkdir($filepath,0777);
                   1569:         }
                   1570:     }
                   1571: # Save the file
                   1572:     {
1.701     albertel 1573: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   1574: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   1575: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   1576: 	    return '/adm/notfound.html';
                   1577: 	}
                   1578: 	if (!print FH ($env{'form.'.$formname})) {
                   1579: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   1580: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   1581: 	    return '/adm/notfound.html';
                   1582: 	}
1.570     albertel 1583: 	close(FH);
1.258     www      1584:     }
1.637     raeburn  1585:     if ($parser eq 'parse') {
1.638     albertel 1586:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
                   1587: 						   $codebase);
1.637     raeburn  1588:         unless ($parse_result eq 'ok') {
1.638     albertel 1589:             &logthis('Failed to parse '.$filepath.$file.
                   1590: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  1591:         }
                   1592:     }
1.259     www      1593: # Notify homeserver to grep it
                   1594: #
1.638     albertel 1595:     my $docuhome=&homeserver($docuname,$docudom);
1.494     albertel 1596:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      1597:     if ($fetchresult eq 'ok') {
1.259     www      1598: #
1.258     www      1599: # Return the URL to it
1.494     albertel 1600:         return '/uploaded/'.$path.$file;
1.263     www      1601:     } else {
1.494     albertel 1602:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   1603: 		 ': '.$fetchresult);
1.263     www      1604:         return '/adm/notfound.html';
                   1605:     }    
1.493     albertel 1606: }
                   1607: 
1.637     raeburn  1608: sub extract_embedded_items {
1.648     raeburn  1609:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
1.637     raeburn  1610:     my @state = ();
                   1611:     my %javafiles = (
                   1612:                       codebase => '',
                   1613:                       code => '',
                   1614:                       archive => ''
                   1615:                     );
                   1616:     my %mediafiles = (
                   1617:                       src => '',
                   1618:                       movie => '',
                   1619:                      );
1.648     raeburn  1620:     my $p;
                   1621:     if ($content) {
                   1622:         $p = HTML::LCParser->new($content);
                   1623:     } else {
                   1624:         $p = HTML::LCParser->new($filepath.'/'.$file);
                   1625:     }
1.641     albertel 1626:     while (my $t=$p->get_token()) {
1.640     albertel 1627: 	if ($t->[0] eq 'S') {
                   1628: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
                   1629: 	    push (@state, $tagname);
1.648     raeburn  1630:             if (lc($tagname) eq 'allow') {
                   1631:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   1632:             }
1.640     albertel 1633: 	    if (lc($tagname) eq 'img') {
                   1634: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   1635: 	    }
1.645     raeburn  1636:             if (lc($tagname) eq 'script') {
                   1637:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   1638:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   1639:                 } else {
                   1640:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   1641:                 }
                   1642:             }
                   1643:             if (lc($tagname) eq 'link') {
                   1644:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   1645:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   1646:                 }
                   1647:             }
1.640     albertel 1648: 	    if (lc($tagname) eq 'object' ||
                   1649: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   1650: 		foreach my $item (keys(%javafiles)) {
                   1651: 		    $javafiles{$item} = '';
                   1652: 		}
                   1653: 	    }
                   1654: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   1655: 		my $name = lc($attr->{'name'});
                   1656: 		foreach my $item (keys(%javafiles)) {
                   1657: 		    if ($name eq $item) {
                   1658: 			$javafiles{$item} = $attr->{'value'};
                   1659: 			last;
                   1660: 		    }
                   1661: 		}
                   1662: 		foreach my $item (keys(%mediafiles)) {
                   1663: 		    if ($name eq $item) {
                   1664: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   1665: 			last;
                   1666: 		    }
                   1667: 		}
                   1668: 	    }
                   1669: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   1670: 		foreach my $item (keys(%javafiles)) {
                   1671: 		    if ($attr->{$item}) {
                   1672: 			$javafiles{$item} = $attr->{$item};
                   1673: 			last;
                   1674: 		    }
                   1675: 		}
                   1676: 		foreach my $item (keys(%mediafiles)) {
                   1677: 		    if ($attr->{$item}) {
                   1678: 			&add_filetype($allfiles,$attr->{$item},$item);
                   1679: 			last;
                   1680: 		    }
                   1681: 		}
                   1682: 	    }
                   1683: 	} elsif ($t->[0] eq 'E') {
                   1684: 	    my ($tagname) = ($t->[1]);
                   1685: 	    if ($javafiles{'codebase'} ne '') {
                   1686: 		$javafiles{'codebase'} .= '/';
                   1687: 	    }  
                   1688: 	    if (lc($tagname) eq 'applet' ||
                   1689: 		lc($tagname) eq 'object' ||
                   1690: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   1691: 		) {
                   1692: 		foreach my $item (keys(%javafiles)) {
                   1693: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   1694: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   1695: 			&add_filetype($allfiles,$file,$item);
                   1696: 		    }
                   1697: 		}
                   1698: 	    } 
                   1699: 	    pop @state;
                   1700: 	}
                   1701:     }
1.637     raeburn  1702:     return 'ok';
                   1703: }
                   1704: 
1.639     albertel 1705: sub add_filetype {
                   1706:     my ($allfiles,$file,$type)=@_;
                   1707:     if (exists($allfiles->{$file})) {
                   1708: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   1709: 	    push(@{$allfiles->{$file}}, &escape($type));
                   1710: 	}
                   1711:     } else {
                   1712: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  1713:     }
                   1714: }
                   1715: 
1.493     albertel 1716: sub removeuploadedurl {
                   1717:     my ($url)=@_;
                   1718:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613     albertel 1719:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 1720: }
                   1721: 
                   1722: sub removeuserfile {
                   1723:     my ($docuname,$docudom,$fname)=@_;
                   1724:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  1725:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
                   1726:     if ($result eq 'ok') {
                   1727:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   1728:             my $metafile = $fname.'.meta';
                   1729:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 1730: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
                   1731:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  1732:             my $sqlresult = 
1.823     albertel 1733:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  1734:                                         'portfolio_metadata',$group,
                   1735:                                         'delete');
1.798     raeburn  1736:         }
                   1737:     }
                   1738:     return $result;
1.257     www      1739: }
1.15      www      1740: 
1.530     albertel 1741: sub mkdiruserfile {
                   1742:     my ($docuname,$docudom,$dir)=@_;
                   1743:     my $home=&homeserver($docuname,$docudom);
                   1744:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   1745: }
                   1746: 
1.531     albertel 1747: sub renameuserfile {
                   1748:     my ($docuname,$docudom,$old,$new)=@_;
                   1749:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  1750:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   1751:                         &escape("$old").':'.&escape("$new"),$home);
                   1752:     if ($result eq 'ok') {
                   1753:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   1754:             my $oldmeta = $old.'.meta';
                   1755:             my $newmeta = $new.'.meta';
                   1756:             my $metaresult = 
                   1757:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 1758: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   1759:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  1760:             my $sqlresult = 
1.823     albertel 1761:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  1762:                                         'portfolio_metadata',$group,
                   1763:                                         'delete');
1.798     raeburn  1764:         }
                   1765:     }
                   1766:     return $result;
1.531     albertel 1767: }
                   1768: 
1.14      www      1769: # ------------------------------------------------------------------------- Log
                   1770: 
                   1771: sub log {
                   1772:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      1773:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      1774: }
                   1775: 
                   1776: # ------------------------------------------------------------------ Course Log
1.352     www      1777: #
                   1778: # This routine flushes several buffers of non-mission-critical nature
                   1779: #
1.157     www      1780: 
                   1781: sub flushcourselogs {
1.352     www      1782:     &logthis('Flushing log buffers');
                   1783: #
                   1784: # course logs
                   1785: # This is a log of all transactions in a course, which can be used
                   1786: # for data mining purposes
                   1787: #
                   1788: # It also collects the courseid database, which lists last transaction
                   1789: # times and course titles for all courseids
                   1790: #
                   1791:     my %courseidbuffer=();
1.800     albertel 1792:     foreach my $crsid (keys %courselogs) {
1.352     www      1793:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      1794: 		          &escape($courselogs{$crsid}),
                   1795: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      1796: 	    delete $courselogs{$crsid};
                   1797:         } else {
                   1798:             &logthis('Failed to flush log buffer for '.$crsid);
                   1799:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 1800:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      1801:                         " exceeded maximum size, deleting.</font>");
                   1802:                delete $courselogs{$crsid};
                   1803:             }
1.352     www      1804:         }
                   1805:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
                   1806:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
1.516     raeburn  1807: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  1808:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.352     www      1809:         } else {
                   1810:            $courseidbuffer{$coursehombuf{$crsid}}=
1.516     raeburn  1811: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  1812:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.571     raeburn  1813:         }
1.191     harris41 1814:     }
1.352     www      1815: #
                   1816: # Write course id database (reverse lookup) to homeserver of courses 
                   1817: # Is used in pickcourse
                   1818: #
1.800     albertel 1819:     foreach my $crsid (keys(%courseidbuffer)) {
                   1820:         &courseidput($hostdom{$crsid},$courseidbuffer{$crsid},$crsid);
1.352     www      1821:     }
                   1822: #
                   1823: # File accesses
                   1824: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   1825: #
1.449     matthew  1826:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  1827:         if ($entry =~ /___count$/) {
                   1828:             my ($dom,$name);
1.807     albertel 1829:             ($dom,$name,undef)=
1.811     albertel 1830: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  1831:             if (! defined($dom) || $dom eq '' || 
                   1832:                 ! defined($name) || $name eq '') {
1.620     albertel 1833:                 my $cid = $env{'request.course.id'};
                   1834:                 $dom  = $env{'request.'.$cid.'.domain'};
                   1835:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  1836:             }
1.450     matthew  1837:             my $value = $accesshash{$entry};
                   1838:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   1839:             my %temphash=($url => $value);
1.449     matthew  1840:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   1841:             if ($result eq 'ok') {
                   1842:                 delete $accesshash{$entry};
                   1843:             } elsif ($result eq 'unknown_cmd') {
                   1844:                 # Target server has old code running on it.
1.450     matthew  1845:                 my %temphash=($entry => $value);
1.449     matthew  1846:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1847:                     delete $accesshash{$entry};
                   1848:                 }
                   1849:             }
                   1850:         } else {
1.811     albertel 1851:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  1852:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  1853:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1854:                 delete $accesshash{$entry};
                   1855:             }
1.185     www      1856:         }
1.191     harris41 1857:     }
1.352     www      1858: #
                   1859: # Roles
                   1860: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   1861: #
1.800     albertel 1862:     foreach my $entry (keys(%userrolehash)) {
1.351     www      1863:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      1864: 	    split(/\:/,$entry);
                   1865:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      1866:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      1867:                 $rudom,$runame) eq 'ok') {
                   1868: 	    delete $userrolehash{$entry};
                   1869:         }
                   1870:     }
1.662     raeburn  1871: #
                   1872: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   1873: #
                   1874:     my %domrolebuffer = ();
                   1875:     foreach my $entry (keys %domainrolehash) {
                   1876:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split/:/,$entry;
                   1877:         if ($domrolebuffer{$rudom}) {
                   1878:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   1879:                       '='.&escape($domainrolehash{$entry});
                   1880:         } else {
                   1881:             $domrolebuffer{$rudom}.=&escape($entry).
                   1882:                       '='.&escape($domainrolehash{$entry});
                   1883:         }
                   1884:         delete $domainrolehash{$entry};
                   1885:     }
                   1886:     foreach my $dom (keys(%domrolebuffer)) {
                   1887:         foreach my $tryserver (keys %libserv) {
                   1888:             if ($hostdom{$tryserver} eq $dom) {
                   1889:                 unless (&reply('domroleput:'.$dom.':'.
                   1890:                   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   1891:                     &logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   1892:                 }
                   1893:             }
                   1894:         }
                   1895:     }
1.186     www      1896:     $dumpcount++;
1.157     www      1897: }
                   1898: 
                   1899: sub courselog {
                   1900:     my $what=shift;
1.158     www      1901:     $what=time.':'.$what;
1.620     albertel 1902:     unless ($env{'request.course.id'}) { return ''; }
                   1903:     $coursedombuf{$env{'request.course.id'}}=
                   1904:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   1905:     $coursenumbuf{$env{'request.course.id'}}=
                   1906:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   1907:     $coursehombuf{$env{'request.course.id'}}=
                   1908:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   1909:     $coursedescrbuf{$env{'request.course.id'}}=
                   1910:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   1911:     $courseinstcodebuf{$env{'request.course.id'}}=
                   1912:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   1913:     $courseownerbuf{$env{'request.course.id'}}=
                   1914:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  1915:     $coursetypebuf{$env{'request.course.id'}}=
                   1916:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 1917:     if (defined $courselogs{$env{'request.course.id'}}) {
                   1918: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      1919:     } else {
1.620     albertel 1920: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      1921:     }
1.620     albertel 1922:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      1923: 	&flushcourselogs();
                   1924:     }
1.158     www      1925: }
                   1926: 
                   1927: sub courseacclog {
                   1928:     my $fnsymb=shift;
1.620     albertel 1929:     unless ($env{'request.course.id'}) { return ''; }
                   1930:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 1931:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      1932:         $what.=':POST';
1.583     matthew  1933:         # FIXME: Probably ought to escape things....
1.800     albertel 1934: 	foreach my $key (keys(%env)) {
                   1935:             if ($key=~/^form\.(.*)/) {
                   1936: 		$what.=':'.$1.'='.$env{$key};
1.158     www      1937:             }
1.191     harris41 1938:         }
1.583     matthew  1939:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   1940:         # FIXME: We should not be depending on a form parameter that someone
                   1941:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 1942:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  1943:             $what.= ':POST';
                   1944:             # FIXME: Probably ought to escape things....
                   1945:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   1946:                                  'crsdiscuss') {
1.620     albertel 1947:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  1948:             }
                   1949:         }
1.158     www      1950:     }
                   1951:     &courselog($what);
1.149     www      1952: }
                   1953: 
1.185     www      1954: sub countacc {
                   1955:     my $url=&declutter(shift);
1.458     matthew  1956:     return if (! defined($url) || $url eq '');
1.620     albertel 1957:     unless ($env{'request.course.id'}) { return ''; }
                   1958:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      1959:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  1960:     $accesshash{$key}++;
1.185     www      1961: }
1.349     www      1962: 
1.361     www      1963: sub linklog {
                   1964:     my ($from,$to)=@_;
                   1965:     $from=&declutter($from);
                   1966:     $to=&declutter($to);
                   1967:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   1968:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   1969: }
                   1970:   
1.349     www      1971: sub userrolelog {
                   1972:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  1973:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  1974:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  1975:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   1976:         ($trole=~/^ta/)) {
1.350     www      1977:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   1978:        $userrolehash
                   1979:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      1980:                     =$tend.':'.$tstart;
1.662     raeburn  1981:     }
                   1982:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   1983:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   1984:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   1985:         ($trole=~/^sc/)) {
                   1986:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   1987:        $domainrolehash
                   1988:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   1989:                     = $tend.':'.$tstart;
                   1990:     }
1.351     www      1991: }
                   1992: 
                   1993: sub get_course_adv_roles {
                   1994:     my $cid=shift;
1.620     albertel 1995:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      1996:     my %coursehash=&coursedescription($cid);
1.470     www      1997:     my %nothide=();
1.800     albertel 1998:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   1999: 	$nothide{join(':',split(/[\@\:]/,$user))}=1;
1.470     www      2000:     }
1.351     www      2001:     my %returnhash=();
                   2002:     my %dumphash=
                   2003:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   2004:     my $now=time;
1.800     albertel 2005:     foreach my $entry (keys %dumphash) {
                   2006: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      2007:         if (($tstart) && ($tstart<0)) { next; }
                   2008:         if (($tend) && ($tend<$now)) { next; }
                   2009:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 2010:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 2011: 	if ($username eq '' || $domain eq '') { next; }
1.470     www      2012: 	if ((&privileged($username,$domain)) && 
                   2013: 	    (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 2014: 	if ($role eq 'cr') { next; }
1.351     www      2015:         my $key=&plaintext($role);
                   2016:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
                   2017:         if ($returnhash{$key}) {
                   2018: 	    $returnhash{$key}.=','.$username.':'.$domain;
                   2019:         } else {
                   2020:             $returnhash{$key}=$username.':'.$domain;
                   2021:         }
1.400     www      2022:      }
                   2023:     return %returnhash;
                   2024: }
                   2025: 
                   2026: sub get_my_roles {
                   2027:     my ($uname,$udom)=@_;
1.620     albertel 2028:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   2029:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.400     www      2030:     my %dumphash=
                   2031:             &dump('nohist_userroles',$udom,$uname);
                   2032:     my %returnhash=();
                   2033:     my $now=time;
1.800     albertel 2034:     foreach my $entry (keys(%dumphash)) {
                   2035: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.400     www      2036:         if (($tstart) && ($tstart<0)) { next; }
                   2037:         if (($tend) && ($tend<$now)) { next; }
                   2038:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 2039:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.400     www      2040: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
1.373     www      2041:      }
                   2042:     return %returnhash;
1.399     www      2043: }
                   2044: 
                   2045: # ----------------------------------------------------- Frontpage Announcements
                   2046: #
                   2047: #
                   2048: 
                   2049: sub postannounce {
                   2050:     my ($server,$text)=@_;
                   2051:     unless (&allowed('psa',$hostdom{$server})) { return 'refused'; }
                   2052:     unless ($text=~/\w/) { $text=''; }
                   2053:     return &reply('setannounce:'.&escape($text),$server);
                   2054: }
                   2055: 
                   2056: sub getannounce {
1.448     albertel 2057: 
                   2058:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      2059: 	my $announcement='';
1.800     albertel 2060: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 2061: 	close($fh);
1.399     www      2062: 	if ($announcement=~/\w/) { 
                   2063: 	    return 
                   2064:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 2065:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      2066: 	} else {
                   2067: 	    return '';
                   2068: 	}
                   2069:     } else {
                   2070: 	return '';
                   2071:     }
1.351     www      2072: }
1.353     www      2073: 
                   2074: # ---------------------------------------------------------- Course ID routines
                   2075: # Deal with domain's nohist_courseid.db files
                   2076: #
                   2077: 
                   2078: sub courseidput {
                   2079:     my ($domain,$what,$coursehome)=@_;
                   2080:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   2081: }
                   2082: 
                   2083: sub courseiddump {
1.791     raeburn  2084:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok)=@_;
1.353     www      2085:     my %returnhash=();
1.355     www      2086:     unless ($domfilter) { $domfilter=''; }
1.353     www      2087:     foreach my $tryserver (keys %libserv) {
1.511     raeburn  2088:         if ( ($hostidflag == 1 && grep/^$tryserver$/,@{$hostidref}) || (!defined($hostidflag)) ) {
1.506     raeburn  2089: 	    if ((!$domfilter) || ($hostdom{$tryserver} eq $domfilter)) {
1.800     albertel 2090: 	        foreach my $line (
1.506     raeburn  2091:                  split(/\&/,&reply('courseiddump:'.$hostdom{$tryserver}.':'.
1.571     raeburn  2092: 			       $sincefilter.':'.&escape($descfilter).':'.
1.791     raeburn  2093:                                &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter).':'.&escape($typefilter).':'.&escape($regexp_ok),
1.354     www      2094:                                $tryserver))) {
1.800     albertel 2095: 		    my ($key,$value)=split(/\=/,$line,2);
1.506     raeburn  2096:                     if (($key) && ($value)) {
1.516     raeburn  2097: 		        $returnhash{&unescape($key)}=$value;
1.506     raeburn  2098:                     }
1.353     www      2099:                 }
                   2100:             }
                   2101:         }
                   2102:     }
                   2103:     return %returnhash;
                   2104: }
                   2105: 
1.658     raeburn  2106: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  2107: 
                   2108: sub dcmailput {
1.685     raeburn  2109:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  2110:     my $status = &Apache::lonnet::critical(
1.740     www      2111:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   2112:        &escape($message),$server);
1.662     raeburn  2113:     return $status;
                   2114: }
                   2115: 
1.658     raeburn  2116: sub dcmaildump {
                   2117:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  2118:     my %returnhash=();
                   2119:     if (exists($domain_primary{$dom})) {
                   2120:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   2121:                                                          &escape($enddate).':';
                   2122: 	my @esc_senders=map { &escape($_)} @$senders;
                   2123: 	$cmd.=&escape(join('&',@esc_senders));
1.800     albertel 2124: 	foreach my $line (split(/\&/,&reply($cmd,$domain_primary{$dom}))) {
                   2125:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  2126:             if (($key) && ($value)) {
                   2127:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  2128:             }
                   2129:         }
                   2130:     }
                   2131:     return %returnhash;
                   2132: }
1.662     raeburn  2133: # ---------------------------------------------------------- Domain roles
                   2134: 
                   2135: sub get_domain_roles {
                   2136:     my ($dom,$roles,$startdate,$enddate)=@_;
                   2137:     if (undef($startdate) || $startdate eq '') {
                   2138:         $startdate = '.';
                   2139:     }
                   2140:     if (undef($enddate) || $enddate eq '') {
                   2141:         $enddate = '.';
                   2142:     }
                   2143:     my $rolelist = join(':',@{$roles});
                   2144:     my %personnel = ();
                   2145:     foreach my $tryserver (keys(%libserv)) {
                   2146:         if ($hostdom{$tryserver} eq $dom) {
                   2147:             %{$personnel{$tryserver}}=();
1.800     albertel 2148:             foreach my $line (
1.662     raeburn  2149:                 split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   2150:                    &escape($startdate).':'.&escape($enddate).':'.
                   2151:                    &escape($rolelist), $tryserver))) {
1.800     albertel 2152:                 my ($key,$value) = split(/\=/,$line,2);
1.662     raeburn  2153:                 if (($key) && ($value)) {
                   2154:                     $personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   2155:                 }
                   2156:             }
                   2157:         }
                   2158:     }
                   2159:     return %personnel;
                   2160: }
1.658     raeburn  2161: 
1.149     www      2162: # ----------------------------------------------------------- Check out an item
                   2163: 
1.504     albertel 2164: sub get_first_access {
                   2165:     my ($type,$argsymb)=@_;
1.790     albertel 2166:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2167:     if ($argsymb) { $symb=$argsymb; }
                   2168:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2169:     if ($type eq 'map') {
                   2170: 	$res=&symbread($map);
                   2171:     } else {
                   2172: 	$res=$symb;
                   2173:     }
                   2174:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   2175:     return $times{"$courseid\0$res"};
1.504     albertel 2176: }
                   2177: 
                   2178: sub set_first_access {
                   2179:     my ($type)=@_;
1.790     albertel 2180:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2181:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2182:     if ($type eq 'map') {
                   2183: 	$res=&symbread($map);
                   2184:     } else {
                   2185: 	$res=$symb;
                   2186:     }
                   2187:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 2188:     if (!$firstaccess) {
1.588     albertel 2189: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 2190:     }
                   2191:     return 'already_set';
1.504     albertel 2192: }
                   2193: 
1.149     www      2194: sub checkout {
                   2195:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   2196:     my $now=time;
                   2197:     my $lonhost=$perlvar{'lonHostID'};
                   2198:     my $infostr=&escape(
1.234     www      2199:                  'CHECKOUTTOKEN&'.
1.149     www      2200:                  $tuname.'&'.
                   2201:                  $tudom.'&'.
                   2202:                  $tcrsid.'&'.
                   2203:                  $symb.'&'.
                   2204: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   2205:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      2206:     if ($token=~/^error\:/) { 
1.672     albertel 2207:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2208:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2209:                  "</font>");
                   2210:         return ''; 
                   2211:     }
                   2212: 
1.149     www      2213:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   2214:     $token=~tr/a-z/A-Z/;
                   2215: 
1.153     www      2216:     my %infohash=('resource.0.outtoken' => $token,
                   2217:                   'resource.0.checkouttime' => $now,
                   2218:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      2219: 
                   2220:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2221:        return '';
1.151     www      2222:     } else {
1.672     albertel 2223:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2224:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2225:                  "</font>");
1.149     www      2226:     }    
                   2227: 
                   2228:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2229:                          &escape('Checkout '.$infostr.' - '.
                   2230:                                                  $token)) ne 'ok') {
                   2231: 	return '';
1.151     www      2232:     } else {
1.672     albertel 2233:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2234:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2235:                  "</font>");
1.149     www      2236:     }
1.151     www      2237:     return $token;
1.149     www      2238: }
                   2239: 
                   2240: # ------------------------------------------------------------ Check in an item
                   2241: 
                   2242: sub checkin {
                   2243:     my $token=shift;
1.150     www      2244:     my $now=time;
                   2245:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   2246:     $lonhost=~tr/A-Z/a-z/;
1.595     albertel 2247:     my $dtoken=$ta.'_'.$hostname{$lonhost}.'_'.$tb;
1.150     www      2248:     $dtoken=~s/\W/\_/g;
1.234     www      2249:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      2250:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   2251: 
1.154     www      2252:     unless (($tuname) && ($tudom)) {
                   2253:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   2254:         return '';
                   2255:     }
                   2256:     
                   2257:     unless (&allowed('mgr',$tcrsid)) {
                   2258:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 2259:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      2260:         return '';
                   2261:     }
                   2262: 
1.153     www      2263:     my %infohash=('resource.0.intoken' => $token,
                   2264:                   'resource.0.checkintime' => $now,
                   2265:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      2266: 
                   2267:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2268:        return '';
                   2269:     }    
                   2270: 
                   2271:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2272:                          &escape('Checkin - '.$token)) ne 'ok') {
                   2273: 	return '';
                   2274:     }
                   2275: 
                   2276:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      2277: }
                   2278: 
                   2279: # --------------------------------------------- Set Expire Date for Spreadsheet
                   2280: 
                   2281: sub expirespread {
                   2282:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 2283:     my $cid=$env{'request.course.id'}; 
1.110     www      2284:     if ($cid) {
                   2285:        my $now=time;
                   2286:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 2287:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   2288:                             $env{'course.'.$cid.'.num'}.
1.110     www      2289: 	        	    ':nohist_expirationdates:'.
                   2290:                             &escape($key).'='.$now,
1.620     albertel 2291:                             $env{'course.'.$cid.'.home'})
1.110     www      2292:     }
                   2293:     return 'ok';
1.14      www      2294: }
                   2295: 
1.109     www      2296: # ----------------------------------------------------- Devalidate Spreadsheets
                   2297: 
                   2298: sub devalidate {
1.325     www      2299:     my ($symb,$uname,$udom)=@_;
1.620     albertel 2300:     my $cid=$env{'request.course.id'}; 
1.109     www      2301:     if ($cid) {
1.391     matthew  2302:         # delete the stored spreadsheets for
                   2303:         # - the student level sheet of this user in course's homespace
                   2304:         # - the assessment level sheet for this resource 
                   2305:         #   for this user in user's homespace
1.553     albertel 2306: 	# - current conditional state info
1.325     www      2307: 	my $key=$uname.':'.$udom.':';
1.109     www      2308:         my $status=
1.299     matthew  2309: 	    &del('nohist_calculatedsheets',
1.391     matthew  2310: 		 [$key.'studentcalc:'],
1.620     albertel 2311: 		 $env{'course.'.$cid.'.domain'},
                   2312: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 2313: 		.' '.
                   2314: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  2315: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      2316:         unless ($status eq 'ok ok') {
                   2317:            &logthis('Could not devalidate spreadsheet '.
1.325     www      2318:                     $uname.' at '.$udom.' for '.
1.109     www      2319: 		    $symb.': '.$status);
1.133     albertel 2320:         }
1.553     albertel 2321: 	&delenv('user.state.'.$cid);
1.109     www      2322:     }
                   2323: }
                   2324: 
1.265     albertel 2325: sub get_scalar {
                   2326:     my ($string,$end) = @_;
                   2327:     my $value;
                   2328:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   2329: 	$value = $1;
                   2330:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   2331: 	$value = $1;
                   2332:     }
                   2333:     return &unescape($value);
                   2334: }
                   2335: 
                   2336: sub array2str {
                   2337:   my (@array) = @_;
                   2338:   my $result=&arrayref2str(\@array);
                   2339:   $result=~s/^__ARRAY_REF__//;
                   2340:   $result=~s/__END_ARRAY_REF__$//;
                   2341:   return $result;
                   2342: }
                   2343: 
1.204     albertel 2344: sub arrayref2str {
                   2345:   my ($arrayref) = @_;
1.265     albertel 2346:   my $result='__ARRAY_REF__';
1.204     albertel 2347:   foreach my $elem (@$arrayref) {
1.265     albertel 2348:     if(ref($elem) eq 'ARRAY') {
                   2349:       $result.=&arrayref2str($elem).'&';
                   2350:     } elsif(ref($elem) eq 'HASH') {
                   2351:       $result.=&hashref2str($elem).'&';
                   2352:     } elsif(ref($elem)) {
                   2353:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 2354:     } else {
                   2355:       $result.=&escape($elem).'&';
                   2356:     }
                   2357:   }
                   2358:   $result=~s/\&$//;
1.265     albertel 2359:   $result .= '__END_ARRAY_REF__';
1.204     albertel 2360:   return $result;
                   2361: }
                   2362: 
1.168     albertel 2363: sub hash2str {
1.204     albertel 2364:   my (%hash) = @_;
                   2365:   my $result=&hashref2str(\%hash);
1.265     albertel 2366:   $result=~s/^__HASH_REF__//;
                   2367:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 2368:   return $result;
                   2369: }
                   2370: 
                   2371: sub hashref2str {
                   2372:   my ($hashref)=@_;
1.265     albertel 2373:   my $result='__HASH_REF__';
1.800     albertel 2374:   foreach my $key (sort(keys(%$hashref))) {
                   2375:     if (ref($key) eq 'ARRAY') {
                   2376:       $result.=&arrayref2str($key).'=';
                   2377:     } elsif (ref($key) eq 'HASH') {
                   2378:       $result.=&hashref2str($key).'=';
                   2379:     } elsif (ref($key)) {
1.265     albertel 2380:       $result.='=';
1.800     albertel 2381:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 2382:     } else {
1.800     albertel 2383: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 2384:     }
                   2385: 
1.800     albertel 2386:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   2387:       $result.=&arrayref2str($hashref->{$key}).'&';
                   2388:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   2389:       $result.=&hashref2str($hashref->{$key}).'&';
                   2390:     } elsif(ref($hashref->{$key})) {
1.265     albertel 2391:        $result.='&';
1.800     albertel 2392:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 2393:     } else {
1.800     albertel 2394:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 2395:     }
                   2396:   }
1.168     albertel 2397:   $result=~s/\&$//;
1.265     albertel 2398:   $result .= '__END_HASH_REF__';
1.168     albertel 2399:   return $result;
                   2400: }
                   2401: 
                   2402: sub str2hash {
1.265     albertel 2403:     my ($string)=@_;
                   2404:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   2405:     return %$hash;
                   2406: }
                   2407: 
                   2408: sub str2hashref {
1.168     albertel 2409:   my ($string) = @_;
1.265     albertel 2410: 
                   2411:   my %hash;
                   2412: 
                   2413:   if($string !~ /^__HASH_REF__/) {
                   2414:       if (! ($string eq '' || !defined($string))) {
                   2415: 	  $hash{'error'}='Not hash reference';
                   2416:       }
                   2417:       return (\%hash, $string);
                   2418:   }
                   2419: 
                   2420:   $string =~ s/^__HASH_REF__//;
                   2421: 
                   2422:   while($string !~ /^__END_HASH_REF__/) {
                   2423:       #key
                   2424:       my $key='';
                   2425:       if($string =~ /^__HASH_REF__/) {
                   2426:           ($key, $string)=&str2hashref($string);
                   2427:           if(defined($key->{'error'})) {
                   2428:               $hash{'error'}='Bad data';
                   2429:               return (\%hash, $string);
                   2430:           }
                   2431:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2432:           ($key, $string)=&str2arrayref($string);
                   2433:           if($key->[0] eq 'Array reference error') {
                   2434:               $hash{'error'}='Bad data';
                   2435:               return (\%hash, $string);
                   2436:           }
                   2437:       } else {
                   2438:           $string =~ s/^(.*?)=//;
1.267     albertel 2439: 	  $key=&unescape($1);
1.265     albertel 2440:       }
                   2441:       $string =~ s/^=//;
                   2442: 
                   2443:       #value
                   2444:       my $value='';
                   2445:       if($string =~ /^__HASH_REF__/) {
                   2446:           ($value, $string)=&str2hashref($string);
                   2447:           if(defined($value->{'error'})) {
                   2448:               $hash{'error'}='Bad data';
                   2449:               return (\%hash, $string);
                   2450:           }
                   2451:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2452:           ($value, $string)=&str2arrayref($string);
                   2453:           if($value->[0] eq 'Array reference error') {
                   2454:               $hash{'error'}='Bad data';
                   2455:               return (\%hash, $string);
                   2456:           }
                   2457:       } else {
                   2458: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   2459:       }
                   2460:       $string =~ s/^&//;
                   2461: 
                   2462:       $hash{$key}=$value;
1.204     albertel 2463:   }
1.265     albertel 2464: 
                   2465:   $string =~ s/^__END_HASH_REF__//;
                   2466: 
                   2467:   return (\%hash, $string);
1.204     albertel 2468: }
                   2469: 
                   2470: sub str2array {
1.265     albertel 2471:     my ($string)=@_;
                   2472:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   2473:     return @$array;
                   2474: }
                   2475: 
                   2476: sub str2arrayref {
1.204     albertel 2477:   my ($string) = @_;
1.265     albertel 2478:   my @array;
                   2479: 
                   2480:   if($string !~ /^__ARRAY_REF__/) {
                   2481:       if (! ($string eq '' || !defined($string))) {
                   2482: 	  $array[0]='Array reference error';
                   2483:       }
                   2484:       return (\@array, $string);
                   2485:   }
                   2486: 
                   2487:   $string =~ s/^__ARRAY_REF__//;
                   2488: 
                   2489:   while($string !~ /^__END_ARRAY_REF__/) {
                   2490:       my $value='';
                   2491:       if($string =~ /^__HASH_REF__/) {
                   2492:           ($value, $string)=&str2hashref($string);
                   2493:           if(defined($value->{'error'})) {
                   2494:               $array[0] ='Array reference error';
                   2495:               return (\@array, $string);
                   2496:           }
                   2497:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2498:           ($value, $string)=&str2arrayref($string);
                   2499:           if($value->[0] eq 'Array reference error') {
                   2500:               $array[0] ='Array reference error';
                   2501:               return (\@array, $string);
                   2502:           }
                   2503:       } else {
                   2504: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   2505:       }
                   2506:       $string =~ s/^&//;
                   2507: 
                   2508:       push(@array, $value);
1.191     harris41 2509:   }
1.265     albertel 2510: 
                   2511:   $string =~ s/^__END_ARRAY_REF__//;
                   2512: 
                   2513:   return (\@array, $string);
1.168     albertel 2514: }
                   2515: 
1.167     albertel 2516: # -------------------------------------------------------------------Temp Store
                   2517: 
1.168     albertel 2518: sub tmpreset {
                   2519:   my ($symb,$namespace,$domain,$stuname) = @_;
                   2520:   if (!$symb) {
                   2521:     $symb=&symbread();
1.620     albertel 2522:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2523:   }
                   2524:   $symb=escape($symb);
                   2525: 
1.620     albertel 2526:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 2527:   $namespace=~s/\//\_/g;
                   2528:   $namespace=~s/\W//g;
                   2529: 
1.620     albertel 2530:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2531:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2532:   if ($domain eq 'public' && $stuname eq 'public') {
                   2533:       $stuname=$ENV{'REMOTE_ADDR'};
                   2534:   }
1.168     albertel 2535:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2536:   my %hash;
                   2537:   if (tie(%hash,'GDBM_File',
                   2538: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2539: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2540:     foreach my $key (keys %hash) {
1.180     albertel 2541:       if ($key=~ /:$symb/) {
1.168     albertel 2542: 	delete($hash{$key});
                   2543:       }
                   2544:     }
                   2545:   }
                   2546: }
                   2547: 
1.167     albertel 2548: sub tmpstore {
1.168     albertel 2549:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2550: 
                   2551:   if (!$symb) {
                   2552:     $symb=&symbread();
1.620     albertel 2553:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2554:   }
                   2555:   $symb=escape($symb);
                   2556: 
                   2557:   if (!$namespace) {
                   2558:     # I don't think we would ever want to store this for a course.
                   2559:     # it seems this will only be used if we don't have a course.
1.620     albertel 2560:     #$namespace=$env{'request.course.id'};
1.168     albertel 2561:     #if (!$namespace) {
1.620     albertel 2562:       $namespace=$env{'request.state'};
1.168     albertel 2563:     #}
                   2564:   }
                   2565:   $namespace=~s/\//\_/g;
                   2566:   $namespace=~s/\W//g;
1.620     albertel 2567:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2568:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2569:   if ($domain eq 'public' && $stuname eq 'public') {
                   2570:       $stuname=$ENV{'REMOTE_ADDR'};
                   2571:   }
1.168     albertel 2572:   my $now=time;
                   2573:   my %hash;
                   2574:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2575:   if (tie(%hash,'GDBM_File',
                   2576: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2577: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2578:     $hash{"version:$symb"}++;
                   2579:     my $version=$hash{"version:$symb"};
                   2580:     my $allkeys=''; 
                   2581:     foreach my $key (keys(%$storehash)) {
                   2582:       $allkeys.=$key.':';
1.591     albertel 2583:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 2584:     }
                   2585:     $hash{"$version:$symb:timestamp"}=$now;
                   2586:     $allkeys.='timestamp';
                   2587:     $hash{"$version:keys:$symb"}=$allkeys;
                   2588:     if (untie(%hash)) {
                   2589:       return 'ok';
                   2590:     } else {
                   2591:       return "error:$!";
                   2592:     }
                   2593:   } else {
                   2594:     return "error:$!";
                   2595:   }
                   2596: }
1.167     albertel 2597: 
1.168     albertel 2598: # -----------------------------------------------------------------Temp Restore
1.167     albertel 2599: 
1.168     albertel 2600: sub tmprestore {
                   2601:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 2602: 
1.168     albertel 2603:   if (!$symb) {
                   2604:     $symb=&symbread();
1.620     albertel 2605:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2606:   }
                   2607:   $symb=escape($symb);
                   2608: 
1.620     albertel 2609:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 2610: 
1.620     albertel 2611:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2612:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2613:   if ($domain eq 'public' && $stuname eq 'public') {
                   2614:       $stuname=$ENV{'REMOTE_ADDR'};
                   2615:   }
1.168     albertel 2616:   my %returnhash;
                   2617:   $namespace=~s/\//\_/g;
                   2618:   $namespace=~s/\W//g;
                   2619:   my %hash;
                   2620:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2621:   if (tie(%hash,'GDBM_File',
                   2622: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2623: 	  &GDBM_READER(),0640)) {
1.168     albertel 2624:     my $version=$hash{"version:$symb"};
                   2625:     $returnhash{'version'}=$version;
                   2626:     my $scope;
                   2627:     for ($scope=1;$scope<=$version;$scope++) {
                   2628:       my $vkeys=$hash{"$scope:keys:$symb"};
                   2629:       my @keys=split(/:/,$vkeys);
                   2630:       my $key;
                   2631:       $returnhash{"$scope:keys"}=$vkeys;
                   2632:       foreach $key (@keys) {
1.591     albertel 2633: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   2634: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 2635:       }
                   2636:     }
1.168     albertel 2637:     if (!(untie(%hash))) {
                   2638:       return "error:$!";
                   2639:     }
                   2640:   } else {
                   2641:     return "error:$!";
                   2642:   }
                   2643:   return %returnhash;
1.167     albertel 2644: }
                   2645: 
1.9       www      2646: # ----------------------------------------------------------------------- Store
                   2647: 
                   2648: sub store {
1.124     www      2649:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2650:     my $home='';
                   2651: 
1.168     albertel 2652:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2653: 
1.213     www      2654:     $symb=&symbclean($symb);
1.122     albertel 2655:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2656: 
1.620     albertel 2657:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2658:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2659: 
                   2660:     &devalidate($symb,$stuname,$domain);
1.109     www      2661: 
                   2662:     $symb=escape($symb);
1.187     www      2663:     if (!$namespace) { 
1.620     albertel 2664:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2665:           return ''; 
                   2666:        } 
                   2667:     }
1.620     albertel 2668:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2669: 
                   2670:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2671:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   2672: 
1.12      www      2673:     my $namevalue='';
1.800     albertel 2674:     foreach my $key (keys(%$storehash)) {
                   2675:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 2676:     }
1.12      www      2677:     $namevalue=~s/\&$//;
1.187     www      2678:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      2679:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      2680: }
                   2681: 
1.47      www      2682: # -------------------------------------------------------------- Critical Store
                   2683: 
                   2684: sub cstore {
1.124     www      2685:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2686:     my $home='';
                   2687: 
1.168     albertel 2688:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2689: 
1.213     www      2690:     $symb=&symbclean($symb);
1.122     albertel 2691:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2692: 
1.620     albertel 2693:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2694:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2695: 
                   2696:     &devalidate($symb,$stuname,$domain);
1.109     www      2697: 
                   2698:     $symb=escape($symb);
1.187     www      2699:     if (!$namespace) { 
1.620     albertel 2700:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2701:           return ''; 
                   2702:        } 
                   2703:     }
1.620     albertel 2704:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2705: 
                   2706:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2707:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 2708: 
1.47      www      2709:     my $namevalue='';
1.800     albertel 2710:     foreach my $key (keys(%$storehash)) {
                   2711:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 2712:     }
1.47      www      2713:     $namevalue=~s/\&$//;
1.187     www      2714:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      2715:     return critical
                   2716:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      2717: }
                   2718: 
1.9       www      2719: # --------------------------------------------------------------------- Restore
                   2720: 
                   2721: sub restore {
1.124     www      2722:     my ($symb,$namespace,$domain,$stuname) = @_;
                   2723:     my $home='';
                   2724: 
1.168     albertel 2725:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2726: 
1.122     albertel 2727:     if (!$symb) {
                   2728:       unless ($symb=escape(&symbread())) { return ''; }
                   2729:     } else {
1.213     www      2730:       $symb=&escape(&symbclean($symb));
1.122     albertel 2731:     }
1.188     www      2732:     if (!$namespace) { 
1.620     albertel 2733:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      2734:           return ''; 
                   2735:        } 
                   2736:     }
1.620     albertel 2737:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2738:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   2739:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 2740:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   2741: 
1.12      www      2742:     my %returnhash=();
1.800     albertel 2743:     foreach my $line (split(/\&/,$answer)) {
                   2744: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 2745:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 2746:     }
1.75      www      2747:     my $version;
                   2748:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 2749:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   2750:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 2751:        }
1.75      www      2752:     }
1.13      www      2753:     return %returnhash;
1.34      www      2754: }
                   2755: 
                   2756: # ---------------------------------------------------------- Course Description
                   2757: 
                   2758: sub coursedescription {
1.731     albertel 2759:     my ($courseid,$args)=@_;
1.34      www      2760:     $courseid=~s/^\///;
1.49      www      2761:     $courseid=~s/\_/\//g;
1.34      www      2762:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 2763:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 2764:     my $normalid=$cdomain.'_'.$cnum;
                   2765:     # need to always cache even if we get errors otherwise we keep 
                   2766:     # trying and trying and trying to get the course description.
                   2767:     my %envhash=();
                   2768:     my %returnhash=();
1.731     albertel 2769:     
                   2770:     my $expiretime=600;
                   2771:     if ($env{'request.course.id'} eq $normalid) {
                   2772: 	$expiretime=120;
                   2773:     }
                   2774: 
                   2775:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   2776:     if (!$args->{'freshen_cache'}
                   2777: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   2778: 	foreach my $key (keys(%env)) {
                   2779: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   2780: 	    my ($setting) = $1;
                   2781: 	    $returnhash{$setting} = $env{$key};
                   2782: 	}
                   2783: 	return %returnhash;
                   2784:     }
                   2785: 
                   2786:     # get the data agin
                   2787:     if (!$args->{'one_time'}) {
                   2788: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   2789:     }
1.811     albertel 2790: 
1.34      www      2791:     if ($chome ne 'no_host') {
1.302     albertel 2792:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 2793:        if (!exists($returnhash{'con_lost'})) {
                   2794:            $returnhash{'home'}= $chome;
                   2795: 	   $returnhash{'domain'} = $cdomain;
                   2796: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  2797:            if (!defined($returnhash{'type'})) {
                   2798:                $returnhash{'type'} = 'Course';
                   2799:            }
1.130     albertel 2800:            while (my ($name,$value) = each %returnhash) {
1.53      www      2801:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 2802:            }
1.270     www      2803:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      2804:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 2805: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      2806:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   2807:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   2808:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      2809:        }
                   2810:     }
1.731     albertel 2811:     if (!$args->{'one_time'}) {
                   2812: 	&appenv(%envhash);
                   2813:     }
1.302     albertel 2814:     return %returnhash;
1.461     www      2815: }
                   2816: 
                   2817: # -------------------------------------------------See if a user is privileged
                   2818: 
                   2819: sub privileged {
                   2820:     my ($username,$domain)=@_;
                   2821:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   2822: 			&homeserver($username,$domain));
                   2823:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   2824:     my $now=time;
                   2825:     if ($rolesdump ne '') {
1.800     albertel 2826:         foreach my $entry (split(/&/,$rolesdump)) {
                   2827: 	    if ($entry!~/^rolesdef_/) {
                   2828: 		my ($area,$role)=split(/=/,$entry);
1.461     www      2829: 		$area=~s/\_\w\w$//;
                   2830: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   2831: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   2832: 		    my $active=1;
                   2833: 		    if ($tend) {
                   2834: 			if ($tend<$now) { $active=0; }
                   2835: 		    }
                   2836: 		    if ($tstart) {
                   2837: 			if ($tstart>$now) { $active=0; }
                   2838: 		    }
                   2839: 		    if ($active) { return 1; }
                   2840: 		}
                   2841: 	    }
                   2842: 	}
                   2843:     }
                   2844:     return 0;
1.9       www      2845: }
1.1       albertel 2846: 
1.103     harris41 2847: # -------------------------------------------------------- Get user privileges
1.11      www      2848: 
                   2849: sub rolesinit {
                   2850:     my ($domain,$username,$authhost)=@_;
                   2851:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12      www      2852:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11      www      2853:     my %allroles=();
1.678     raeburn  2854:     my %allgroups=();   
1.11      www      2855:     my $now=time;
1.743     albertel 2856:     my %userroles = ('user.login.time' => $now);
1.678     raeburn  2857:     my $group_privs;
1.11      www      2858: 
                   2859:     if ($rolesdump ne '') {
1.800     albertel 2860:         foreach my $entry (split(/&/,$rolesdump)) {
                   2861: 	  if ($entry!~/^rolesdef_/) {
                   2862:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 2863: 	    $area=~s/\_\w\w$//;
1.678     raeburn  2864:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 2865: 	    if ($role=~/^cr/) { 
1.807     albertel 2866: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   2867: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 2868: 		    ($tend,$tstart)=split('_',$trest);
                   2869: 		} else {
                   2870: 		    $trole=$role;
                   2871: 		}
1.678     raeburn  2872:             } elsif ($role =~ m|^gr/|) {
                   2873:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   2874:                 ($trole,$group_privs) = split(/\//,$trole);
                   2875:                 $group_privs = &unescape($group_privs);
1.587     albertel 2876: 	    } else {
                   2877: 		($trole,$tend,$tstart)=split(/_/,$role);
                   2878: 	    }
1.743     albertel 2879: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   2880: 					 $username);
                   2881: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  2882:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   2883:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      2884:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 2885: 		my $spec=$trole.'.'.$area;
                   2886: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   2887: 		if ($trole =~ /^cr\//) {
1.567     raeburn  2888:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  2889:                 } elsif ($trole eq 'gr') {
                   2890:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 2891: 		} else {
1.567     raeburn  2892:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 2893: 		}
1.12      www      2894:             }
1.662     raeburn  2895:           }
1.191     harris41 2896:         }
1.743     albertel 2897:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   2898:         $userroles{'user.adv'}    = $adv;
                   2899: 	$userroles{'user.author'} = $author;
1.620     albertel 2900:         $env{'user.adv'}=$adv;
1.11      www      2901:     }
1.743     albertel 2902:     return \%userroles;  
1.11      www      2903: }
                   2904: 
1.567     raeburn  2905: sub set_arearole {
                   2906:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   2907: # log the associated role with the area
                   2908:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 2909:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  2910: }
                   2911: 
                   2912: sub custom_roleprivs {
                   2913:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   2914:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   2915:     my $homsvr=homeserver($rauthor,$rdomain);
                   2916:     if ($hostname{$homsvr} ne '') {
                   2917:         my ($rdummy,$roledef)=
                   2918:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   2919:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   2920:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   2921:             if (defined($syspriv)) {
                   2922:                 $$allroles{'cm./'}.=':'.$syspriv;
                   2923:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   2924:             }
                   2925:             if ($tdomain ne '') {
                   2926:                 if (defined($dompriv)) {
                   2927:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   2928:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   2929:                 }
                   2930:                 if (($trest ne '') && (defined($coursepriv))) {
                   2931:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   2932:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   2933:                 }
                   2934:             }
                   2935:         }
                   2936:     }
                   2937: }
                   2938: 
1.678     raeburn  2939: sub group_roleprivs {
                   2940:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   2941:     my $access = 1;
                   2942:     my $now = time;
                   2943:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   2944:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   2945:     if ($access) {
1.811     albertel 2946:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  2947:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   2948:     }
                   2949: }
1.567     raeburn  2950: 
                   2951: sub standard_roleprivs {
                   2952:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   2953:     if (defined($pr{$trole.':s'})) {
                   2954:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   2955:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   2956:     }
                   2957:     if ($tdomain ne '') {
                   2958:         if (defined($pr{$trole.':d'})) {
                   2959:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   2960:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   2961:         }
                   2962:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   2963:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   2964:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   2965:         }
                   2966:     }
                   2967: }
                   2968: 
                   2969: sub set_userprivs {
1.678     raeburn  2970:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  2971:     my $author=0;
                   2972:     my $adv=0;
1.678     raeburn  2973:     my %grouproles = ();
                   2974:     if (keys(%{$allgroups}) > 0) {
                   2975:         foreach my $role (keys %{$allroles}) {
1.681     raeburn  2976:             my ($trole,$area,$sec,$extendedarea);
1.811     albertel 2977:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)-) {
1.678     raeburn  2978:                 $trole = $1;
                   2979:                 $area = $2;
1.681     raeburn  2980:                 $sec = $3;
                   2981:                 $extendedarea = $area.$sec;
                   2982:                 if (exists($$allgroups{$area})) {
                   2983:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   2984:                         my $spec = $trole.'.'.$extendedarea;
                   2985:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   2986:                                                 $$allgroups{$area}{$group};
1.678     raeburn  2987:                     }
                   2988:                 }
                   2989:             }
                   2990:         }
                   2991:     }
1.800     albertel 2992:     foreach my $group (keys(%grouproles)) {
                   2993:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  2994:     }
1.800     albertel 2995:     foreach my $role (keys(%{$allroles})) {
                   2996:         my %thesepriv;
                   2997:         if (($role=~/^au/) || ($role=~/^ca/)) { $author=1; }
                   2998:         foreach my $item (split(/:/,$$allroles{$role})) {
                   2999:             if ($item ne '') {
                   3000:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  3001:                 if ($restrictions eq '') {
                   3002:                     $thesepriv{$privilege}='F';
                   3003:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   3004:                     $thesepriv{$privilege}.=$restrictions;
                   3005:                 }
                   3006:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   3007:             }
                   3008:         }
                   3009:         my $thesestr='';
1.800     albertel 3010:         foreach my $priv (keys(%thesepriv)) {
                   3011: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   3012: 	}
                   3013:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  3014:     }
                   3015:     return ($author,$adv);
                   3016: }
                   3017: 
1.12      www      3018: # --------------------------------------------------------------- get interface
                   3019: 
                   3020: sub get {
1.131     albertel 3021:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3022:    my $items='';
1.800     albertel 3023:    foreach my $item (@$storearr) {
                   3024:        $items.=&escape($item).'&';
1.191     harris41 3025:    }
1.12      www      3026:    $items=~s/\&$//;
1.620     albertel 3027:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3028:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 3029:    my $uhome=&homeserver($uname,$udomain);
                   3030: 
1.133     albertel 3031:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3032:    my @pairs=split(/\&/,$rep);
1.273     albertel 3033:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   3034:      return @pairs;
                   3035:    }
1.15      www      3036:    my %returnhash=();
1.42      www      3037:    my $i=0;
1.800     albertel 3038:    foreach my $item (@$storearr) {
                   3039:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3040:       $i++;
1.191     harris41 3041:    }
1.15      www      3042:    return %returnhash;
1.27      www      3043: }
                   3044: 
                   3045: # --------------------------------------------------------------- del interface
                   3046: 
                   3047: sub del {
1.133     albertel 3048:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      3049:    my $items='';
1.800     albertel 3050:    foreach my $item (@$storearr) {
                   3051:        $items.=&escape($item).'&';
1.191     harris41 3052:    }
1.27      www      3053:    $items=~s/\&$//;
1.620     albertel 3054:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3055:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3056:    my $uhome=&homeserver($uname,$udomain);
                   3057: 
                   3058:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3059: }
                   3060: 
                   3061: # -------------------------------------------------------------- dump interface
                   3062: 
                   3063: sub dump {
1.755     albertel 3064:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   3065:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3066:     if (!$uname) { $uname=$env{'user.name'}; }
                   3067:     my $uhome=&homeserver($uname,$udomain);
                   3068:     if ($regexp) {
                   3069: 	$regexp=&escape($regexp);
                   3070:     } else {
                   3071: 	$regexp='.';
                   3072:     }
                   3073:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3074:     my @pairs=split(/\&/,$rep);
                   3075:     my %returnhash=();
                   3076:     foreach my $item (@pairs) {
                   3077: 	my ($key,$value)=split(/=/,$item,2);
                   3078: 	$key = &unescape($key);
                   3079: 	next if ($key =~ /^error: 2 /);
                   3080: 	$returnhash{$key}=&thaw_unescape($value);
                   3081:     }
                   3082:     return %returnhash;
1.407     www      3083: }
                   3084: 
1.717     albertel 3085: # --------------------------------------------------------- dumpstore interface
                   3086: 
                   3087: sub dumpstore {
                   3088:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 3089:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3090:    if (!$uname) { $uname=$env{'user.name'}; }
                   3091:    my $uhome=&homeserver($uname,$udomain);
                   3092:    if ($regexp) {
                   3093:        $regexp=&escape($regexp);
                   3094:    } else {
                   3095:        $regexp='.';
                   3096:    }
                   3097:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3098:    my @pairs=split(/\&/,$rep);
                   3099:    my %returnhash=();
                   3100:    foreach my $item (@pairs) {
                   3101:        my ($key,$value)=split(/=/,$item,2);
                   3102:        next if ($key =~ /^error: 2 /);
                   3103:        $returnhash{$key}=&thaw_unescape($value);
                   3104:    }
                   3105:    return %returnhash;
1.717     albertel 3106: }
                   3107: 
1.407     www      3108: # -------------------------------------------------------------- keys interface
                   3109: 
                   3110: sub getkeys {
                   3111:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 3112:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3113:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      3114:    my $uhome=&homeserver($uname,$udomain);
                   3115:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   3116:    my @keyarray=();
1.800     albertel 3117:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  3118:       next if ($key =~ /^error: 2 /);
1.800     albertel 3119:       push(@keyarray,&unescape($key));
1.407     www      3120:    }
                   3121:    return @keyarray;
1.318     matthew  3122: }
                   3123: 
1.319     matthew  3124: # --------------------------------------------------------------- currentdump
                   3125: sub currentdump {
1.328     matthew  3126:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 3127:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   3128:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   3129:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  3130:    my $uhome = &homeserver($sname,$sdom);
                   3131:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  3132:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  3133:    #
1.318     matthew  3134:    my %returnhash=();
1.319     matthew  3135:    #
                   3136:    if ($rep eq "unknown_cmd") { 
                   3137:        # an old lond will not know currentdump
                   3138:        # Do a dump and make it look like a currentdump
1.822     albertel 3139:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  3140:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   3141:        my %hash = @tmp;
                   3142:        @tmp=();
1.424     matthew  3143:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  3144:    } else {
                   3145:        my @pairs=split(/\&/,$rep);
1.800     albertel 3146:        foreach my $pair (@pairs) {
                   3147:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  3148:            my ($symb,$param) = split(/:/,$key);
                   3149:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 3150:                                                         &thaw_unescape($value);
1.319     matthew  3151:        }
1.191     harris41 3152:    }
1.12      www      3153:    return %returnhash;
1.424     matthew  3154: }
                   3155: 
                   3156: sub convert_dump_to_currentdump{
                   3157:     my %hash = %{shift()};
                   3158:     my %returnhash;
                   3159:     # Code ripped from lond, essentially.  The only difference
                   3160:     # here is the unescaping done by lonnet::dump().  Conceivably
                   3161:     # we might run in to problems with parameter names =~ /^v\./
                   3162:     while (my ($key,$value) = each(%hash)) {
                   3163:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 3164: 	$symb  = &unescape($symb);
                   3165: 	$param = &unescape($param);
1.424     matthew  3166:         next if ($v eq 'version' || $symb eq 'keys');
                   3167:         next if (exists($returnhash{$symb}) &&
                   3168:                  exists($returnhash{$symb}->{$param}) &&
                   3169:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   3170:         $returnhash{$symb}->{$param}=$value;
                   3171:         $returnhash{$symb}->{'v.'.$param}=$v;
                   3172:     }
                   3173:     #
                   3174:     # Remove all of the keys in the hashes which keep track of
                   3175:     # the version of the parameter.
                   3176:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   3177:         # use a foreach because we are going to delete from the hash.
                   3178:         foreach my $key (keys(%$param_hash)) {
                   3179:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   3180:         }
                   3181:     }
                   3182:     return \%returnhash;
1.12      www      3183: }
                   3184: 
1.627     albertel 3185: # ------------------------------------------------------ critical inc interface
                   3186: 
                   3187: sub cinc {
                   3188:     return &inc(@_,'critical');
                   3189: }
                   3190: 
1.449     matthew  3191: # --------------------------------------------------------------- inc interface
                   3192: 
                   3193: sub inc {
1.627     albertel 3194:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 3195:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3196:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  3197:     my $uhome=&homeserver($uname,$udomain);
                   3198:     my $items='';
                   3199:     if (! ref($store)) {
                   3200:         # got a single value, so use that instead
                   3201:         $items = &escape($store).'=&';
                   3202:     } elsif (ref($store) eq 'SCALAR') {
                   3203:         $items = &escape($$store).'=&';        
                   3204:     } elsif (ref($store) eq 'ARRAY') {
                   3205:         $items = join('=&',map {&escape($_);} @{$store});
                   3206:     } elsif (ref($store) eq 'HASH') {
                   3207:         while (my($key,$value) = each(%{$store})) {
                   3208:             $items.= &escape($key).'='.&escape($value).'&';
                   3209:         }
                   3210:     }
                   3211:     $items=~s/\&$//;
1.627     albertel 3212:     if ($critical) {
                   3213: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3214:     } else {
                   3215: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3216:     }
1.449     matthew  3217: }
                   3218: 
1.12      www      3219: # --------------------------------------------------------------- put interface
                   3220: 
                   3221: sub put {
1.134     albertel 3222:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3223:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3224:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3225:    my $uhome=&homeserver($uname,$udomain);
1.12      www      3226:    my $items='';
1.800     albertel 3227:    foreach my $item (keys(%$storehash)) {
                   3228:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3229:    }
1.12      www      3230:    $items=~s/\&$//;
1.134     albertel 3231:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      3232: }
                   3233: 
1.631     albertel 3234: # ------------------------------------------------------------ newput interface
                   3235: 
                   3236: sub newput {
                   3237:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   3238:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3239:    if (!$uname) { $uname=$env{'user.name'}; }
                   3240:    my $uhome=&homeserver($uname,$udomain);
                   3241:    my $items='';
                   3242:    foreach my $key (keys(%$storehash)) {
                   3243:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   3244:    }
                   3245:    $items=~s/\&$//;
                   3246:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   3247: }
                   3248: 
                   3249: # ---------------------------------------------------------  putstore interface
                   3250: 
1.524     raeburn  3251: sub putstore {
1.715     albertel 3252:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 3253:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3254:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  3255:    my $uhome=&homeserver($uname,$udomain);
                   3256:    my $items='';
1.715     albertel 3257:    foreach my $key (keys(%$storehash)) {
                   3258:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  3259:    }
1.715     albertel 3260:    $items=~s/\&$//;
1.716     albertel 3261:    my $esc_symb=&escape($symb);
                   3262:    my $esc_v=&escape($version);
1.715     albertel 3263:    my $reply =
1.716     albertel 3264:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 3265: 	      $uhome);
                   3266:    if ($reply eq 'unknown_cmd') {
1.716     albertel 3267:        # gfall back to way things use to be done
1.715     albertel 3268:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   3269: 			    $uname);
1.524     raeburn  3270:    }
1.715     albertel 3271:    return $reply;
                   3272: }
                   3273: 
                   3274: sub old_putstore {
1.716     albertel 3275:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   3276:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3277:     if (!$uname) { $uname=$env{'user.name'}; }
                   3278:     my $uhome=&homeserver($uname,$udomain);
                   3279:     my %newstorehash;
1.800     albertel 3280:     foreach my $item (keys(%$storehash)) {
                   3281: 	my $key = $version.':'.&escape($symb).':'.$item;
                   3282: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 3283:     }
                   3284:     my $items='';
                   3285:     my %allitems = ();
1.800     albertel 3286:     foreach my $item (keys(%newstorehash)) {
                   3287: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 3288: 	    my $key = $1.':keys:'.$2;
                   3289: 	    $allitems{$key} .= $3.':';
                   3290: 	}
1.800     albertel 3291: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 3292:     }
1.800     albertel 3293:     foreach my $item (keys(%allitems)) {
                   3294: 	$allitems{$item} =~ s/\:$//;
                   3295: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 3296:     }
                   3297:     $items=~s/\&$//;
                   3298:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  3299: }
                   3300: 
1.47      www      3301: # ------------------------------------------------------ critical put interface
                   3302: 
                   3303: sub cput {
1.134     albertel 3304:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3305:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3306:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3307:    my $uhome=&homeserver($uname,$udomain);
1.47      www      3308:    my $items='';
1.800     albertel 3309:    foreach my $item (keys(%$storehash)) {
                   3310:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3311:    }
1.47      www      3312:    $items=~s/\&$//;
1.134     albertel 3313:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3314: }
                   3315: 
                   3316: # -------------------------------------------------------------- eget interface
                   3317: 
                   3318: sub eget {
1.133     albertel 3319:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3320:    my $items='';
1.800     albertel 3321:    foreach my $item (@$storearr) {
                   3322:        $items.=&escape($item).'&';
1.191     harris41 3323:    }
1.12      www      3324:    $items=~s/\&$//;
1.620     albertel 3325:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3326:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3327:    my $uhome=&homeserver($uname,$udomain);
                   3328:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3329:    my @pairs=split(/\&/,$rep);
                   3330:    my %returnhash=();
1.42      www      3331:    my $i=0;
1.800     albertel 3332:    foreach my $item (@$storearr) {
                   3333:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3334:       $i++;
1.191     harris41 3335:    }
1.12      www      3336:    return %returnhash;
                   3337: }
                   3338: 
1.667     albertel 3339: # ------------------------------------------------------------ tmpput interface
                   3340: sub tmpput {
1.802     raeburn  3341:     my ($storehash,$server,$context)=@_;
1.667     albertel 3342:     my $items='';
1.800     albertel 3343:     foreach my $item (keys(%$storehash)) {
                   3344: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 3345:     }
                   3346:     $items=~s/\&$//;
1.802     raeburn  3347:     if (defined($context)) {
                   3348:         $items .= ':'.&escape($context);
                   3349:     }
1.667     albertel 3350:     return &reply("tmpput:$items",$server);
                   3351: }
                   3352: 
                   3353: # ------------------------------------------------------------ tmpget interface
                   3354: sub tmpget {
1.688     albertel 3355:     my ($token,$server)=@_;
                   3356:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3357:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 3358:     my %returnhash;
                   3359:     foreach my $item (split(/\&/,$rep)) {
                   3360: 	my ($key,$value)=split(/=/,$item);
                   3361: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   3362:     }
                   3363:     return %returnhash;
                   3364: }
                   3365: 
1.688     albertel 3366: # ------------------------------------------------------------ tmpget interface
                   3367: sub tmpdel {
                   3368:     my ($token,$server)=@_;
                   3369:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3370:     return &reply("tmpdel:$token",$server);
                   3371: }
                   3372: 
1.765     albertel 3373: # -------------------------------------------------- portfolio access checking
                   3374: 
                   3375: sub portfolio_access {
1.766     albertel 3376:     my ($requrl) = @_;
1.765     albertel 3377:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   3378:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  3379:     if ($result) {
                   3380:         my %setters;
                   3381:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3382:             my ($startblock,$endblock) =
                   3383:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   3384:             if ($startblock && $endblock) {
                   3385:                 return 'B';
                   3386:             }
                   3387:         } else {
                   3388:             my ($startblock,$endblock) =
                   3389:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   3390:             if ($startblock && $endblock) {
                   3391:                 return 'B';
                   3392:             }
                   3393:         }
                   3394:     }
1.765     albertel 3395:     if ($result eq 'ok') {
1.766     albertel 3396:        return 'F';
1.765     albertel 3397:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 3398:        return 'A';
1.765     albertel 3399:     }
1.766     albertel 3400:     return '';
1.765     albertel 3401: }
                   3402: 
                   3403: sub get_portfolio_access {
1.767     albertel 3404:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   3405: 
                   3406:     if (!ref($access_hash)) {
                   3407: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   3408: 	my %access_controls = &get_access_controls($current_perms,$group,
                   3409: 						   $file_name);
                   3410: 	$access_hash = $access_controls{$file_name};
                   3411:     }
                   3412: 
1.765     albertel 3413:     my ($public,$guest,@domains,@users,@courses,@groups);
                   3414:     my $now = time;
                   3415:     if (ref($access_hash) eq 'HASH') {
                   3416:         foreach my $key (keys(%{$access_hash})) {
                   3417:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   3418:             if ($start > $now) {
                   3419:                 next;
                   3420:             }
                   3421:             if ($end && $end<$now) {
                   3422:                 next;
                   3423:             }
                   3424:             if ($scope eq 'public') {
                   3425:                 $public = $key;
                   3426:                 last;
                   3427:             } elsif ($scope eq 'guest') {
                   3428:                 $guest = $key;
                   3429:             } elsif ($scope eq 'domains') {
                   3430:                 push(@domains,$key);
                   3431:             } elsif ($scope eq 'users') {
                   3432:                 push(@users,$key);
                   3433:             } elsif ($scope eq 'course') {
                   3434:                 push(@courses,$key);
                   3435:             } elsif ($scope eq 'group') {
                   3436:                 push(@groups,$key);
                   3437:             }
                   3438:         }
                   3439:         if ($public) {
                   3440:             return 'ok';
                   3441:         }
                   3442:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3443:             if ($guest) {
                   3444:                 return $guest;
                   3445:             }
                   3446:         } else {
                   3447:             if (@domains > 0) {
                   3448:                 foreach my $domkey (@domains) {
                   3449:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   3450:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   3451:                             return 'ok';
                   3452:                         }
                   3453:                     }
                   3454:                 }
                   3455:             }
                   3456:             if (@users > 0) {
                   3457:                 foreach my $userkey (@users) {
                   3458:                     if (exists($access_hash->{$userkey}{'users'}{$env{'user.name'}.':'.$env{'user.domain'}})) {
                   3459:                         return 'ok';
                   3460:                     }
                   3461:                 }
                   3462:             }
                   3463:             my %roleshash;
                   3464:             my @courses_and_groups = @courses;
                   3465:             push(@courses_and_groups,@groups); 
                   3466:             if (@courses_and_groups > 0) {
                   3467:                 my (%allgroups,%allroles); 
                   3468:                 my ($start,$end,$role,$sec,$group);
                   3469:                 foreach my $envkey (%env) {
1.811     albertel 3470:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 3471:                         my $cid = $2.'_'.$3; 
                   3472:                         if ($1 eq 'gr') {
                   3473:                             $group = $4;
                   3474:                             $allgroups{$cid}{$group} = $env{$envkey};
                   3475:                         } else {
                   3476:                             if ($4 eq '') {
                   3477:                                 $sec = 'none';
                   3478:                             } else {
                   3479:                                 $sec = $4;
                   3480:                             }
                   3481:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3482:                         }
1.811     albertel 3483:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 3484:                         my $cid = $2.'_'.$3;
                   3485:                         if ($4 eq '') {
                   3486:                             $sec = 'none';
                   3487:                         } else {
                   3488:                             $sec = $4;
                   3489:                         }
                   3490:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3491:                     }
                   3492:                 }
                   3493:                 if (keys(%allroles) == 0) {
                   3494:                     return;
                   3495:                 }
                   3496:                 foreach my $key (@courses_and_groups) {
                   3497:                     my %content = %{$$access_hash{$key}};
                   3498:                     my $cnum = $content{'number'};
                   3499:                     my $cdom = $content{'domain'};
                   3500:                     my $cid = $cdom.'_'.$cnum;
                   3501:                     if (!exists($allroles{$cid})) {
                   3502:                         next;
                   3503:                     }    
                   3504:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   3505:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   3506:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   3507:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   3508:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   3509:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   3510:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   3511:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   3512:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   3513:                                         if (grep/^all$/,@sections) {
                   3514:                                             return 'ok';
                   3515:                                         } else {
                   3516:                                             if (grep/^$sec$/,@sections) {
                   3517:                                                 return 'ok';
                   3518:                                             }
                   3519:                                         }
                   3520:                                     }
                   3521:                                 }
                   3522:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   3523:                                     if (grep/^none$/,@groups) {
                   3524:                                         return 'ok';
                   3525:                                     }
                   3526:                                 } else {
                   3527:                                     if (grep/^all$/,@groups) {
                   3528:                                         return 'ok';
                   3529:                                     } 
                   3530:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   3531:                                         if (grep/^$group$/,@groups) {
                   3532:                                             return 'ok';
                   3533:                                         }
                   3534:                                     }
                   3535:                                 } 
                   3536:                             }
                   3537:                         }
                   3538:                     }
                   3539:                 }
                   3540:             }
                   3541:             if ($guest) {
                   3542:                 return $guest;
                   3543:             }
                   3544:         }
                   3545:     }
                   3546:     return;
                   3547: }
                   3548: 
                   3549: sub course_group_datechecker {
                   3550:     my ($dates,$now,$status) = @_;
                   3551:     my ($start,$end) = split(/\./,$dates);
                   3552:     if (!$start && !$end) {
                   3553:         return 'ok';
                   3554:     }
                   3555:     if (grep/^active$/,@{$status}) {
                   3556:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   3557:             return 'ok';
                   3558:         }
                   3559:     }
                   3560:     if (grep/^previous$/,@{$status}) {
                   3561:         if ($end > $now ) {
                   3562:             return 'ok';
                   3563:         }
                   3564:     }
                   3565:     if (grep/^future$/,@{$status}) {
                   3566:         if ($start > $now) {
                   3567:             return 'ok';
                   3568:         }
                   3569:     }
                   3570:     return; 
                   3571: }
                   3572: 
                   3573: sub parse_portfolio_url {
                   3574:     my ($url) = @_;
                   3575: 
                   3576:     my ($type,$udom,$unum,$group,$file_name);
                   3577:     
1.823     albertel 3578:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 3579: 	$type = 1;
                   3580:         $udom = $1;
                   3581:         $unum = $2;
                   3582:         $file_name = $3;
1.823     albertel 3583:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 3584: 	$type = 2;
                   3585:         $udom = $1;
                   3586:         $unum = $2;
                   3587:         $group = $3;
                   3588:         $file_name = $3.'/'.$4;
                   3589:     }
                   3590:     if (wantarray) {
                   3591: 	return ($type,$udom,$unum,$file_name,$group);
                   3592:     }
                   3593:     return $type;
                   3594: }
                   3595: 
                   3596: sub is_portfolio_url {
                   3597:     my ($url) = @_;
                   3598:     return scalar(&parse_portfolio_url($url));
                   3599: }
                   3600: 
1.798     raeburn  3601: sub is_portfolio_file {
                   3602:     my ($file) = @_;
1.820     raeburn  3603:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  3604:         return 1;
                   3605:     }
                   3606:     return;
                   3607: }
                   3608: 
                   3609: 
1.341     www      3610: # ---------------------------------------------- Custom access rule evaluation
                   3611: 
                   3612: sub customaccess {
                   3613:     my ($priv,$uri)=@_;
1.807     albertel 3614:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      3615:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 3616:     $udom = &LONCAPA::clean_domain($udom);
                   3617:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      3618:     my $access=0;
1.800     albertel 3619:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
                   3620: 	my ($effect,$realm,$role)=split(/\:/,$right);
1.343     www      3621:         if ($role) {
                   3622: 	   if ($role ne $urole) { next; }
                   3623:         }
1.800     albertel 3624:         foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   3625:             my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
1.343     www      3626:             if ($tdom) {
                   3627: 		if ($tdom ne $udom) { next; }
                   3628:             }
                   3629:             if ($tcrs) {
                   3630: 		if ($tcrs ne $ucrs) { next; }
                   3631:             }
                   3632:             if ($tsec) {
                   3633: 		if ($tsec ne $usec) { next; }
                   3634:             }
                   3635:             $access=($effect eq 'allow');
                   3636:             last;
1.342     www      3637:         }
1.402     bowersj2 3638: 	if ($realm eq '' && $role eq '') {
                   3639:             $access=($effect eq 'allow');
                   3640: 	}
1.341     www      3641:     }
                   3642:     return $access;
                   3643: }
                   3644: 
1.103     harris41 3645: # ------------------------------------------------- Check for a user privilege
1.12      www      3646: 
                   3647: sub allowed {
1.810     raeburn  3648:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 3649:     my $ver_orguri=$uri;
1.439     www      3650:     $uri=&deversion($uri);
1.152     www      3651:     my $orguri=$uri;
1.52      www      3652:     $uri=&declutter($uri);
1.809     raeburn  3653: 
1.810     raeburn  3654:     if ($priv eq 'evb') {
                   3655: # Evade communication block restrictions for specified role in a course
                   3656:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   3657:             return $1;
                   3658:         } else {
                   3659:             return;
                   3660:         }
                   3661:     }
                   3662: 
1.620     albertel 3663:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      3664: # Free bre access to adm and meta resources
1.775     albertel 3665:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 3666: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   3667: 	&& ($priv eq 'bre')) {
1.14      www      3668: 	return 'F';
1.159     www      3669:     }
                   3670: 
1.545     banghart 3671: # Free bre access to user's own portfolio contents
1.714     raeburn  3672:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  3673:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  3674: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  3675:         my %setters;
                   3676:         my ($startblock,$endblock) = 
                   3677:             &Apache::loncommon::blockcheck(\%setters,'port');
                   3678:         if ($startblock && $endblock) {
                   3679:             return 'B';
                   3680:         } else {
                   3681:             return 'F';
                   3682:         }
1.545     banghart 3683:     }
                   3684: 
1.762     raeburn  3685: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  3686:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   3687:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   3688:         if (exists($env{'request.course.id'})) {
                   3689:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3690:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3691:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   3692:                 my $courseprivid=$env{'request.course.id'};
                   3693:                 $courseprivid=~s/\_/\//;
                   3694:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   3695:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   3696:                     return $1; 
1.762     raeburn  3697:                 } else {
                   3698:                     if ($env{'request.course.sec'}) {
                   3699:                         $courseprivid.='/'.$env{'request.course.sec'};
                   3700:                     }
                   3701:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   3702:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   3703:                         return $2;
                   3704:                     }
1.714     raeburn  3705:                 }
                   3706:             }
                   3707:         }
                   3708:     }
                   3709: 
1.159     www      3710: # Free bre to public access
                   3711: 
                   3712:     if ($priv eq 'bre') {
1.238     www      3713:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 3714: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      3715:            return 'F'; 
                   3716:         }
1.238     www      3717:         if ($copyright eq 'priv') {
                   3718:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3719: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      3720: 		return '';
                   3721:             }
                   3722:         }
                   3723:         if ($copyright eq 'domain') {
                   3724:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3725: 	    unless (($env{'user.domain'} eq $1) ||
                   3726:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      3727: 		return '';
                   3728:             }
1.262     matthew  3729:         }
1.620     albertel 3730:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  3731:             # Library role, so allow browsing of resources in this domain.
                   3732:             return 'F';
1.238     www      3733:         }
1.341     www      3734:         if ($copyright eq 'custom') {
                   3735: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   3736:         }
1.14      www      3737:     }
1.264     matthew  3738:     # Domain coordinator is trying to create a course
1.620     albertel 3739:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  3740:         # uri is the requested domain in this case.
                   3741:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  3742:         # a role of dc for the domain in question.
1.620     albertel 3743:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  3744:     }
1.29      www      3745: 
1.52      www      3746:     my $thisallowed='';
                   3747:     my $statecond=0;
                   3748:     my $courseprivid='';
                   3749: 
                   3750: # Course
                   3751: 
1.620     albertel 3752:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3753:        $thisallowed.=$1;
                   3754:     }
1.29      www      3755: 
1.52      www      3756: # Domain
                   3757: 
1.620     albertel 3758:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 3759:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3760:        $thisallowed.=$1;
                   3761:     }
1.52      www      3762: 
                   3763: # Course: uri itself is a course
1.66      www      3764:     my $courseuri=$uri;
                   3765:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      3766:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      3767: 
1.620     albertel 3768:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 3769:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3770:        $thisallowed.=$1;
                   3771:     }
1.29      www      3772: 
1.665     albertel 3773: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 3774: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 3775:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 3776: 	$thisallowed='';
1.671     raeburn  3777:         my ($match)=&is_on_map($uri);
                   3778:         if ($match) {
                   3779:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   3780:                   =~/\Q$priv\E\&([^\:]*)/) {
                   3781:                 $thisallowed.=$1;
                   3782:             }
                   3783:         } else {
1.705     albertel 3784:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  3785:             if ($refuri) {
                   3786:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  3787:                     $thisallowed='F';
1.671     raeburn  3788:                 } else {
                   3789:                     $refuri=&declutter($refuri);
                   3790:                     my ($match) = &is_on_map($refuri);
                   3791:                     if ($match) {
                   3792:                         $thisallowed='F';
                   3793:                     }
1.669     raeburn  3794:                 }
1.671     raeburn  3795:             }
                   3796:         }
1.314     www      3797:     }
1.492     albertel 3798: 
1.766     albertel 3799:     if ($priv eq 'bre'
                   3800: 	&& $thisallowed ne 'F' 
                   3801: 	&& $thisallowed ne '2'
                   3802: 	&& &is_portfolio_url($uri)) {
                   3803: 	$thisallowed = &portfolio_access($uri);
                   3804:     }
                   3805:     
1.52      www      3806: # Full access at system, domain or course-wide level? Exit.
1.29      www      3807: 
                   3808:     if ($thisallowed=~/F/) {
                   3809: 	return 'F';
                   3810:     }
                   3811: 
1.52      www      3812: # If this is generating or modifying users, exit with special codes
1.29      www      3813: 
1.643     www      3814:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   3815: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 3816: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      3817: # no author name given, so this just checks on the general right to make a co-author in this domain
                   3818: 	    unless ($auname) { return $thisallowed; }
                   3819: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 3820: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   3821: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   3822: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   3823: 	}
1.52      www      3824: 	return $thisallowed;
                   3825:     }
                   3826: #
1.103     harris41 3827: # Gathered so far: system, domain and course wide privileges
1.52      www      3828: #
                   3829: # Course: See if uri or referer is an individual resource that is part of 
                   3830: # the course
                   3831: 
1.620     albertel 3832:     if ($env{'request.course.id'}) {
1.232     www      3833: 
1.620     albertel 3834:        $courseprivid=$env{'request.course.id'};
                   3835:        if ($env{'request.course.sec'}) {
                   3836:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      3837:        }
                   3838:        $courseprivid=~s/\_/\//;
                   3839:        my $checkreferer=1;
1.232     www      3840:        my ($match,$cond)=&is_on_map($uri);
                   3841:        if ($match) {
                   3842:            $statecond=$cond;
1.620     albertel 3843:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 3844:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3845:                $thisallowed.=$1;
                   3846:                $checkreferer=0;
                   3847:            }
1.29      www      3848:        }
1.83      www      3849:        
1.148     www      3850:        if ($checkreferer) {
1.620     albertel 3851: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      3852:             unless ($refuri) {
1.800     albertel 3853:                 foreach my $key (keys(%env)) {
                   3854: 		    if ($key=~/^httpref\..*\*/) {
                   3855: 			my $pattern=$key;
1.156     www      3856:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      3857:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   3858:                         $pattern=~s/\//\\\//g;
1.152     www      3859:                         if ($orguri=~/$pattern/) {
1.800     albertel 3860: 			    $refuri=$env{$key};
1.148     www      3861:                         }
                   3862:                     }
1.191     harris41 3863:                 }
1.148     www      3864:             }
1.232     www      3865: 
1.148     www      3866:          if ($refuri) { 
1.152     www      3867: 	  $refuri=&declutter($refuri);
1.232     www      3868:           my ($match,$cond)=&is_on_map($refuri);
                   3869:             if ($match) {
                   3870:               my $refstatecond=$cond;
1.620     albertel 3871:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 3872:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3873:                   $thisallowed.=$1;
1.53      www      3874:                   $uri=$refuri;
                   3875:                   $statecond=$refstatecond;
1.52      www      3876:               }
                   3877:           }
1.148     www      3878:         }
1.29      www      3879:        }
1.52      www      3880:    }
1.29      www      3881: 
1.52      www      3882: #
1.103     harris41 3883: # Gathered now: all privileges that could apply, and condition number
1.52      www      3884: # 
                   3885: #
                   3886: # Full or no access?
                   3887: #
1.29      www      3888: 
1.52      www      3889:     if ($thisallowed=~/F/) {
                   3890: 	return 'F';
                   3891:     }
1.29      www      3892: 
1.52      www      3893:     unless ($thisallowed) {
                   3894:         return '';
                   3895:     }
1.29      www      3896: 
1.52      www      3897: # Restrictions exist, deal with them
                   3898: #
                   3899: #   C:according to course preferences
                   3900: #   R:according to resource settings
                   3901: #   L:unless locked
                   3902: #   X:according to user session state
                   3903: #
                   3904: 
                   3905: # Possibly locked functionality, check all courses
1.54      www      3906: # Locks might take effect only after 10 minutes cache expiration for other
                   3907: # courses, and 2 minutes for current course
1.52      www      3908: 
                   3909:     my $envkey;
                   3910:     if ($thisallowed=~/L/) {
1.620     albertel 3911:         foreach $envkey (keys %env) {
1.54      www      3912:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   3913:                my $courseid=$2;
                   3914:                my $roleid=$1.'.'.$2;
1.92      www      3915:                $courseid=~s/^\///;
1.54      www      3916:                my $expiretime=600;
1.620     albertel 3917:                if ($env{'request.role'} eq $roleid) {
1.54      www      3918: 		  $expiretime=120;
                   3919:                }
                   3920: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   3921:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 3922:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 3923: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      3924:                }
1.620     albertel 3925:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   3926:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   3927: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   3928:                        &log($env{'user.domain'},$env{'user.name'},
                   3929:                             $env{'user.home'},
1.57      www      3930:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      3931:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 3932:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      3933: 		       return '';
                   3934:                    }
                   3935:                }
1.620     albertel 3936:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   3937:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   3938: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   3939:                        &log($env{'user.domain'},$env{'user.name'},
                   3940:                             $env{'user.home'},
1.57      www      3941:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      3942:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 3943:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      3944: 		       return '';
                   3945:                    }
                   3946:                }
                   3947: 	   }
1.29      www      3948:        }
1.52      www      3949:     }
                   3950:    
                   3951: #
                   3952: # Rest of the restrictions depend on selected course
                   3953: #
                   3954: 
1.620     albertel 3955:     unless ($env{'request.course.id'}) {
1.766     albertel 3956: 	if ($thisallowed eq 'A') {
                   3957: 	    return 'A';
1.814     raeburn  3958:         } elsif ($thisallowed eq 'B') {
                   3959:             return 'B';
1.766     albertel 3960: 	} else {
                   3961: 	    return '1';
                   3962: 	}
1.52      www      3963:     }
1.29      www      3964: 
1.52      www      3965: #
                   3966: # Now user is definitely in a course
                   3967: #
1.53      www      3968: 
                   3969: 
                   3970: # Course preferences
                   3971: 
                   3972:    if ($thisallowed=~/C/) {
1.620     albertel 3973:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   3974:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   3975:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 3976: 	   =~/\Q$rolecode\E/) {
1.689     albertel 3977: 	   if ($priv ne 'pch') { 
                   3978: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   3979: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   3980: 			$env{'request.course.id'});
                   3981: 	   }
1.237     www      3982:            return '';
                   3983:        }
                   3984: 
1.620     albertel 3985:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 3986: 	   =~/\Q$unamedom\E/) {
1.689     albertel 3987: 	   if ($priv ne 'pch') { 
                   3988: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   3989: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   3990: 			$env{'request.course.id'});
                   3991: 	   }
1.54      www      3992:            return '';
                   3993:        }
1.53      www      3994:    }
                   3995: 
                   3996: # Resource preferences
                   3997: 
                   3998:    if ($thisallowed=~/R/) {
1.620     albertel 3999:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 4000:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 4001: 	   if ($priv ne 'pch') { 
                   4002: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4003: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   4004: 	   }
                   4005: 	   return '';
1.54      www      4006:        }
1.53      www      4007:    }
1.30      www      4008: 
1.246     www      4009: # Restricted by state or randomout?
1.30      www      4010: 
1.52      www      4011:    if ($thisallowed=~/X/) {
1.620     albertel 4012:       if ($env{'acc.randomout'}) {
1.579     albertel 4013: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 4014:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      4015:             return ''; 
                   4016:          }
1.247     www      4017:       }
                   4018:       if (&condval($statecond)) {
1.52      www      4019: 	 return '2';
                   4020:       } else {
                   4021:          return '';
                   4022:       }
                   4023:    }
1.30      www      4024: 
1.766     albertel 4025:     if ($thisallowed eq 'A') {
                   4026: 	return 'A';
1.814     raeburn  4027:     } elsif ($thisallowed eq 'B') {
                   4028:         return 'B';
1.766     albertel 4029:     }
1.52      www      4030:    return 'F';
1.232     www      4031: }
                   4032: 
1.710     albertel 4033: sub split_uri_for_cond {
                   4034:     my $uri=&deversion(&declutter(shift));
                   4035:     my @uriparts=split(/\//,$uri);
                   4036:     my $filename=pop(@uriparts);
                   4037:     my $pathname=join('/',@uriparts);
                   4038:     return ($pathname,$filename);
                   4039: }
1.232     www      4040: # --------------------------------------------------- Is a resource on the map?
                   4041: 
                   4042: sub is_on_map {
1.710     albertel 4043:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 4044:     #Trying to find the conditional for the file
1.620     albertel 4045:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 4046: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      4047:     if ($match) {
1.289     bowersj2 4048: 	return (1,$1);
                   4049:     } else {
1.434     www      4050: 	return (0,0);
1.289     bowersj2 4051:     }
1.12      www      4052: }
                   4053: 
1.427     www      4054: # --------------------------------------------------------- Get symb from alias
                   4055: 
                   4056: sub get_symb_from_alias {
                   4057:     my $symb=shift;
                   4058:     my ($map,$resid,$url)=&decode_symb($symb);
                   4059: # Already is a symb
                   4060:     if ($url) { return $symb; }
                   4061: # Must be an alias
                   4062:     my $aliassymb='';
                   4063:     my %bighash;
1.620     albertel 4064:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      4065:                             &GDBM_READER(),0640)) {
                   4066:         my $rid=$bighash{'mapalias_'.$symb};
                   4067: 	if ($rid) {
                   4068: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 4069: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   4070: 				    $resid,$bighash{'src_'.$rid});
1.427     www      4071: 	}
                   4072:         untie %bighash;
                   4073:     }
                   4074:     return $aliassymb;
                   4075: }
                   4076: 
1.12      www      4077: # ----------------------------------------------------------------- Define Role
                   4078: 
                   4079: sub definerole {
                   4080:   if (allowed('mcr','/')) {
                   4081:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 4082:     foreach my $role (split(':',$sysrole)) {
                   4083: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4084:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   4085:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   4086: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4087:                return "refused:s:$crole&$cqual"; 
                   4088:             }
                   4089:         }
1.191     harris41 4090:     }
1.800     albertel 4091:     foreach my $role (split(':',$domrole)) {
                   4092: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4093:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   4094:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   4095: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      4096:                return "refused:d:$crole&$cqual"; 
                   4097:             }
                   4098:         }
1.191     harris41 4099:     }
1.800     albertel 4100:     foreach my $role (split(':',$courole)) {
                   4101: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4102:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   4103:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   4104: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4105:                return "refused:c:$crole&$cqual"; 
                   4106:             }
                   4107:         }
1.191     harris41 4108:     }
1.620     albertel 4109:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   4110:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4111: 	        "rolesdef_$rolename=".
                   4112:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 4113:     return reply($command,$env{'user.home'});
1.12      www      4114:   } else {
                   4115:     return 'refused';
                   4116:   }
1.105     harris41 4117: }
                   4118: 
                   4119: # ---------------- Make a metadata query against the network of library servers
                   4120: 
                   4121: sub metadata_query {
1.244     matthew  4122:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 4123:     my %rhash;
1.244     matthew  4124:     my @server_list = (defined($server_array) ? @$server_array
                   4125:                                               : keys(%libserv) );
                   4126:     for my $server (@server_list) {
1.118     harris41 4127: 	unless ($custom or $customshow) {
                   4128: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   4129: 	    $rhash{$server}=$reply;
                   4130: 	}
                   4131: 	else {
                   4132: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   4133: 			     &escape($custom).':'.&escape($customshow),
                   4134: 			     $server);
                   4135: 	    $rhash{$server}=$reply;
                   4136: 	}
1.112     harris41 4137:     }
1.118     harris41 4138:     return \%rhash;
1.240     www      4139: }
                   4140: 
                   4141: # ----------------------------------------- Send log queries and wait for reply
                   4142: 
                   4143: sub log_query {
                   4144:     my ($uname,$udom,$query,%filters)=@_;
                   4145:     my $uhome=&homeserver($uname,$udom);
                   4146:     if ($uhome eq 'no_host') { return 'error: no_host'; }
                   4147:     my $uhost=$hostname{$uhome};
1.800     albertel 4148:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      4149:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   4150:                        $uhome);
1.479     albertel 4151:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      4152:     return get_query_reply($queryid);
                   4153: }
                   4154: 
1.818     raeburn  4155: # -------------------------- Update MySQL table for portfolio file
                   4156: 
                   4157: sub update_portfolio_table {
1.821     raeburn  4158:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.818     raeburn  4159:     my $homeserver = &homeserver($uname,$udom);
                   4160:     my $queryid=
1.821     raeburn  4161:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   4162:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  4163:     my $reply = &get_query_reply($queryid);
                   4164:     return $reply;
                   4165: }
                   4166: 
1.508     raeburn  4167: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  4168: 
                   4169: sub fetch_enrollment_query {
1.511     raeburn  4170:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  4171:     my $homeserver;
1.547     raeburn  4172:     my $maxtries = 1;
1.508     raeburn  4173:     if ($context eq 'automated') {
                   4174:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  4175:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  4176:     } else {
                   4177:         $homeserver = &homeserver($cnum,$dom);
                   4178:     }
1.506     raeburn  4179:     my $host=$hostname{$homeserver};
                   4180:     my $cmd = '';
1.800     albertel 4181:     foreach my $affiliate (keys %{$affiliatesref}) {
                   4182:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  4183:     }
                   4184:     $cmd =~ s/%%$//;
                   4185:     $cmd = &escape($cmd);
                   4186:     my $query = 'fetchenrollment';
1.620     albertel 4187:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  4188:     unless ($queryid=~/^\Q$host\E\_/) { 
                   4189:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   4190:         return 'error: '.$queryid;
                   4191:     }
1.506     raeburn  4192:     my $reply = &get_query_reply($queryid);
1.547     raeburn  4193:     my $tries = 1;
                   4194:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4195:         $reply = &get_query_reply($queryid);
                   4196:         $tries ++;
                   4197:     }
1.526     raeburn  4198:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 4199:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  4200:     } else {
1.515     raeburn  4201:         my @responses = split/:/,$reply;
                   4202:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 4203:             foreach my $line (@responses) {
                   4204:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  4205:                 $$replyref{$key} = $value;
                   4206:             }
                   4207:         } else {
1.506     raeburn  4208:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 4209:             foreach my $line (@responses) {
                   4210:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  4211:                 $$replyref{$key} = $value;
                   4212:                 if ($value > 0) {
1.800     albertel 4213:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   4214:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  4215:                         my $destname = $pathname.'/'.$filename;
                   4216:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  4217:                         if ($xml_classlist =~ /^error/) {
                   4218:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   4219:                         } else {
1.506     raeburn  4220:                             if ( open(FILE,">$destname") ) {
                   4221:                                 print FILE &unescape($xml_classlist);
                   4222:                                 close(FILE);
1.526     raeburn  4223:                             } else {
                   4224:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  4225:                             }
                   4226:                         }
                   4227:                     }
                   4228:                 }
                   4229:             }
                   4230:         }
                   4231:         return 'ok';
                   4232:     }
                   4233:     return 'error';
                   4234: }
                   4235: 
1.242     www      4236: sub get_query_reply {
                   4237:     my $queryid=shift;
1.240     www      4238:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   4239:     my $reply='';
                   4240:     for (1..100) {
                   4241: 	sleep 2;
                   4242:         if (-e $replyfile.'.end') {
1.448     albertel 4243: 	    if (open(my $fh,$replyfile)) {
1.240     www      4244:                $reply.=<$fh>;
1.448     albertel 4245:                close($fh);
1.240     www      4246: 	   } else { return 'error: reply_file_error'; }
1.242     www      4247:            return &unescape($reply);
                   4248: 	}
1.240     www      4249:     }
1.242     www      4250:     return 'timeout:'.$queryid;
1.240     www      4251: }
                   4252: 
                   4253: sub courselog_query {
1.241     www      4254: #
                   4255: # possible filters:
                   4256: # url: url or symb
                   4257: # username
                   4258: # domain
                   4259: # action: view, submit, grade
                   4260: # start: timestamp
                   4261: # end: timestamp
                   4262: #
1.240     www      4263:     my (%filters)=@_;
1.620     albertel 4264:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      4265:     if ($filters{'url'}) {
                   4266: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   4267:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   4268:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   4269:     }
1.620     albertel 4270:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4271:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      4272:     return &log_query($cname,$cdom,'courselog',%filters);
                   4273: }
                   4274: 
                   4275: sub userlog_query {
                   4276:     my ($uname,$udom,%filters)=@_;
                   4277:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      4278: }
                   4279: 
1.506     raeburn  4280: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   4281: 
                   4282: sub auto_run {
1.508     raeburn  4283:     my ($cnum,$cdom) = @_;
                   4284:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4285:     my $response = &reply('autorun:'.$cdom,$homeserver);
1.506     raeburn  4286:     return $response;
                   4287: }
1.776     albertel 4288: 
1.506     raeburn  4289: sub auto_get_sections {
1.508     raeburn  4290:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   4291:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  4292:     my @secs = ();
1.511     raeburn  4293:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  4294:     unless ($response eq 'refused') {
                   4295:         @secs = split/:/,$response;
                   4296:     }
                   4297:     return @secs;
                   4298: }
1.776     albertel 4299: 
1.506     raeburn  4300: sub auto_new_course {
1.508     raeburn  4301:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   4302:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  4303:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  4304:     return $response;
                   4305: }
1.776     albertel 4306: 
1.506     raeburn  4307: sub auto_validate_courseID {
1.508     raeburn  4308:     my ($cnum,$cdom,$inst_course_id) = @_;
                   4309:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4310:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  4311:     return $response;
                   4312: }
1.776     albertel 4313: 
1.506     raeburn  4314: sub auto_create_password {
1.508     raeburn  4315:     my ($cnum,$cdom,$authparam) = @_;
                   4316:     my $homeserver = &homeserver($cnum,$cdom); 
1.506     raeburn  4317:     my $create_passwd = 0;
                   4318:     my $authchk = '';
1.511     raeburn  4319:     my $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
1.506     raeburn  4320:     if ($response eq 'refused') {
                   4321:         $authchk = 'refused';
                   4322:     } else {
                   4323:         ($authparam,$create_passwd,$authchk) = split/:/,$response;
                   4324:     }
                   4325:     return ($authparam,$create_passwd,$authchk);
                   4326: }
                   4327: 
1.706     raeburn  4328: sub auto_photo_permission {
                   4329:     my ($cnum,$cdom,$students) = @_;
                   4330:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 4331:     my ($outcome,$perm_reqd,$conditions) = 
                   4332: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 4333:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4334: 	return (undef,undef);
                   4335:     }
1.706     raeburn  4336:     return ($outcome,$perm_reqd,$conditions);
                   4337: }
                   4338: 
                   4339: sub auto_checkphotos {
                   4340:     my ($uname,$udom,$pid) = @_;
                   4341:     my $homeserver = &homeserver($uname,$udom);
                   4342:     my ($result,$resulttype);
                   4343:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 4344: 				   &escape($uname).':'.&escape($pid),
                   4345: 				   $homeserver));
1.709     albertel 4346:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4347: 	return (undef,undef);
                   4348:     }
1.706     raeburn  4349:     if ($outcome) {
                   4350:         ($result,$resulttype) = split(/:/,$outcome);
                   4351:     } 
                   4352:     return ($result,$resulttype);
                   4353: }
                   4354: 
                   4355: sub auto_photochoice {
                   4356:     my ($cnum,$cdom) = @_;
                   4357:     my $homeserver = &homeserver($cnum,$cdom);
                   4358:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 4359: 						       &escape($cdom),
                   4360: 						       $homeserver)));
1.709     albertel 4361:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4362: 	return (undef,undef);
                   4363:     }
1.706     raeburn  4364:     return ($update,$comment);
                   4365: }
                   4366: 
                   4367: sub auto_photoupdate {
                   4368:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   4369:     my $homeserver = &homeserver($cnum,$dom);
                   4370:     my $host=$hostname{$homeserver};
                   4371:     my $cmd = '';
                   4372:     my $maxtries = 1;
1.800     albertel 4373:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   4374:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  4375:     }
                   4376:     $cmd =~ s/%%$//;
                   4377:     $cmd = &escape($cmd);
                   4378:     my $query = 'institutionalphotos';
                   4379:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   4380:     unless ($queryid=~/^\Q$host\E\_/) {
                   4381:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   4382:         return 'error: '.$queryid;
                   4383:     }
                   4384:     my $reply = &get_query_reply($queryid);
                   4385:     my $tries = 1;
                   4386:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4387:         $reply = &get_query_reply($queryid);
                   4388:         $tries ++;
                   4389:     }
                   4390:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   4391:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   4392:     } else {
                   4393:         my @responses = split(/:/,$reply);
                   4394:         my $outcome = shift(@responses); 
                   4395:         foreach my $item (@responses) {
                   4396:             my ($key,$value) = split(/=/,$item);
                   4397:             $$photo{$key} = $value;
                   4398:         }
                   4399:         return $outcome;
                   4400:     }
                   4401:     return 'error';
                   4402: }
                   4403: 
1.521     raeburn  4404: sub auto_instcode_format {
1.793     albertel 4405:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   4406: 	$cat_order) = @_;
1.521     raeburn  4407:     my $courses = '';
1.772     raeburn  4408:     my @homeservers;
1.521     raeburn  4409:     if ($caller eq 'global') {
1.793     albertel 4410:         foreach my $tryserver (keys(%libserv)) {
1.584     raeburn  4411:             if ($hostdom{$tryserver} eq $codedom) {
1.793     albertel 4412:                 if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
1.772     raeburn  4413:                     push(@homeservers,$tryserver);
                   4414:                 }
1.584     raeburn  4415:             }
                   4416:         }
1.521     raeburn  4417:     } else {
1.772     raeburn  4418:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  4419:     }
1.793     albertel 4420:     foreach my $code (keys(%{$instcodes})) {
                   4421:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  4422:     }
                   4423:     chop($courses);
1.772     raeburn  4424:     my $ok_response = 0;
                   4425:     my $response;
                   4426:     while (@homeservers > 0 && $ok_response == 0) {
                   4427:         my $server = shift(@homeservers); 
                   4428:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   4429:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   4430:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.793     albertel 4431: 		split/:/,$response;
1.772     raeburn  4432:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   4433:             push(@{$codetitles},&str2array($codetitles_str));
                   4434:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   4435:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   4436:             $ok_response = 1;
                   4437:         }
                   4438:     }
                   4439:     if ($ok_response) {
1.521     raeburn  4440:         return 'ok';
1.772     raeburn  4441:     } else {
                   4442:         return $response;
1.521     raeburn  4443:     }
                   4444: }
                   4445: 
1.792     raeburn  4446: sub auto_instcode_defaults {
                   4447:     my ($domain,$returnhash,$code_order) = @_;
                   4448:     my @homeservers;
1.793     albertel 4449:     foreach my $tryserver (keys(%libserv)) {
1.792     raeburn  4450:         if ($hostdom{$tryserver} eq $domain) {
1.793     albertel 4451:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
1.792     raeburn  4452:                 push(@homeservers,$tryserver);
                   4453:             }
                   4454:         }
                   4455:     }
                   4456:     my $ok_response = 0;
                   4457:     my $response;
                   4458:     while (@homeservers > 0 && $ok_response == 0) {
                   4459:         my $server = shift(@homeservers);
                   4460:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
                   4461:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
1.793     albertel 4462:             foreach my $pair (split(/\&/,$response)) {
                   4463:                 my ($name,$value)=split(/\=/,$pair);
1.792     raeburn  4464:                 if ($name eq 'code_order') {
1.796     raeburn  4465:                     @{$code_order} = split(/\&/,&unescape($value));
1.792     raeburn  4466:                 } else {
1.796     raeburn  4467:                     $returnhash->{&unescape($name)}=&unescape($value);
1.792     raeburn  4468:                 }
                   4469:             }
1.804     raeburn  4470:             $ok_response = 1;
1.792     raeburn  4471:         }
                   4472:     }
                   4473:     if ($ok_response) {
                   4474:         return 'ok';
                   4475:     } else {
                   4476:         return $response;
                   4477:     }
                   4478: } 
                   4479: 
1.777     albertel 4480: sub auto_validate_class_sec {
1.773     raeburn  4481:     my ($cdom,$cnum,$owner,$inst_class) = @_;
                   4482:     my $homeserver = &homeserver($cnum,$cdom);
                   4483:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.774     banghart 4484:                         &escape($owner).':'.$cdom,$homeserver);
1.773     raeburn  4485:     return $response;
                   4486: }
                   4487: 
1.679     raeburn  4488: # ------------------------------------------------------- Course Group routines
                   4489: 
                   4490: sub get_coursegroups {
1.809     raeburn  4491:     my ($cdom,$cnum,$group,$namespace) = @_;
                   4492:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  4493: }
                   4494: 
1.679     raeburn  4495: sub modify_coursegroup {
                   4496:     my ($cdom,$cnum,$groupsettings) = @_;
                   4497:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   4498: }
                   4499: 
1.809     raeburn  4500: sub toggle_coursegroup_status {
                   4501:     my ($cdom,$cnum,$group,$action) = @_;
                   4502:     my ($from_namespace,$to_namespace);
                   4503:     if ($action eq 'delete') {
                   4504:         $from_namespace = 'coursegroups';
                   4505:         $to_namespace = 'deleted_groups';
                   4506:     } else {
                   4507:         $from_namespace = 'deleted_groups';
                   4508:         $to_namespace = 'coursegroups';
                   4509:     }
                   4510:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  4511:     if (my $tmp = &error(%curr_group)) {
                   4512:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   4513:         return ('read error',$tmp);
                   4514:     } else {
                   4515:         my %savedsettings = %curr_group; 
1.809     raeburn  4516:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  4517:         my $deloutcome;
                   4518:         if ($result eq 'ok') {
1.809     raeburn  4519:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  4520:         } else {
                   4521:             return ('write error',$result);
                   4522:         }
                   4523:         if ($deloutcome eq 'ok') {
                   4524:             return 'ok';
                   4525:         } else {
                   4526:             return ('delete error',$deloutcome);
                   4527:         }
                   4528:     }
                   4529: }
                   4530: 
1.679     raeburn  4531: sub modify_group_roles {
                   4532:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
                   4533:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   4534:     my $role = 'gr/'.&escape($userprivs);
                   4535:     my ($uname,$udom) = split(/:/,$user);
                   4536:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
1.684     raeburn  4537:     if ($result eq 'ok') {
                   4538:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   4539:     }
1.679     raeburn  4540:     return $result;
                   4541: }
                   4542: 
                   4543: sub modify_coursegroup_membership {
                   4544:     my ($cdom,$cnum,$membership) = @_;
                   4545:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   4546:     return $result;
                   4547: }
                   4548: 
1.682     raeburn  4549: sub get_active_groups {
                   4550:     my ($udom,$uname,$cdom,$cnum) = @_;
                   4551:     my $now = time;
                   4552:     my %groups = ();
                   4553:     foreach my $key (keys(%env)) {
1.811     albertel 4554:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  4555:             my ($start,$end) = split(/\./,$env{$key});
                   4556:             if (($end!=0) && ($end<$now)) { next; }
                   4557:             if (($start!=0) && ($start>$now)) { next; }
                   4558:             if ($1 eq $cdom && $2 eq $cnum) {
                   4559:                 $groups{$3} = $env{$key} ;
                   4560:             }
                   4561:         }
                   4562:     }
                   4563:     return %groups;
                   4564: }
                   4565: 
1.683     raeburn  4566: sub get_group_membership {
                   4567:     my ($cdom,$cnum,$group) = @_;
                   4568:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   4569: }
                   4570: 
                   4571: sub get_users_groups {
                   4572:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  4573:     my @usersgroups;
1.683     raeburn  4574:     my $cachetime=1800;
                   4575: 
                   4576:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  4577:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   4578:     if (defined($cached)) {
1.734     albertel 4579:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  4580:     } else {  
                   4581:         $grouplist = '';
1.816     raeburn  4582:         my $courseurl = &courseid_to_courseurl($courseid);
                   4583:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  4584:         my $access_end = $env{'course.'.$courseid.
                   4585:                               '.default_enrollment_end_date'};
                   4586:         my $now = time;
                   4587:         foreach my $key (keys(%roleshash)) {
                   4588:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   4589:                 my $group = $1;
                   4590:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   4591:                     my $start = $2;
                   4592:                     my $end = $1;
                   4593:                     if ($start == -1) { next; } # deleted from group
                   4594:                     if (($start!=0) && ($start>$now)) { next; }
                   4595:                     if (($end!=0) && ($end<$now)) {
                   4596:                         if ($access_end && $access_end < $now) {
                   4597:                             if ($access_end - $end < 86400) {
                   4598:                                 push(@usersgroups,$group);
1.733     raeburn  4599:                             }
                   4600:                         }
1.817     raeburn  4601:                         next;
1.733     raeburn  4602:                     }
1.817     raeburn  4603:                     push(@usersgroups,$group);
1.683     raeburn  4604:                 }
                   4605:             }
                   4606:         }
1.817     raeburn  4607:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   4608:         $grouplist = join(':',@usersgroups);
                   4609:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  4610:     }
1.733     raeburn  4611:     return @usersgroups;
1.683     raeburn  4612: }
                   4613: 
                   4614: sub devalidate_getgroups_cache {
                   4615:     my ($udom,$uname,$cdom,$cnum)=@_;
                   4616:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 4617: 
1.683     raeburn  4618:     my $hashid="$udom:$uname:$courseid";
                   4619:     &devalidate_cache_new('getgroups',$hashid);
                   4620: }
                   4621: 
1.12      www      4622: # ------------------------------------------------------------------ Plain Text
                   4623: 
                   4624: sub plaintext {
1.742     raeburn  4625:     my ($short,$type,$cid) = @_;
1.758     albertel 4626:     if ($short =~ /^cr/) {
                   4627: 	return (split('/',$short))[-1];
                   4628:     }
1.742     raeburn  4629:     if (!defined($cid)) {
                   4630:         $cid = $env{'request.course.id'};
                   4631:     }
                   4632:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
                   4633:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
                   4634:                                           '.plaintext'});
                   4635:     }
                   4636:     my %rolenames = (
                   4637:                       Course => 'std',
                   4638:                       Group => 'alt1',
                   4639:                     );
                   4640:     if (defined($type) && 
                   4641:          defined($rolenames{$type}) && 
                   4642:          defined($prp{$short}{$rolenames{$type}})) {
                   4643:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   4644:     } else {
                   4645:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   4646:     }
1.12      www      4647: }
                   4648: 
                   4649: # ----------------------------------------------------------------- Assign Role
                   4650: 
                   4651: sub assignrole {
1.357     www      4652:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
1.21      www      4653:     my $mrole;
                   4654:     if ($role =~ /^cr\//) {
1.393     www      4655:         my $cwosec=$url;
1.811     albertel 4656:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      4657: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      4658:            &logthis('Refused custom assignrole: '.
                   4659:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4660: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4661:            return 'refused'; 
                   4662:         }
1.21      www      4663:         $mrole='cr';
1.678     raeburn  4664:     } elsif ($role =~ /^gr\//) {
                   4665:         my $cwogrp=$url;
1.811     albertel 4666:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  4667:         unless (&allowed('mdg',$cwogrp)) {
                   4668:             &logthis('Refused group assignrole: '.
                   4669:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   4670:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   4671:             return 'refused';
                   4672:         }
                   4673:         $mrole='gr';
1.21      www      4674:     } else {
1.82      www      4675:         my $cwosec=$url;
1.811     albertel 4676:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.373     www      4677:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
1.104     www      4678:            &logthis('Refused assignrole: '.
                   4679:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4680: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4681:            return 'refused'; 
                   4682:         }
1.21      www      4683:         $mrole=$role;
                   4684:     }
1.620     albertel 4685:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4686:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      4687:     if ($end) { $command.='_'.$end; }
1.21      www      4688:     if ($start) {
                   4689: 	if ($end) { 
1.81      www      4690:            $command.='_'.$start; 
1.21      www      4691:         } else {
1.81      www      4692:            $command.='_0_'.$start;
1.21      www      4693:         }
                   4694:     }
1.739     raeburn  4695:     my $origstart = $start;
                   4696:     my $origend = $end;
1.357     www      4697: # actually delete
                   4698:     if ($deleteflag) {
1.373     www      4699: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      4700: # modify command to delete the role
1.620     albertel 4701:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      4702:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 4703: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      4704: # set start and finish to negative values for userrolelog
                   4705:            $start=-1;
                   4706:            $end=-1;
                   4707:         }
                   4708:     }
                   4709: # send command
1.349     www      4710:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      4711: # log new user role if status is ok
1.349     www      4712:     if ($answer eq 'ok') {
1.663     raeburn  4713: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  4714: # for course roles, perform group memberships changes triggered by role change.
                   4715:         unless ($role =~ /^gr/) {
                   4716:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   4717:                                              $origstart);
                   4718:         }
1.349     www      4719:     }
                   4720:     return $answer;
1.169     harris41 4721: }
                   4722: 
                   4723: # -------------------------------------------------- Modify user authentication
1.197     www      4724: # Overrides without validation
                   4725: 
1.169     harris41 4726: sub modifyuserauth {
                   4727:     my ($udom,$uname,$umode,$upass)=@_;
                   4728:     my $uhome=&homeserver($uname,$udom);
1.197     www      4729:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   4730:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 4731:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4732:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 4733:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   4734: 		     &escape($upass),$uhome);
1.620     albertel 4735:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      4736:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   4737:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   4738:     &log($udom,,$uname,$uhome,
1.620     albertel 4739:         'Authentication changed by '.$env{'user.domain'}.', '.
                   4740:                                      $env{'user.name'}.', '.$umode.
1.197     www      4741:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 4742:     unless ($reply eq 'ok') {
1.197     www      4743:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 4744: 	return 'error: '.$reply;
                   4745:     }   
1.170     harris41 4746:     return 'ok';
1.80      www      4747: }
                   4748: 
1.81      www      4749: # --------------------------------------------------------------- Modify a user
1.80      www      4750: 
1.81      www      4751: sub modifyuser {
1.206     matthew  4752:     my ($udom,    $uname, $uid,
                   4753:         $umode,   $upass, $first,
                   4754:         $middle,  $last,  $gene,
1.387     www      4755:         $forceid, $desiredhome, $email)=@_;
1.807     albertel 4756:     $udom= &LONCAPA::clean_domain($udom);
                   4757:     $uname=&LONCAPA::clean_username($uname);
1.81      www      4758:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4759:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  4760: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   4761:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   4762:                                      ' desiredhome not specified'). 
1.620     albertel 4763:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4764:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 4765:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      4766: # ----------------------------------------------------------------- Create User
1.406     albertel 4767:     if (($uhome eq 'no_host') && 
                   4768: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      4769:         my $unhome='';
1.209     matthew  4770:         if (defined($desiredhome) && $hostdom{$desiredhome} eq $udom) { 
                   4771:             $unhome = $desiredhome;
1.620     albertel 4772: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   4773: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  4774:         } else { # load balancing routine for determining $unhome
1.80      www      4775:             my $tryserver;
1.81      www      4776:             my $loadm=10000000;
1.80      www      4777:             foreach $tryserver (keys %libserv) {
                   4778: 	       if ($hostdom{$tryserver} eq $udom) {
                   4779:                   my $answer=reply('load',$tryserver);
                   4780:                   if (($answer=~/\d+/) && ($answer<$loadm)) {
                   4781: 		      $loadm=$answer;
                   4782:                       $unhome=$tryserver;
                   4783:                   }
                   4784: 	       }
                   4785: 	    }
                   4786:         }
                   4787:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  4788: 	    return 'error: unable to find a home server for '.$uname.
                   4789:                    ' in domain '.$udom;
1.80      www      4790:         }
                   4791:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   4792:                          &escape($upass),$unhome);
                   4793: 	unless ($reply eq 'ok') {
                   4794:             return 'error: '.$reply;
                   4795:         }   
1.230     stredwic 4796:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      4797:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  4798: 	    return 'error: unable verify users home machine.';
1.80      www      4799:         }
1.209     matthew  4800:     }   # End of creation of new user
1.80      www      4801: # ---------------------------------------------------------------------- Add ID
                   4802:     if ($uid) {
                   4803:        $uid=~tr/A-Z/a-z/;
                   4804:        my %uidhash=&idrget($udom,$uname);
1.196     www      4805:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   4806:          && (!$forceid)) {
1.80      www      4807: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  4808: 	      return 'error: user id "'.$uid.'" does not match '.
                   4809:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      4810:           }
                   4811:        } else {
                   4812: 	  &idput($udom,($uname => $uid));
                   4813:        }
                   4814:     }
                   4815: # -------------------------------------------------------------- Add names, etc
1.313     matthew  4816:     my @tmp=&get('environment',
1.134     albertel 4817: 		   ['firstname','middlename','lastname','generation'],
                   4818: 		   $udom,$uname);
1.313     matthew  4819:     my %names;
                   4820:     if ($tmp[0] =~ m/^error:.*/) { 
                   4821:         %names=(); 
                   4822:     } else {
                   4823:         %names = @tmp;
                   4824:     }
1.388     www      4825: #
                   4826: # Make sure to not trash student environment if instructor does not bother
                   4827: # to supply name and email information
                   4828: #
                   4829:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  4830:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      4831:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  4832:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      4833:     if ($email) {
                   4834:        $email=~s/[^\w\@\.\-\,]//gs;
                   4835:        if ($email=~/\@/) { $names{'notification'} = $email;
                   4836: 			   $names{'critnotification'} = $email;
                   4837: 			   $names{'permanentemail'} = $email; }
                   4838:     }
1.134     albertel 4839:     my $reply = &put('environment', \%names, $udom,$uname);
                   4840:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.680     www      4841:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.81      www      4842:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4843:              $umode.', '.$first.', '.$middle.', '.
                   4844: 	     $last.', '.$gene.' by '.
1.620     albertel 4845:              $env{'user.name'}.' at '.$env{'user.domain'});
1.134     albertel 4846:     return 'ok';
1.80      www      4847: }
                   4848: 
1.81      www      4849: # -------------------------------------------------------------- Modify student
1.80      www      4850: 
1.81      www      4851: sub modifystudent {
                   4852:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.515     raeburn  4853:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
1.455     albertel 4854:     if (!$cid) {
1.620     albertel 4855: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 4856: 	    return 'not_in_class';
                   4857: 	}
1.80      www      4858:     }
                   4859: # --------------------------------------------------------------- Make the user
1.81      www      4860:     my $reply=&modifyuser
1.209     matthew  4861: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      4862:          $desiredhome,$email);
1.80      www      4863:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  4864:     # This will cause &modify_student_enrollment to get the uid from the
                   4865:     # students environment
                   4866:     $uid = undef if (!$forceid);
1.455     albertel 4867:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.515     raeburn  4868: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
1.297     matthew  4869:     return $reply;
                   4870: }
                   4871: 
                   4872: sub modify_student_enrollment {
1.515     raeburn  4873:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
1.455     albertel 4874:     my ($cdom,$cnum,$chome);
                   4875:     if (!$cid) {
1.620     albertel 4876: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 4877: 	    return 'not_in_class';
                   4878: 	}
1.620     albertel 4879: 	$cdom=$env{'course.'.$cid.'.domain'};
                   4880: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 4881:     } else {
                   4882: 	($cdom,$cnum)=split(/_/,$cid);
                   4883:     }
1.620     albertel 4884:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 4885:     if (!$chome) {
1.457     raeburn  4886: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  4887:     }
1.455     albertel 4888:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  4889:     # Make sure the user exists
1.81      www      4890:     my $uhome=&homeserver($uname,$udom);
                   4891:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   4892: 	return 'error: no such user';
                   4893:     }
1.297     matthew  4894:     # Get student data if we were not given enough information
                   4895:     if (!defined($first)  || $first  eq '' || 
                   4896:         !defined($last)   || $last   eq '' || 
                   4897:         !defined($uid)    || $uid    eq '' || 
                   4898:         !defined($middle) || $middle eq '' || 
                   4899:         !defined($gene)   || $gene   eq '') {
1.294     matthew  4900:         # They did not supply us with enough data to enroll the student, so
                   4901:         # we need to pick up more information.
1.297     matthew  4902:         my %tmp = &get('environment',
1.294     matthew  4903:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  4904:                        ,$udom,$uname);
                   4905: 
1.800     albertel 4906:         #foreach my $key (keys(%tmp)) {
                   4907:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 4908:         #}
1.294     matthew  4909:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   4910:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   4911:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  4912:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  4913:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   4914:     }
1.556     albertel 4915:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 4916:     my $reply=cput('classlist',
                   4917: 		   {"$uname:$udom" => 
1.515     raeburn  4918: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 4919: 		   $cdom,$cnum);
1.81      www      4920:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   4921: 	return 'error: '.$reply;
1.652     albertel 4922:     } else {
                   4923: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      4924:     }
1.297     matthew  4925:     # Add student role to user
1.83      www      4926:     my $uurl='/'.$cid;
1.81      www      4927:     $uurl=~s/\_/\//g;
                   4928:     if ($usec) {
                   4929: 	$uurl.='/'.$usec;
                   4930:     }
                   4931:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21      www      4932: }
                   4933: 
1.556     albertel 4934: sub format_name {
                   4935:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   4936:     my $name;
                   4937:     if ($first ne 'lastname') {
                   4938: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   4939:     } else {
                   4940: 	if ($lastname=~/\S/) {
                   4941: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   4942: 	    $name=~s/\s+,/,/;
                   4943: 	} else {
                   4944: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   4945: 	}
                   4946:     }
                   4947:     $name=~s/^\s+//;
                   4948:     $name=~s/\s+$//;
                   4949:     $name=~s/\s+/ /g;
                   4950:     return $name;
                   4951: }
                   4952: 
1.84      www      4953: # ------------------------------------------------- Write to course preferences
                   4954: 
                   4955: sub writecoursepref {
                   4956:     my ($courseid,%prefs)=@_;
                   4957:     $courseid=~s/^\///;
                   4958:     $courseid=~s/\_/\//g;
                   4959:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   4960:     my $chome=homeserver($cnum,$cdomain);
                   4961:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   4962: 	return 'error: no such course';
                   4963:     }
                   4964:     my $cstring='';
1.800     albertel 4965:     foreach my $pref (keys(%prefs)) {
                   4966: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 4967:     }
1.84      www      4968:     $cstring=~s/\&$//;
                   4969:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   4970: }
                   4971: 
                   4972: # ---------------------------------------------------------- Make/modify course
                   4973: 
                   4974: sub createcourse {
1.741     raeburn  4975:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
                   4976:         $course_owner,$crstype)=@_;
1.84      www      4977:     $url=&declutter($url);
                   4978:     my $cid='';
1.264     matthew  4979:     unless (&allowed('ccc',$udom)) {
1.84      www      4980:         return 'refused';
                   4981:     }
                   4982: # ------------------------------------------------------------------- Create ID
1.674     www      4983:    my $uname=int(1+rand(9)).
                   4984:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   4985:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      4986:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   4987: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 4988:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      4989:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   4990:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   4991:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 4992:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      4993:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   4994:            return 'error: unable to generate unique course-ID';
                   4995:        } 
                   4996:    }
1.264     matthew  4997: # ------------------------------------------------ Check supplied server name
1.620     albertel 4998:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.264     matthew  4999:     if (! exists($libserv{$course_server})) {
                   5000:         return 'error:bad server name '.$course_server;
                   5001:     }
1.84      www      5002: # ------------------------------------------------------------- Make the course
                   5003:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  5004:                       $course_server);
1.84      www      5005:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 5006:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      5007:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5008: 	return 'error: no such course';
                   5009:     }
1.271     www      5010: # ----------------------------------------------------------------- Course made
1.516     raeburn  5011: # log existence
                   5012:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
1.741     raeburn  5013:                  ':'.&escape($inst_code).':'.&escape($course_owner).':'.
                   5014:                   &escape($crstype),$uhome);
1.358     www      5015:     &flushcourselogs();
                   5016: # set toplevel url
1.271     www      5017:     my $topurl=$url;
                   5018:     unless ($nonstandard) {
                   5019: # ------------------------------------------ For standard courses, make top url
                   5020:         my $mapurl=&clutter($url);
1.278     www      5021:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 5022:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      5023: <map>
                   5024: <resource id="1" type="start"></resource>
                   5025: <resource id="2" src="$mapurl"></resource>
                   5026: <resource id="3" type="finish"></resource>
                   5027: <link index="1" from="1" to="2"></link>
                   5028: <link index="2" from="2" to="3"></link>
                   5029: </map>
                   5030: ENDINITMAP
                   5031:         $topurl=&declutter(
1.638     albertel 5032:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      5033:                           );
                   5034:     }
                   5035: # ----------------------------------------------------------- Write preferences
1.84      www      5036:     &writecoursepref($udom.'_'.$uname,
                   5037:                      ('description' => $description,
1.271     www      5038:                       'url'         => $topurl));
1.84      www      5039:     return '/'.$udom.'/'.$uname;
                   5040: }
                   5041: 
1.813     albertel 5042: sub is_course {
                   5043:     my ($cdom,$cnum) = @_;
                   5044:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
                   5045: 				undef,'.');
                   5046:     if (exists($courses{$cdom.'_'.$cnum})) {
                   5047:         return 1;
                   5048:     }
                   5049:     return 0;
                   5050: }
                   5051: 
1.21      www      5052: # ---------------------------------------------------------- Assign Custom Role
                   5053: 
                   5054: sub assigncustomrole {
1.357     www      5055:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21      www      5056:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357     www      5057:                        $end,$start,$deleteflag);
1.21      www      5058: }
                   5059: 
                   5060: # ----------------------------------------------------------------- Revoke Role
                   5061: 
                   5062: sub revokerole {
1.357     www      5063:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21      www      5064:     my $now=time;
1.357     www      5065:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21      www      5066: }
                   5067: 
                   5068: # ---------------------------------------------------------- Revoke Custom Role
                   5069: 
                   5070: sub revokecustomrole {
1.357     www      5071:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21      www      5072:     my $now=time;
1.357     www      5073:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
                   5074:            $deleteflag);
1.17      www      5075: }
                   5076: 
1.533     banghart 5077: # ------------------------------------------------------------ Disk usage
1.535     albertel 5078: sub diskusage {
1.533     banghart 5079:     my ($udom,$uname,$directoryRoot)=@_;
                   5080:     $directoryRoot =~ s/\/$//;
1.535     albertel 5081:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
1.514     albertel 5082:     return $listing;
1.512     banghart 5083: }
                   5084: 
1.566     banghart 5085: sub is_locked {
                   5086:     my ($file_name, $domain, $user) = @_;
                   5087:     my @check;
                   5088:     my $is_locked;
                   5089:     push @check, $file_name;
1.613     albertel 5090:     my %locked = &get('file_permissions',\@check,
1.620     albertel 5091: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 5092:     my ($tmp)=keys(%locked);
                   5093:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  5094:     
1.566     banghart 5095:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  5096:         $is_locked = 'false';
                   5097:         foreach my $entry (@{$locked{$file_name}}) {
                   5098:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  5099:                $is_locked = 'true';
                   5100:                last;
1.745     raeburn  5101:            }
                   5102:        }
1.566     banghart 5103:     } else {
                   5104:         $is_locked = 'false';
                   5105:     }
                   5106: }
                   5107: 
1.759     albertel 5108: sub declutter_portfile {
                   5109:     my ($file) = @_;
                   5110:     &logthis("got $file");
                   5111:     $file =~ s-^(/portfolio/|portfolio/)-/-;
                   5112:     &logthis("ret $file");
                   5113:     return $file;
                   5114: }
                   5115: 
1.559     banghart 5116: # ------------------------------------------------------------- Mark as Read Only
                   5117: 
                   5118: sub mark_as_readonly {
                   5119:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 5120:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5121:     my ($tmp)=keys(%current_permissions);
                   5122:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 5123:     foreach my $file (@{$files}) {
1.759     albertel 5124: 	$file = &declutter_portfile($file);
1.561     banghart 5125:         push(@{$current_permissions{$file}},$what);
1.559     banghart 5126:     }
1.613     albertel 5127:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5128:     return;
                   5129: }
                   5130: 
1.572     banghart 5131: # ------------------------------------------------------------Save Selected Files
                   5132: 
                   5133: sub save_selected_files {
                   5134:     my ($user, $path, @files) = @_;
                   5135:     my $filename = $user."savedfiles";
1.573     banghart 5136:     my @other_files = &files_not_in_path($user, $path);
1.574     banghart 5137:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 5138:     foreach my $file (@files) {
1.620     albertel 5139:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 5140:     }
                   5141:     foreach my $file (@other_files) {
1.574     banghart 5142:         print (OUT $file."\n");
1.572     banghart 5143:     }
1.574     banghart 5144:     close (OUT);
1.572     banghart 5145:     return 'ok';
                   5146: }
                   5147: 
1.574     banghart 5148: sub clear_selected_files {
                   5149:     my ($user) = @_;
                   5150:     my $filename = $user."savedfiles";
                   5151:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5152:     print (OUT undef);
                   5153:     close (OUT);
                   5154:     return ("ok");    
                   5155: }
                   5156: 
1.572     banghart 5157: sub files_in_path {
                   5158:     my ($user, $path) = @_;
                   5159:     my $filename = $user."savedfiles";
                   5160:     my %return_files;
1.574     banghart 5161:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 5162:     while (my $line_in = <IN>) {
1.574     banghart 5163:         chomp ($line_in);
                   5164:         my @paths_and_file = split (m!/!, $line_in);
                   5165:         my $file_part = pop (@paths_and_file);
                   5166:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 5167:         $path_part.='/';
                   5168:         my $path_and_file = $path_part.$file_part;
                   5169:         if ($path_part eq $path) {
                   5170:             $return_files{$file_part}= 'selected';
                   5171:         }
                   5172:     }
1.574     banghart 5173:     close (IN);
                   5174:     return (\%return_files);
1.572     banghart 5175: }
                   5176: 
                   5177: # called in portfolio select mode, to show files selected NOT in current directory
                   5178: sub files_not_in_path {
                   5179:     my ($user, $path) = @_;
                   5180:     my $filename = $user."savedfiles";
                   5181:     my @return_files;
                   5182:     my $path_part;
1.800     albertel 5183:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5184:     while (my $line = <IN>) {
1.572     banghart 5185:         #ok, I know it's clunky, but I want it to work
1.800     albertel 5186:         my @paths_and_file = split(m|/|, $line);
                   5187:         my $file_part = pop(@paths_and_file);
                   5188:         chomp($file_part);
                   5189:         my $path_part = join('/', @paths_and_file);
1.572     banghart 5190:         $path_part .= '/';
                   5191:         my $path_and_file = $path_part.$file_part;
                   5192:         if ($path_part ne $path) {
1.800     albertel 5193:             push(@return_files, ($path_and_file));
1.572     banghart 5194:         }
                   5195:     }
1.800     albertel 5196:     close(OUT);
1.574     banghart 5197:     return (@return_files);
1.572     banghart 5198: }
                   5199: 
1.745     raeburn  5200: #----------------------------------------------Get portfolio file permissions
1.629     banghart 5201: 
1.745     raeburn  5202: sub get_portfile_permissions {
                   5203:     my ($domain,$user) = @_;
1.613     albertel 5204:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5205:     my ($tmp)=keys(%current_permissions);
                   5206:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5207:     return \%current_permissions;
                   5208: }
                   5209: 
                   5210: #---------------------------------------------Get portfolio file access controls
                   5211: 
1.749     raeburn  5212: sub get_access_controls {
1.745     raeburn  5213:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 5214:     my %access;
                   5215:     my $real_file = $file;
                   5216:     $file =~ s/\.meta$//;
1.745     raeburn  5217:     if (defined($file)) {
1.749     raeburn  5218:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   5219:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 5220:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  5221:             }
                   5222:         }
1.745     raeburn  5223:     } else {
1.749     raeburn  5224:         foreach my $key (keys(%{$current_permissions})) {
                   5225:             if ($key =~ /\0accesscontrol$/) {
                   5226:                 if (defined($group)) {
                   5227:                     if ($key !~ m-^\Q$group\E/-) {
                   5228:                         next;
                   5229:                     }
                   5230:                 }
                   5231:                 my ($fullpath) = split(/\0/,$key);
                   5232:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   5233:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   5234:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   5235:                     }
                   5236:                 }
                   5237:             }
                   5238:         }
                   5239:     }
                   5240:     return %access;
                   5241: }
                   5242: 
                   5243: sub modify_access_controls {
                   5244:     my ($file_name,$changes,$domain,$user)=@_;
                   5245:     my ($outcome,$deloutcome);
                   5246:     my %store_permissions;
                   5247:     my %new_values;
                   5248:     my %new_control;
                   5249:     my %translation;
                   5250:     my @deletions = ();
                   5251:     my $now = time;
                   5252:     if (exists($$changes{'activate'})) {
                   5253:         if (ref($$changes{'activate'}) eq 'HASH') {
                   5254:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   5255:             my $numnew = scalar(@newitems);
                   5256:             for (my $i=0; $i<$numnew; $i++) {
                   5257:                 my $newkey = $newitems[$i];
                   5258:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  5259:                 if ($newkey =~ /^\d+:/) { 
                   5260:                     $newkey =~ s/^(\d+)/$newid/;
                   5261:                     $translation{$1} = $newid;
                   5262:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   5263:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   5264:                     $translation{$1} = $newid;
                   5265:                 }
1.749     raeburn  5266:                 $new_values{$file_name."\0".$newkey} = 
                   5267:                                           $$changes{'activate'}{$newitems[$i]};
                   5268:                 $new_control{$newkey} = $now;
                   5269:             }
                   5270:         }
                   5271:     }
                   5272:     my %todelete;
                   5273:     my %changed_items;
                   5274:     foreach my $action ('delete','update') {
                   5275:         if (exists($$changes{$action})) {
                   5276:             if (ref($$changes{$action}) eq 'HASH') {
                   5277:                 foreach my $key (keys(%{$$changes{$action}})) {
                   5278:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   5279:                     if ($action eq 'delete') { 
                   5280:                         $todelete{$itemnum} = 1;
                   5281:                     } else {
                   5282:                         $changed_items{$itemnum} = $key;
                   5283:                     }
                   5284:                 }
1.745     raeburn  5285:             }
                   5286:         }
1.749     raeburn  5287:     }
                   5288:     # get lock on access controls for file.
                   5289:     my $lockhash = {
                   5290:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   5291:                                                        ':'.$env{'user.domain'},
                   5292:                    }; 
                   5293:     my $tries = 0;
                   5294:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5295:    
                   5296:     while (($gotlock ne 'ok') && $tries <3) {
                   5297:         $tries ++;
                   5298:         sleep 1;
                   5299:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5300:     }
                   5301:     if ($gotlock eq 'ok') {
                   5302:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   5303:         my ($tmp)=keys(%curr_permissions);
                   5304:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   5305:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   5306:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   5307:             if (ref($curr_controls) eq 'HASH') {
                   5308:                 foreach my $control_item (keys(%{$curr_controls})) {
                   5309:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   5310:                     if (defined($todelete{$itemnum})) {
                   5311:                         push(@deletions,$file_name."\0".$control_item);
                   5312:                     } else {
                   5313:                         if (defined($changed_items{$itemnum})) {
                   5314:                             $new_control{$changed_items{$itemnum}} = $now;
                   5315:                             push(@deletions,$file_name."\0".$control_item);
                   5316:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   5317:                         } else {
                   5318:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   5319:                         }
                   5320:                     }
1.745     raeburn  5321:                 }
                   5322:             }
                   5323:         }
1.749     raeburn  5324:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   5325:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   5326:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   5327:         #  remove lock
                   5328:         my @del_lock = ($file_name."\0".'locked_access_records');
                   5329:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  5330:         my ($file,$group);
                   5331:         if (&is_course($domain,$user)) {
                   5332:             ($group,$file) = split(/\//,$file_name,2);
                   5333:         } else {
                   5334:             $file = $file_name;
                   5335:         }
                   5336:         my $sqlresult =
                   5337:             &update_portfolio_table($user,$domain,$file,'portfolio_access',
                   5338:                                     $group);
1.749     raeburn  5339:     } else {
                   5340:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  5341:     }
1.749     raeburn  5342:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  5343: }
                   5344: 
                   5345: #------------------------------------------------------Get Marked as Read Only
                   5346: 
                   5347: sub get_marked_as_readonly {
                   5348:     my ($domain,$user,$what,$group) = @_;
                   5349:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 5350:     my @readonly_files;
1.629     banghart 5351:     my $cmp1=$what;
                   5352:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  5353:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5354:         if (defined($group)) {
                   5355:             if ($file_name !~ m-^\Q$group\E/-) {
                   5356:                 next;
                   5357:             }
                   5358:         }
1.561     banghart 5359:         if (ref($value) eq "ARRAY"){
                   5360:             foreach my $stored_what (@{$value}) {
1.629     banghart 5361:                 my $cmp2=$stored_what;
1.759     albertel 5362:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  5363:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  5364:                 }
1.629     banghart 5365:                 if ($cmp1 eq $cmp2) {
1.561     banghart 5366:                     push(@readonly_files, $file_name);
1.745     raeburn  5367:                     last;
1.563     banghart 5368:                 } elsif (!defined($what)) {
                   5369:                     push(@readonly_files, $file_name);
1.745     raeburn  5370:                     last;
1.561     banghart 5371:                 }
                   5372:             }
1.745     raeburn  5373:         }
1.561     banghart 5374:     }
                   5375:     return @readonly_files;
                   5376: }
1.577     banghart 5377: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 5378: 
1.577     banghart 5379: sub get_marked_as_readonly_hash {
1.745     raeburn  5380:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 5381:     my %readonly_files;
1.745     raeburn  5382:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5383:         if (defined($group)) {
                   5384:             if ($file_name !~ m-^\Q$group\E/-) {
                   5385:                 next;
                   5386:             }
                   5387:         }
1.577     banghart 5388:         if (ref($value) eq "ARRAY"){
                   5389:             foreach my $stored_what (@{$value}) {
1.745     raeburn  5390:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 5391:                     foreach my $lock_descriptor(@{$stored_what}) {
                   5392:                         if ($lock_descriptor eq 'graded') {
                   5393:                             $readonly_files{$file_name} = 'graded';
                   5394:                         } elsif ($lock_descriptor eq 'handback') {
                   5395:                             $readonly_files{$file_name} = 'handback';
                   5396:                         } else {
                   5397:                             if (!exists($readonly_files{$file_name})) {
                   5398:                                 $readonly_files{$file_name} = 'locked';
                   5399:                             }
                   5400:                         }
1.745     raeburn  5401:                     }
1.750     banghart 5402:                 } 
1.577     banghart 5403:             }
                   5404:         } 
                   5405:     }
                   5406:     return %readonly_files;
                   5407: }
1.559     banghart 5408: # ------------------------------------------------------------ Unmark as Read Only
                   5409: 
                   5410: sub unmark_as_readonly {
1.629     banghart 5411:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   5412:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  5413:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 5414:     $file_name = &declutter_portfile($file_name);
1.634     albertel 5415:     my $symb_crs = $what;
                   5416:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  5417:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 5418:     my ($tmp)=keys(%current_permissions);
                   5419:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5420:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 5421:     foreach my $file (@readonly_files) {
1.759     albertel 5422: 	my $clean_file = &declutter_portfile($file);
                   5423: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 5424: 	my $current_locks = $current_permissions{$file};
1.563     banghart 5425:         my @new_locks;
                   5426:         my @del_keys;
                   5427:         if (ref($current_locks) eq "ARRAY"){
                   5428:             foreach my $locker (@{$current_locks}) {
1.632     albertel 5429:                 my $compare=$locker;
1.749     raeburn  5430:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  5431:                     $compare=join('',@{$locker});
1.746     raeburn  5432:                     if ($compare ne $symb_crs) {
                   5433:                         push(@new_locks, $locker);
                   5434:                     }
1.563     banghart 5435:                 }
                   5436:             }
1.650     albertel 5437:             if (scalar(@new_locks) > 0) {
1.563     banghart 5438:                 $current_permissions{$file} = \@new_locks;
                   5439:             } else {
                   5440:                 push(@del_keys, $file);
1.613     albertel 5441:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 5442:                 delete($current_permissions{$file});
1.563     banghart 5443:             }
                   5444:         }
1.561     banghart 5445:     }
1.613     albertel 5446:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5447:     return;
                   5448: }
1.512     banghart 5449: 
1.17      www      5450: # ------------------------------------------------------------ Directory lister
                   5451: 
                   5452: sub dirlist {
1.253     stredwic 5453:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
                   5454: 
1.18      www      5455:     $uri=~s/^\///;
                   5456:     $uri=~s/\/$//;
1.253     stredwic 5457:     my ($udom, $uname);
                   5458:     (undef,$udom,$uname)=split(/\//,$uri);
                   5459:     if(defined($userdomain)) {
                   5460:         $udom = $userdomain;
                   5461:     }
                   5462:     if(defined($username)) {
                   5463:         $uname = $username;
                   5464:     }
                   5465: 
                   5466:     my $dirRoot = $perlvar{'lonDocRoot'};
                   5467:     if(defined($alternateDirectoryRoot)) {
                   5468:         $dirRoot = $alternateDirectoryRoot;
                   5469:         $dirRoot =~ s/\/$//;
1.751     banghart 5470:     }
1.253     stredwic 5471: 
                   5472:     if($udom) {
                   5473:         if($uname) {
1.800     albertel 5474:             my $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   5475: 				 &homeserver($uname,$udom));
1.605     matthew  5476:             my @listing_results;
                   5477:             if ($listing eq 'unknown_cmd') {
1.800     albertel 5478:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   5479: 				  &homeserver($uname,$udom));
1.605     matthew  5480:                 @listing_results = split(/:/,$listing);
                   5481:             } else {
                   5482:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   5483:             }
                   5484:             return @listing_results;
1.253     stredwic 5485:         } elsif(!defined($alternateDirectoryRoot)) {
1.800     albertel 5486:             my %allusers;
                   5487:             foreach my $tryserver (keys(%libserv)) {
1.253     stredwic 5488:                 if($hostdom{$tryserver} eq $udom) {
1.800     albertel 5489:                     my $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   5490: 					 $udom, $tryserver);
1.605     matthew  5491:                     my @listing_results;
                   5492:                     if ($listing eq 'unknown_cmd') {
1.800     albertel 5493:                         $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   5494: 					  $udom, $tryserver);
1.605     matthew  5495:                         @listing_results = split(/:/,$listing);
                   5496:                     } else {
                   5497:                         @listing_results =
                   5498:                             map { &unescape($_); } split(/:/,$listing);
                   5499:                     }
                   5500:                     if ($listing_results[0] ne 'no_such_dir' && 
                   5501:                         $listing_results[0] ne 'empty'       &&
                   5502:                         $listing_results[0] ne 'con_lost') {
1.800     albertel 5503:                         foreach my $line (@listing_results) {
                   5504:                             my ($entry) = split(/&/,$line,2);
                   5505:                             $allusers{$entry} = 1;
1.253     stredwic 5506:                         }
                   5507:                     }
1.191     harris41 5508:                 }
1.253     stredwic 5509:             }
                   5510:             my $alluserstr='';
1.800     albertel 5511:             foreach my $user (sort(keys(%allusers))) {
                   5512:                 $alluserstr.=$user.'&user:';
1.253     stredwic 5513:             }
                   5514:             $alluserstr=~s/:$//;
                   5515:             return split(/:/,$alluserstr);
                   5516:         } else {
1.800     albertel 5517:             return ('missing user name');
1.253     stredwic 5518:         }
                   5519:     } elsif(!defined($alternateDirectoryRoot)) {
                   5520:         my $tryserver;
                   5521:         my %alldom=();
1.800     albertel 5522:         foreach $tryserver (keys(%libserv)) {
1.253     stredwic 5523:             $alldom{$hostdom{$tryserver}}=1;
                   5524:         }
                   5525:         my $alldomstr='';
1.800     albertel 5526:         foreach my $domain (sort(keys(%alldom))) {
                   5527:             $alldomstr.=$perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain:';
1.253     stredwic 5528:         }
                   5529:         $alldomstr=~s/:$//;
                   5530:         return split(/:/,$alldomstr);       
                   5531:     } else {
1.800     albertel 5532:         return ('missing domain');
1.275     stredwic 5533:     }
                   5534: }
                   5535: 
                   5536: # --------------------------------------------- GetFileTimestamp
                   5537: # This function utilizes dirlist and returns the date stamp for
                   5538: # when it was last modified.  It will also return an error of -1
                   5539: # if an error occurs
                   5540: 
1.410     matthew  5541: ##
                   5542: ## FIXME: This subroutine assumes its caller knows something about the
                   5543: ## directory structure of the home server for the student ($root).
                   5544: ## Not a good assumption to make.  Since this is for looking up files
                   5545: ## in user directories, the full path should be constructed by lond, not
                   5546: ## whatever machine we request data from.
                   5547: ##
1.275     stredwic 5548: sub GetFileTimestamp {
                   5549:     my ($studentDomain,$studentName,$filename,$root)=@_;
1.807     albertel 5550:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   5551:     $studentName   = &LONCAPA::clean_username($studentName);
1.275     stredwic 5552:     my $subdir=$studentName.'__';
                   5553:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   5554:     my $proname="$studentDomain/$subdir/$studentName";
                   5555:     $proname .= '/'.$filename;
1.375     matthew  5556:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
                   5557:                                               $studentName, $root);
1.275     stredwic 5558:     my @stats = split('&', $fileStat);
                   5559:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  5560:         # @stats contains first the filename, then the stat output
                   5561:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 5562:     } else {
                   5563:         return -1;
1.253     stredwic 5564:     }
1.26      www      5565: }
                   5566: 
1.712     albertel 5567: sub stat_file {
                   5568:     my ($uri) = @_;
1.787     albertel 5569:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 5570: 
1.712     albertel 5571:     my ($udom,$uname,$file,$dir);
                   5572:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   5573: 	($udom,$uname,$file) =
1.811     albertel 5574: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 5575: 	$file = 'userfiles/'.$file;
1.740     www      5576: 	$dir = &propath($udom,$uname);
1.712     albertel 5577:     }
                   5578:     if ($uri =~ m-^/res/-) {
                   5579: 	($udom,$uname) = 
1.807     albertel 5580: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 5581: 	$file = $uri;
                   5582:     }
                   5583: 
                   5584:     if (!$udom || !$uname || !$file) {
                   5585: 	# unable to handle the uri
                   5586: 	return ();
                   5587:     }
                   5588: 
                   5589:     my ($result) = &dirlist($file,$udom,$uname,$dir);
                   5590:     my @stats = split('&', $result);
1.721     banghart 5591:     
1.712     albertel 5592:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   5593: 	shift(@stats); #filename is first
                   5594: 	return @stats;
                   5595:     }
                   5596:     return ();
                   5597: }
                   5598: 
1.26      www      5599: # -------------------------------------------------------- Value of a Condition
                   5600: 
1.713     albertel 5601: # gets the value of a specific preevaluated condition
                   5602: #    stored in the string  $env{user.state.<cid>}
                   5603: # or looks up a condition reference in the bighash and if if hasn't
                   5604: # already been evaluated recurses into docondval to get the value of
                   5605: # the condition, then memoizing it to 
                   5606: #   $env{user.state.<cid>.<condition>}
1.40      www      5607: sub directcondval {
                   5608:     my $number=shift;
1.620     albertel 5609:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 5610: 	&Apache::lonuserstate::evalstate();
                   5611:     }
1.713     albertel 5612:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   5613: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   5614:     } elsif ($number =~ /^_/) {
                   5615: 	my $sub_condition;
                   5616: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   5617: 		&GDBM_READER(),0640)) {
                   5618: 	    $sub_condition=$bighash{'conditions'.$number};
                   5619: 	    untie(%bighash);
                   5620: 	}
                   5621: 	my $value = &docondval($sub_condition);
                   5622: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
                   5623: 	return $value;
                   5624:     }
1.620     albertel 5625:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   5626:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      5627:     } else {
                   5628:        return 2;
                   5629:     }
                   5630: }
                   5631: 
1.713     albertel 5632: # get the collection of conditions for this resource
1.26      www      5633: sub condval {
                   5634:     my $condidx=shift;
1.54      www      5635:     my $allpathcond='';
1.713     albertel 5636:     foreach my $cond (split(/\|/,$condidx)) {
                   5637: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   5638: 	    $allpathcond.=
                   5639: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   5640: 	}
1.191     harris41 5641:     }
1.54      www      5642:     $allpathcond=~s/\|$//;
1.713     albertel 5643:     return &docondval($allpathcond);
                   5644: }
                   5645: 
                   5646: #evaluates an expression of conditions
                   5647: sub docondval {
                   5648:     my ($allpathcond) = @_;
                   5649:     my $result=0;
                   5650:     if ($env{'request.course.id'}
                   5651: 	&& defined($allpathcond)) {
                   5652: 	my $operand='|';
                   5653: 	my @stack;
                   5654: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   5655: 	    if ($chunk eq '(') {
                   5656: 		push @stack,($operand,$result);
                   5657: 	    } elsif ($chunk eq ')') {
                   5658: 		my $before=pop @stack;
                   5659: 		if (pop @stack eq '&') {
                   5660: 		    $result=$result>$before?$before:$result;
                   5661: 		} else {
                   5662: 		    $result=$result>$before?$result:$before;
                   5663: 		}
                   5664: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   5665: 		$operand=$chunk;
                   5666: 	    } else {
                   5667: 		my $new=directcondval($chunk);
                   5668: 		if ($operand eq '&') {
                   5669: 		    $result=$result>$new?$new:$result;
                   5670: 		} else {
                   5671: 		    $result=$result>$new?$result:$new;
                   5672: 		}
                   5673: 	    }
                   5674: 	}
1.26      www      5675:     }
                   5676:     return $result;
1.421     albertel 5677: }
                   5678: 
                   5679: # ---------------------------------------------------- Devalidate courseresdata
                   5680: 
                   5681: sub devalidatecourseresdata {
                   5682:     my ($coursenum,$coursedomain)=@_;
                   5683:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 5684:     &devalidate_cache_new('courseres',$hashid);
1.28      www      5685: }
                   5686: 
1.763     www      5687: 
1.200     www      5688: # --------------------------------------------------- Course Resourcedata Query
                   5689: 
1.624     albertel 5690: sub get_courseresdata {
                   5691:     my ($coursenum,$coursedomain)=@_;
1.200     www      5692:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   5693:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 5694:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 5695:     my %dumpreply;
1.417     albertel 5696:     unless (defined($cached)) {
1.624     albertel 5697: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 5698: 	$result=\%dumpreply;
1.251     albertel 5699: 	my ($tmp) = keys(%dumpreply);
                   5700: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 5701: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 5702: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   5703: 	    return $tmp;
1.416     albertel 5704: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 5705: 	    $result=undef;
1.599     albertel 5706: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 5707: 	}
                   5708:     }
1.624     albertel 5709:     return $result;
                   5710: }
                   5711: 
1.633     albertel 5712: sub devalidateuserresdata {
                   5713:     my ($uname,$udom)=@_;
                   5714:     my $hashid="$udom:$uname";
                   5715:     &devalidate_cache_new('userres',$hashid);
                   5716: }
                   5717: 
1.624     albertel 5718: sub get_userresdata {
                   5719:     my ($uname,$udom)=@_;
                   5720:     #most student don\'t have any data set, check if there is some data
                   5721:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   5722: 
                   5723:     my $hashid="$udom:$uname";
                   5724:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   5725:     if (!defined($cached)) {
                   5726: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   5727: 	$result=\%resourcedata;
                   5728: 	&do_cache_new('userres',$hashid,$result,600);
                   5729:     }
                   5730:     my ($tmp)=keys(%$result);
                   5731:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   5732: 	return $result;
                   5733:     }
                   5734:     #error 2 occurs when the .db doesn't exist
                   5735:     if ($tmp!~/error: 2 /) {
1.672     albertel 5736: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 5737: 		 " Trying to get resource data for ".
                   5738: 		 $uname." at ".$udom.": ".
                   5739: 		 $tmp."</font>");
                   5740:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 5741: 	#&EXT_cache_set($udom,$uname);
                   5742: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 5743: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 5744:     }
                   5745:     return $tmp;
                   5746: }
                   5747: 
                   5748: sub resdata {
                   5749:     my ($name,$domain,$type,@which)=@_;
                   5750:     my $result;
                   5751:     if ($type eq 'course') {
                   5752: 	$result=&get_courseresdata($name,$domain);
                   5753:     } elsif ($type eq 'user') {
                   5754: 	$result=&get_userresdata($name,$domain);
                   5755:     }
                   5756:     if (!ref($result)) { return $result; }    
1.251     albertel 5757:     foreach my $item (@which) {
1.417     albertel 5758: 	if (defined($result->{$item})) {
                   5759: 	    return $result->{$item};
1.251     albertel 5760: 	}
1.250     albertel 5761:     }
1.291     albertel 5762:     return undef;
1.200     www      5763: }
                   5764: 
1.379     matthew  5765: #
                   5766: # EXT resource caching routines
                   5767: #
                   5768: 
                   5769: sub clear_EXT_cache_status {
1.383     albertel 5770:     &delenv('cache.EXT.');
1.379     matthew  5771: }
                   5772: 
                   5773: sub EXT_cache_status {
                   5774:     my ($target_domain,$target_user) = @_;
1.383     albertel 5775:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 5776:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  5777:         # We know already the user has no data
                   5778:         return 1;
                   5779:     } else {
                   5780:         return 0;
                   5781:     }
                   5782: }
                   5783: 
                   5784: sub EXT_cache_set {
                   5785:     my ($target_domain,$target_user) = @_;
1.383     albertel 5786:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.633     albertel 5787:     #&appenv($cachename => time);
1.379     matthew  5788: }
                   5789: 
1.28      www      5790: # --------------------------------------------------------- Value of a Variable
1.58      www      5791: sub EXT {
1.715     albertel 5792: 
1.395     albertel 5793:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      5794:     unless ($varname) { return ''; }
1.218     albertel 5795:     #get real user name/domain, courseid and symb
                   5796:     my $courseid;
1.359     albertel 5797:     my $publicuser;
1.427     www      5798:     if ($symbparm) {
                   5799: 	$symbparm=&get_symb_from_alias($symbparm);
                   5800:     }
1.218     albertel 5801:     if (!($uname && $udom)) {
1.790     albertel 5802:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 5803:       if (!$symbparm) {	$symbparm=$cursymb; }
                   5804:     } else {
1.620     albertel 5805: 	$courseid=$env{'request.course.id'};
1.218     albertel 5806:     }
1.48      www      5807:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   5808:     my $rest;
1.320     albertel 5809:     if (defined($therest[0])) {
1.48      www      5810:        $rest=join('.',@therest);
                   5811:     } else {
                   5812:        $rest='';
                   5813:     }
1.320     albertel 5814: 
1.57      www      5815:     my $qualifierrest=$qualifier;
                   5816:     if ($rest) { $qualifierrest.='.'.$rest; }
                   5817:     my $spacequalifierrest=$space;
                   5818:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      5819:     if ($realm eq 'user') {
1.48      www      5820: # --------------------------------------------------------------- user.resource
                   5821: 	if ($space eq 'resource') {
1.651     albertel 5822: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   5823: 		  || defined($Apache::lonhomework::parsing_a_task))
                   5824: 		 &&
1.744     albertel 5825: 		 ($symbparm eq &symbread()) ) {	
                   5826: 		# if we are in the middle of processing the resource the
                   5827: 		# get the value we are planning on committing
                   5828:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   5829:                     return $Apache::lonhomework::results{$qualifierrest};
                   5830:                 } else {
                   5831:                     return $Apache::lonhomework::history{$qualifierrest};
                   5832:                 }
1.335     albertel 5833: 	    } else {
1.359     albertel 5834: 		my %restored;
1.620     albertel 5835: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 5836: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   5837: 		} else {
                   5838: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   5839: 		}
1.335     albertel 5840: 		return $restored{$qualifierrest};
                   5841: 	    }
1.48      www      5842: # ----------------------------------------------------------------- user.access
                   5843:         } elsif ($space eq 'access') {
1.218     albertel 5844: 	    # FIXME - not supporting calls for a specific user
1.48      www      5845:             return &allowed($qualifier,$rest);
                   5846: # ------------------------------------------ user.preferences, user.environment
                   5847:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 5848: 	    if (($uname eq $env{'user.name'}) &&
                   5849: 		($udom eq $env{'user.domain'})) {
                   5850: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 5851: 	    } else {
1.359     albertel 5852: 		my %returnhash;
                   5853: 		if (!$publicuser) {
                   5854: 		    %returnhash=&userenvironment($udom,$uname,
                   5855: 						 $qualifierrest);
                   5856: 		}
1.218     albertel 5857: 		return $returnhash{$qualifierrest};
                   5858: 	    }
1.48      www      5859: # ----------------------------------------------------------------- user.course
                   5860:         } elsif ($space eq 'course') {
1.218     albertel 5861: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 5862:             return $env{join('.',('request.course',$qualifier))};
1.48      www      5863: # ------------------------------------------------------------------- user.role
                   5864:         } elsif ($space eq 'role') {
1.218     albertel 5865: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 5866:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      5867:             if ($qualifier eq 'value') {
                   5868: 		return $role;
                   5869:             } elsif ($qualifier eq 'extent') {
                   5870:                 return $where;
                   5871:             }
                   5872: # ----------------------------------------------------------------- user.domain
                   5873:         } elsif ($space eq 'domain') {
1.218     albertel 5874:             return $udom;
1.48      www      5875: # ------------------------------------------------------------------- user.name
                   5876:         } elsif ($space eq 'name') {
1.218     albertel 5877:             return $uname;
1.48      www      5878: # ---------------------------------------------------- Any other user namespace
1.29      www      5879:         } else {
1.359     albertel 5880: 	    my %reply;
                   5881: 	    if (!$publicuser) {
                   5882: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   5883: 	    }
                   5884: 	    return $reply{$qualifierrest};
1.48      www      5885:         }
1.236     www      5886:     } elsif ($realm eq 'query') {
                   5887: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 5888:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   5889: 						[$spacequalifierrest]);
1.620     albertel 5890: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      5891:    } elsif ($realm eq 'request') {
1.48      www      5892: # ------------------------------------------------------------- request.browser
                   5893:         if ($space eq 'browser') {
1.430     www      5894: 	    if ($qualifier eq 'textremote') {
1.676     albertel 5895: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      5896: 		    return 1;
                   5897: 		} else {
                   5898: 		    return 0;
                   5899: 		}
                   5900: 	    } else {
1.620     albertel 5901: 		return $env{'browser.'.$qualifier};
1.430     www      5902: 	    }
1.57      www      5903: # ------------------------------------------------------------ request.filename
                   5904:         } else {
1.620     albertel 5905:             return $env{'request.'.$spacequalifierrest};
1.29      www      5906:         }
1.28      www      5907:     } elsif ($realm eq 'course') {
1.48      www      5908: # ---------------------------------------------------------- course.description
1.620     albertel 5909:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      5910:     } elsif ($realm eq 'resource') {
1.165     www      5911: 
1.620     albertel 5912: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 5913: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   5914: 	}
1.693     albertel 5915: 
                   5916: 	if ($space eq 'title') {
                   5917: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   5918: 	    return &gettitle($symbparm);
                   5919: 	}
                   5920: 	
                   5921: 	if ($space eq 'map') {
                   5922: 	    my ($map) = &decode_symb($symbparm);
                   5923: 	    return &symbread($map);
                   5924: 	}
                   5925: 
                   5926: 	my ($section, $group, @groups);
1.593     albertel 5927: 	my ($courselevelm,$courselevel);
1.539     albertel 5928: 	if ($symbparm && defined($courseid) && 
1.620     albertel 5929: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      5930: 
1.218     albertel 5931: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      5932: 
1.60      www      5933: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 5934: 	    my $symbp=$symbparm;
1.735     albertel 5935: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 5936: 
                   5937: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   5938: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   5939: 
1.620     albertel 5940: 	    if (($env{'user.name'} eq $uname) &&
                   5941: 		($env{'user.domain'} eq $udom)) {
                   5942: 		$section=$env{'request.course.sec'};
1.733     raeburn  5943:                 @groups = split(/:/,$env{'request.course.groups'});  
                   5944:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 5945: 	    } else {
1.539     albertel 5946: 		if (! defined($usection)) {
1.551     albertel 5947: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 5948: 		} else {
                   5949: 		    $section = $usection;
                   5950: 		}
1.733     raeburn  5951:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 5952: 	    }
                   5953: 
                   5954: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   5955: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   5956: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   5957: 
1.593     albertel 5958: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 5959: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 5960: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      5961: 
1.60      www      5962: # ----------------------------------------------------------- first, check user
1.624     albertel 5963: 
                   5964: 	    my $userreply=&resdata($uname,$udom,'user',
                   5965: 				       ($courselevelr,$courselevelm,
                   5966: 					$courselevel));
                   5967: 	    if (defined($userreply)) { return $userreply; }
1.95      www      5968: 
1.594     albertel 5969: # ------------------------------------------------ second, check some of course
1.684     raeburn  5970:             my $coursereply;
1.691     raeburn  5971:             if (@groups > 0) {
                   5972:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   5973:                                        $mapparm,$spacequalifierrest);
1.684     raeburn  5974:                 if (defined($coursereply)) { return $coursereply; }
                   5975:             }
1.96      www      5976: 
1.684     raeburn  5977: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.624     albertel 5978: 				     $env{'course.'.$courseid.'.domain'},
                   5979: 				     'course',
                   5980: 				     ($seclevelr,$seclevelm,$seclevel,
                   5981: 				      $courselevelr));
1.287     albertel 5982: 	    if (defined($coursereply)) { return $coursereply; }
1.200     www      5983: 
1.60      www      5984: # ------------------------------------------------------ third, check map parms
1.218     albertel 5985: 	    my %parmhash=();
                   5986: 	    my $thisparm='';
                   5987: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 5988: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 5989: 		    &GDBM_READER(),0640)) {
1.218     albertel 5990: 		$thisparm=$parmhash{$symbparm};
                   5991: 		untie(%parmhash);
                   5992: 	    }
                   5993: 	    if ($thisparm) { return $thisparm; }
                   5994: 	}
1.594     albertel 5995: # ------------------------------------------ fourth, look in resource metadata
1.71      www      5996: 
1.218     albertel 5997: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 5998: 	my $filename;
                   5999: 	if (!$symbparm) { $symbparm=&symbread(); }
                   6000: 	if ($symbparm) {
1.409     www      6001: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 6002: 	} else {
1.620     albertel 6003: 	    $filename=$env{'request.filename'};
1.282     albertel 6004: 	}
                   6005: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.288     albertel 6006: 	if (defined($metadata)) { return $metadata; }
1.282     albertel 6007: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.288     albertel 6008: 	if (defined($metadata)) { return $metadata; }
1.142     www      6009: 
1.594     albertel 6010: # ---------------------------------------------- fourth, look in rest pf course
1.593     albertel 6011: 	if ($symbparm && defined($courseid) && 
1.620     albertel 6012: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 6013: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   6014: 				     $env{'course.'.$courseid.'.domain'},
                   6015: 				     'course',
                   6016: 				     ($courselevelm,$courselevel));
1.593     albertel 6017: 	    if (defined($coursereply)) { return $coursereply; }
                   6018: 	}
1.145     www      6019: # ------------------------------------------------------------------ Cascade up
1.218     albertel 6020: 	unless ($space eq '0') {
1.336     albertel 6021: 	    my @parts=split(/_/,$space);
                   6022: 	    my $id=pop(@parts);
                   6023: 	    my $part=join('_',@parts);
                   6024: 	    if ($part eq '') { $part='0'; }
                   6025: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 6026: 				 $symbparm,$udom,$uname,$section,1);
1.337     albertel 6027: 	    if (defined($partgeneral)) { return $partgeneral; }
1.218     albertel 6028: 	}
1.395     albertel 6029: 	if ($recurse) { return undef; }
                   6030: 	my $pack_def=&packages_tab_default($filename,$varname);
                   6031: 	if (defined($pack_def)) { return $pack_def; }
1.71      www      6032: 
1.48      www      6033: # ---------------------------------------------------- Any other user namespace
                   6034:     } elsif ($realm eq 'environment') {
                   6035: # ----------------------------------------------------------------- environment
1.620     albertel 6036: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   6037: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 6038: 	} else {
1.770     albertel 6039: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   6040: 		return '';
                   6041: 	    }
1.219     albertel 6042: 	    my %returnhash=&userenvironment($udom,$uname,
                   6043: 					    $spacequalifierrest);
                   6044: 	    return $returnhash{$spacequalifierrest};
                   6045: 	}
1.28      www      6046:     } elsif ($realm eq 'system') {
1.48      www      6047: # ----------------------------------------------------------------- system.time
                   6048: 	if ($space eq 'time') {
                   6049: 	    return time;
                   6050:         }
1.696     albertel 6051:     } elsif ($realm eq 'server') {
                   6052: # ----------------------------------------------------------------- system.time
                   6053: 	if ($space eq 'name') {
                   6054: 	    return $ENV{'SERVER_NAME'};
                   6055:         }
1.28      www      6056:     }
1.48      www      6057:     return '';
1.61      www      6058: }
                   6059: 
1.691     raeburn  6060: sub check_group_parms {
                   6061:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   6062:     my @groupitems = ();
                   6063:     my $resultitem;
                   6064:     my @levels = ($symbparm,$mapparm,$what);
                   6065:     foreach my $group (@{$groups}) {
                   6066:         foreach my $level (@levels) {
                   6067:              my $item = $courseid.'.['.$group.'].'.$level;
                   6068:              push(@groupitems,$item);
                   6069:         }
                   6070:     }
                   6071:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   6072:                             $env{'course.'.$courseid.'.domain'},
                   6073:                                      'course',@groupitems);
                   6074:     return $coursereply;
                   6075: }
                   6076: 
                   6077: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  6078:     my ($courseid,@groups) = @_;
                   6079:     @groups = sort(@groups);
1.691     raeburn  6080:     return @groups;
                   6081: }
                   6082: 
1.395     albertel 6083: sub packages_tab_default {
                   6084:     my ($uri,$varname)=@_;
                   6085:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 6086: 
                   6087:     my (@extension,@specifics,$do_default);
                   6088:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 6089: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 6090: 	if ($pack_type eq 'default') {
                   6091: 	    $do_default=1;
                   6092: 	} elsif ($pack_type eq 'extension') {
                   6093: 	    push(@extension,[$package,$pack_type,$pack_part]);
                   6094: 	} else {
                   6095: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   6096: 	}
                   6097:     }
                   6098:     # first look for a package that matches the requested part id
                   6099:     foreach my $package (@specifics) {
                   6100: 	my (undef,$pack_type,$pack_part)=@{$package};
                   6101: 	next if ($pack_part ne $part);
                   6102: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6103: 	    return $packagetab{"$pack_type&$name&default"};
                   6104: 	}
                   6105:     }
                   6106:     # look for any possible matching non extension_ package
                   6107:     foreach my $package (@specifics) {
                   6108: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 6109: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6110: 	    return $packagetab{"$pack_type&$name&default"};
                   6111: 	}
1.585     albertel 6112: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 6113: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   6114: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 6115: 	}
                   6116:     }
1.738     albertel 6117:     # look for any posible extension_ match
                   6118:     foreach my $package (@extension) {
                   6119: 	my ($package,$pack_type)=@{$package};
                   6120: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6121: 	    return $packagetab{"$pack_type&$name&default"};
                   6122: 	}
                   6123: 	if (defined($packagetab{$package."&$name&default"})) {
                   6124: 	    return $packagetab{$package."&$name&default"};
                   6125: 	}
                   6126:     }
                   6127:     # look for a global default setting
                   6128:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   6129: 	return $packagetab{"default&$name&default"};
                   6130:     }
1.395     albertel 6131:     return undef;
                   6132: }
                   6133: 
1.334     albertel 6134: sub add_prefix_and_part {
                   6135:     my ($prefix,$part)=@_;
                   6136:     my $keyroot;
                   6137:     if (defined($prefix) && $prefix !~ /^__/) {
                   6138: 	# prefix that has a part already
                   6139: 	$keyroot=$prefix;
                   6140:     } elsif (defined($prefix)) {
                   6141: 	# prefix that is missing a part
                   6142: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   6143:     } else {
                   6144: 	# no prefix at all
                   6145: 	if (defined($part)) { $keyroot='_'.$part; }
                   6146:     }
                   6147:     return $keyroot;
                   6148: }
                   6149: 
1.71      www      6150: # ---------------------------------------------------------------- Get metadata
                   6151: 
1.599     albertel 6152: my %metaentry;
1.71      www      6153: sub metadata {
1.176     www      6154:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      6155:     $uri=&declutter($uri);
1.288     albertel 6156:     # if it is a non metadata possible uri return quickly
1.529     albertel 6157:     if (($uri eq '') || 
                   6158: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 6159: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.423     albertel 6160:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
1.807     albertel 6161: 	($uri =~ m|home/$match_username/public_html/|)) {
1.468     albertel 6162: 	return undef;
1.288     albertel 6163:     }
1.73      www      6164:     my $filename=$uri;
                   6165:     $uri=~s/\.meta$//;
1.172     www      6166: #
                   6167: # Is the metadata already cached?
1.177     www      6168: # Look at timestamp of caching
1.172     www      6169: # Everything is cached by the main uri, libraries are never directly cached
                   6170: #
1.428     albertel 6171:     if (!defined($liburi)) {
1.599     albertel 6172: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 6173: 	if (defined($cached)) { return $result->{':'.$what}; }
                   6174:     }
                   6175:     {
1.172     www      6176: #
                   6177: # Is this a recursive call for a library?
                   6178: #
1.599     albertel 6179: #	if (! exists($metacache{$uri})) {
                   6180: #	    $metacache{$uri}={};
                   6181: #	}
1.171     www      6182:         if ($liburi) {
                   6183: 	    $liburi=&declutter($liburi);
                   6184:             $filename=$liburi;
1.401     bowersj2 6185:         } else {
1.599     albertel 6186: 	    &devalidate_cache_new('meta',$uri);
                   6187: 	    undef(%metaentry);
1.401     bowersj2 6188: 	}
1.140     www      6189:         my %metathesekeys=();
1.73      www      6190:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 6191: 	my $metastring;
1.768     albertel 6192: 	if ($uri !~ m -^(editupload)/-) {
1.543     albertel 6193: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 6194: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 6195: 	    $metastring=&getfile($file);
1.489     albertel 6196: 	}
1.208     albertel 6197:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      6198:         my $token;
1.140     www      6199:         undef %metathesekeys;
1.71      www      6200:         while ($token=$parser->get_token) {
1.339     albertel 6201: 	    if ($token->[0] eq 'S') {
                   6202: 		if (defined($token->[2]->{'package'})) {
1.172     www      6203: #
                   6204: # This is a package - get package info
                   6205: #
1.339     albertel 6206: 		    my $package=$token->[2]->{'package'};
                   6207: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6208: 		    if (defined($token->[2]->{'id'})) { 
                   6209: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   6210: 		    }
1.599     albertel 6211: 		    if ($metaentry{':packages'}) {
                   6212: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 6213: 		    } else {
1.599     albertel 6214: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 6215: 		    }
1.736     albertel 6216: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 6217: 			my $part=$keyroot;
                   6218: 			$part=~s/^\_//;
1.736     albertel 6219: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   6220: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   6221: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 6222: 			    # ignore package.tab specified default values
                   6223:                             # here &package_tab_default() will fetch those
                   6224: 			    if ($subp eq 'default') { next; }
1.736     albertel 6225: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 6226: 			    my $unikey;
                   6227: 			    if ($pack =~ /_0$/) {
                   6228: 				$unikey='parameter_0_'.$name;
                   6229: 				$part=0;
                   6230: 			    } else {
                   6231: 				$unikey='parameter'.$keyroot.'_'.$name;
                   6232: 			    }
1.339     albertel 6233: 			    if ($subp eq 'display') {
                   6234: 				$value.=' [Part: '.$part.']';
                   6235: 			    }
1.599     albertel 6236: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 6237: 			    $metathesekeys{$unikey}=1;
1.599     albertel 6238: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6239: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 6240: 			    }
1.599     albertel 6241: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   6242: 				$metaentry{':'.$unikey}=
                   6243: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 6244: 			    }
1.339     albertel 6245: 			}
                   6246: 		    }
                   6247: 		} else {
1.172     www      6248: #
                   6249: # This is not a package - some other kind of start tag
1.339     albertel 6250: #
                   6251: 		    my $entry=$token->[1];
                   6252: 		    my $unikey;
                   6253: 		    if ($entry eq 'import') {
                   6254: 			$unikey='';
                   6255: 		    } else {
                   6256: 			$unikey=$entry;
                   6257: 		    }
                   6258: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6259: 
                   6260: 		    if (defined($token->[2]->{'id'})) { 
                   6261: 			$unikey.='_'.$token->[2]->{'id'}; 
                   6262: 		    }
1.175     www      6263: 
1.339     albertel 6264: 		    if ($entry eq 'import') {
1.175     www      6265: #
                   6266: # Importing a library here
1.339     albertel 6267: #
                   6268: 			if ($depthcount<20) {
                   6269: 			    my $location=$parser->get_text('/import');
                   6270: 			    my $dir=$filename;
                   6271: 			    $dir=~s|[^/]*$||;
                   6272: 			    $location=&filelocation($dir,$location);
1.736     albertel 6273: 			    my $metadata = 
                   6274: 				&metadata($uri,'keys', $location,$unikey,
                   6275: 					  $depthcount+1);
                   6276: 			    foreach my $meta (split(',',$metadata)) {
                   6277: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   6278: 				$metathesekeys{$meta}=1;
1.339     albertel 6279: 			    }
                   6280: 			}
                   6281: 		    } else { 
                   6282: 			
                   6283: 			if (defined($token->[2]->{'name'})) { 
                   6284: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   6285: 			}
                   6286: 			$metathesekeys{$unikey}=1;
1.736     albertel 6287: 			foreach my $param (@{$token->[3]}) {
                   6288: 			    $metaentry{':'.$unikey.'.'.$param} =
                   6289: 				$token->[2]->{$param};
1.339     albertel 6290: 			}
                   6291: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 6292: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 6293: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   6294: 		 # only ws inside the tag, and not in default, so use default
                   6295: 		 # as value
1.599     albertel 6296: 			    $metaentry{':'.$unikey}=$default;
1.339     albertel 6297: 			} else {
1.321     albertel 6298: 		  # either something interesting inside the tag or default
                   6299:                   # uninteresting
1.599     albertel 6300: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 6301: 			}
1.172     www      6302: # end of not-a-package not-a-library import
1.339     albertel 6303: 		    }
1.172     www      6304: # end of not-a-package start tag
1.339     albertel 6305: 		}
1.172     www      6306: # the next is the end of "start tag"
1.339     albertel 6307: 	    }
                   6308: 	}
1.483     albertel 6309: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.737     albertel 6310: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 6311: 	    #no specific packages #how's our extension
                   6312: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 6313: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 6314: 					 \%metathesekeys);
                   6315: 	}
1.599     albertel 6316: 	if (!exists($metaentry{':packages'})) {
1.737     albertel 6317: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 6318: 		#no specific packages well let's get default then
                   6319: 		if ($key!~/^default&/) { next; }
1.488     albertel 6320: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 6321: 					     \%metathesekeys);
                   6322: 	    }
                   6323: 	}
1.338     www      6324: # are there custom rights to evaluate
1.599     albertel 6325: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 6326: 
1.338     www      6327:     #
                   6328:     # Importing a rights file here
1.339     albertel 6329:     #
                   6330: 	    unless ($depthcount) {
1.599     albertel 6331: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 6332: 		my $dir=$filename;
                   6333: 		$dir=~s|[^/]*$||;
                   6334: 		$location=&filelocation($dir,$location);
1.736     albertel 6335: 		my $rights_metadata =
                   6336: 		    &metadata($uri,'keys',$location,'_rights',
                   6337: 			      $depthcount+1);
                   6338: 		foreach my $rights (split(',',$rights_metadata)) {
                   6339: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   6340: 		    $metathesekeys{$rights}=1;
1.339     albertel 6341: 		}
                   6342: 	    }
                   6343: 	}
1.737     albertel 6344: 	# uniqifiy package listing
                   6345: 	my %seen;
                   6346: 	my @uniq_packages =
                   6347: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   6348: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   6349: 
                   6350: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 6351: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   6352: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.699     albertel 6353: 	&do_cache_new('meta',$uri,\%metaentry,60*60);
1.177     www      6354: # this is the end of "was not already recently cached
1.71      www      6355:     }
1.599     albertel 6356:     return $metaentry{':'.$what};
1.261     albertel 6357: }
                   6358: 
1.488     albertel 6359: sub metadata_create_package_def {
1.483     albertel 6360:     my ($uri,$key,$package,$metathesekeys)=@_;
                   6361:     my ($pack,$name,$subp)=split(/\&/,$key);
                   6362:     if ($subp eq 'default') { next; }
                   6363:     
1.599     albertel 6364:     if (defined($metaentry{':packages'})) {
                   6365: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 6366:     } else {
1.599     albertel 6367: 	$metaentry{':packages'}=$package;
1.483     albertel 6368:     }
                   6369:     my $value=$packagetab{$key};
                   6370:     my $unikey;
                   6371:     $unikey='parameter_0_'.$name;
1.599     albertel 6372:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 6373:     $$metathesekeys{$unikey}=1;
1.599     albertel 6374:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6375: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 6376:     }
1.599     albertel 6377:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   6378: 	$metaentry{':'.$unikey}=
                   6379: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 6380:     }
                   6381: }
                   6382: 
1.261     albertel 6383: sub metadata_generate_part0 {
                   6384:     my ($metadata,$metacache,$uri) = @_;
                   6385:     my %allnames;
1.737     albertel 6386:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 6387: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 6388: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   6389: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 6390: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 6391: 	    $allnames{$name}=$part;
                   6392: 	  }
                   6393: 	}
                   6394:     }
                   6395:     foreach my $name (keys(%allnames)) {
                   6396:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 6397:       my $key=":parameter_0_$name";
1.261     albertel 6398:       $$metacache{"$key.part"}='0';
                   6399:       $$metacache{"$key.name"}=$name;
1.428     albertel 6400:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 6401: 					   $allnames{$name}.'_'.$name.
                   6402: 					   '.type'};
1.428     albertel 6403:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 6404: 			     '.display'};
1.644     www      6405:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 6406:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 6407:       $$metacache{"$key.display"}=$olddis;
                   6408:     }
1.71      www      6409: }
                   6410: 
1.764     albertel 6411: # ------------------------------------------------------ Devalidate title cache
                   6412: 
                   6413: sub devalidate_title_cache {
                   6414:     my ($url)=@_;
                   6415:     if (!$env{'request.course.id'}) { return; }
                   6416:     my $symb=&symbread($url);
                   6417:     if (!$symb) { return; }
                   6418:     my $key=$env{'request.course.id'}."\0".$symb;
                   6419:     &devalidate_cache_new('title',$key);
                   6420: }
                   6421: 
1.301     www      6422: # ------------------------------------------------- Get the title of a resource
                   6423: 
                   6424: sub gettitle {
                   6425:     my $urlsymb=shift;
                   6426:     my $symb=&symbread($urlsymb);
1.534     albertel 6427:     if ($symb) {
1.620     albertel 6428: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 6429: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 6430: 	if (defined($cached)) { 
                   6431: 	    return $result;
                   6432: 	}
1.534     albertel 6433: 	my ($map,$resid,$url)=&decode_symb($symb);
                   6434: 	my $title='';
                   6435: 	my %bighash;
1.620     albertel 6436: 	if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.534     albertel 6437: 		&GDBM_READER(),0640)) {
                   6438: 	    my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   6439: 	    $title=$bighash{'title_'.$mapid.'.'.$resid};
                   6440: 	    untie %bighash;
                   6441: 	}
                   6442: 	$title=~s/\&colon\;/\:/gs;
                   6443: 	if ($title) {
1.599     albertel 6444: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 6445: 	}
                   6446: 	$urlsymb=$url;
                   6447:     }
                   6448:     my $title=&metadata($urlsymb,'title');
                   6449:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   6450:     return $title;
1.301     www      6451: }
1.613     albertel 6452: 
1.614     albertel 6453: sub get_slot {
                   6454:     my ($which,$cnum,$cdom)=@_;
                   6455:     if (!$cnum || !$cdom) {
1.790     albertel 6456: 	(undef,my $courseid)=&whichuser();
1.620     albertel 6457: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   6458: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 6459:     }
1.703     albertel 6460:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   6461:     my %slotinfo;
                   6462:     if (exists($remembered{$key})) {
                   6463: 	$slotinfo{$which} = $remembered{$key};
                   6464:     } else {
                   6465: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   6466: 	&Apache::lonhomework::showhash(%slotinfo);
                   6467: 	my ($tmp)=keys(%slotinfo);
                   6468: 	if ($tmp=~/^error:/) { return (); }
                   6469: 	$remembered{$key} = $slotinfo{$which};
                   6470:     }
1.616     albertel 6471:     if (ref($slotinfo{$which}) eq 'HASH') {
                   6472: 	return %{$slotinfo{$which}};
                   6473:     }
                   6474:     return $slotinfo{$which};
1.614     albertel 6475: }
1.31      www      6476: # ------------------------------------------------- Update symbolic store links
                   6477: 
                   6478: sub symblist {
                   6479:     my ($mapname,%newhash)=@_;
1.438     www      6480:     $mapname=&deversion(&declutter($mapname));
1.31      www      6481:     my %hash;
1.620     albertel 6482:     if (($env{'request.course.fn'}) && (%newhash)) {
                   6483:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6484:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 6485: 	    foreach my $url (keys %newhash) {
                   6486: 		next if ($url eq 'last_known'
                   6487: 			 && $env{'form.no_update_last_known'});
                   6488: 		$hash{declutter($url)}=&encode_symb($mapname,
                   6489: 						    $newhash{$url}->[1],
                   6490: 						    $newhash{$url}->[0]);
1.191     harris41 6491:             }
1.31      www      6492:             if (untie(%hash)) {
                   6493: 		return 'ok';
                   6494:             }
                   6495:         }
                   6496:     }
                   6497:     return 'error';
1.212     www      6498: }
                   6499: 
                   6500: # --------------------------------------------------------------- Verify a symb
                   6501: 
                   6502: sub symbverify {
1.510     www      6503:     my ($symb,$thisurl)=@_;
                   6504:     my $thisfn=$thisurl;
1.439     www      6505:     $thisfn=&declutter($thisfn);
1.215     www      6506: # direct jump to resource in page or to a sequence - will construct own symbs
                   6507:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   6508: # check URL part
1.409     www      6509:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      6510: 
1.431     www      6511:     unless ($url eq $thisfn) { return 0; }
1.213     www      6512: 
1.216     www      6513:     $symb=&symbclean($symb);
1.510     www      6514:     $thisurl=&deversion($thisurl);
1.439     www      6515:     $thisfn=&deversion($thisfn);
1.213     www      6516: 
                   6517:     my %bighash;
                   6518:     my $okay=0;
1.431     www      6519: 
1.620     albertel 6520:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6521:                             &GDBM_READER(),0640)) {
1.510     www      6522:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      6523:         unless ($ids) { 
1.510     www      6524:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      6525:         }
                   6526:         if ($ids) {
                   6527: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 6528: 	    foreach my $id (split(/\,/,$ids)) {
                   6529: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      6530:                if (
                   6531:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   6532:    eq $symb) { 
1.620     albertel 6533: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 6534: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 6535: 		       $okay=1; 
                   6536: 		   }
                   6537: 	       }
1.216     www      6538: 	   }
                   6539:         }
1.213     www      6540: 	untie(%bighash);
                   6541:     }
                   6542:     return $okay;
1.31      www      6543: }
                   6544: 
1.210     www      6545: # --------------------------------------------------------------- Clean-up symb
                   6546: 
                   6547: sub symbclean {
                   6548:     my $symb=shift;
1.568     albertel 6549:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      6550: # remove version from map
                   6551:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      6552: 
1.210     www      6553: # remove version from URL
                   6554:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      6555: 
1.507     www      6556: # remove wrapper
                   6557: 
1.510     www      6558:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 6559:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      6560:     return $symb;
1.409     www      6561: }
                   6562: 
                   6563: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 6564: 
                   6565: sub encode_symb {
                   6566:     my ($map,$resid,$url)=@_;
                   6567:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   6568: }
1.409     www      6569: 
                   6570: sub decode_symb {
1.568     albertel 6571:     my $symb=shift;
                   6572:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   6573:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      6574:     return (&fixversion($map),$resid,&fixversion($url));
                   6575: }
                   6576: 
                   6577: sub fixversion {
                   6578:     my $fn=shift;
1.609     banghart 6579:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      6580:     my %bighash;
                   6581:     my $uri=&clutter($fn);
1.620     albertel 6582:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      6583: # is this cached?
1.599     albertel 6584:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      6585:     if (defined($cached)) { return $result; }
                   6586: # unfortunately not cached, or expired
1.620     albertel 6587:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      6588: 	    &GDBM_READER(),0640)) {
                   6589:  	if ($bighash{'version_'.$uri}) {
                   6590:  	    my $version=$bighash{'version_'.$uri};
1.444     www      6591:  	    unless (($version eq 'mostrecent') || 
                   6592: 		    ($version==&getversion($uri))) {
1.440     www      6593:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   6594:  	    }
                   6595:  	}
                   6596:  	untie %bighash;
1.413     www      6597:     }
1.599     albertel 6598:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      6599: }
                   6600: 
                   6601: sub deversion {
                   6602:     my $url=shift;
                   6603:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   6604:     return $url;
1.210     www      6605: }
                   6606: 
1.31      www      6607: # ------------------------------------------------------ Return symb list entry
                   6608: 
                   6609: sub symbread {
1.249     www      6610:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 6611:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 6612:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      6613: # no filename provided? try from environment
1.44      www      6614:     unless ($thisfn) {
1.620     albertel 6615:         if ($env{'request.symb'}) {
                   6616: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 6617: 	}
1.620     albertel 6618: 	$thisfn=$env{'request.filename'};
1.44      www      6619:     }
1.569     albertel 6620:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      6621: # is that filename actually a symb? Verify, clean, and return
                   6622:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 6623: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 6624: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 6625: 	}
1.242     www      6626:     }
1.44      www      6627:     $thisfn=declutter($thisfn);
1.31      www      6628:     my %hash;
1.37      www      6629:     my %bighash;
                   6630:     my $syval='';
1.620     albertel 6631:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  6632:         my $targetfn = $thisfn;
1.609     banghart 6633:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  6634:             $targetfn = 'adm/wrapper/'.$thisfn;
                   6635:         }
1.687     albertel 6636: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   6637: 	    $targetfn=$1;
                   6638: 	}
1.620     albertel 6639:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6640:                       &GDBM_READER(),0640)) {
1.481     raeburn  6641: 	    $syval=$hash{$targetfn};
1.37      www      6642:             untie(%hash);
                   6643:         }
                   6644: # ---------------------------------------------------------- There was an entry
                   6645:         if ($syval) {
1.601     albertel 6646: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 6647: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.601     albertel 6648: 		    #&appenv('request.ambiguous' => $thisfn);
1.620     albertel 6649: 		    #return $env{$cache_str}='';
1.601     albertel 6650: 		#}    
                   6651: 		#$syval.=$1;
                   6652: 	    #}
1.37      www      6653:         } else {
                   6654: # ------------------------------------------------------- Was not in symb table
1.620     albertel 6655:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6656:                             &GDBM_READER(),0640)) {
1.37      www      6657: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      6658:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      6659:               unless ($ids) { 
                   6660:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      6661:               }
                   6662:               unless ($ids) {
                   6663: # alias?
                   6664: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      6665:               }
1.37      www      6666:               if ($ids) {
                   6667: # ------------------------------------------------------------------- Has ID(s)
                   6668:                  my @possibilities=split(/\,/,$ids);
1.39      www      6669:                  if ($#possibilities==0) {
                   6670: # ----------------------------------------------- There is only one possibility
1.37      www      6671: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 6672: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6673: 						    $resid,$thisfn);
1.249     www      6674:                  } elsif (!$donotrecurse) {
1.39      www      6675: # ------------------------------------------ There is more than one possibility
                   6676:                      my $realpossible=0;
1.800     albertel 6677:                      foreach my $id (@possibilities) {
                   6678: 			 my $file=$bighash{'src_'.$id};
1.39      www      6679:                          if (&allowed('bre',$file)) {
1.800     albertel 6680:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      6681:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   6682: 				$realpossible++;
1.626     albertel 6683:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6684: 						    $resid,$thisfn);
1.39      www      6685:                             }
                   6686: 			 }
1.191     harris41 6687:                      }
1.39      www      6688: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      6689:                  } else {
                   6690:                      $syval='';
1.37      www      6691:                  }
                   6692: 	      }
                   6693:               untie(%bighash)
1.481     raeburn  6694:            }
1.31      www      6695:         }
1.62      www      6696:         if ($syval) {
1.620     albertel 6697: 	    return $env{$cache_str}=$syval;
1.62      www      6698:         }
1.31      www      6699:     }
1.44      www      6700:     &appenv('request.ambiguous' => $thisfn);
1.620     albertel 6701:     return $env{$cache_str}='';
1.31      www      6702: }
                   6703: 
                   6704: # ---------------------------------------------------------- Return random seed
                   6705: 
1.32      www      6706: sub numval {
                   6707:     my $txt=shift;
                   6708:     $txt=~tr/A-J/0-9/;
                   6709:     $txt=~tr/a-j/0-9/;
                   6710:     $txt=~tr/K-T/0-9/;
                   6711:     $txt=~tr/k-t/0-9/;
                   6712:     $txt=~tr/U-Z/0-5/;
                   6713:     $txt=~tr/u-z/0-5/;
                   6714:     $txt=~s/\D//g;
1.564     albertel 6715:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      6716:     return int($txt);
1.368     albertel 6717: }
                   6718: 
1.484     albertel 6719: sub numval2 {
                   6720:     my $txt=shift;
                   6721:     $txt=~tr/A-J/0-9/;
                   6722:     $txt=~tr/a-j/0-9/;
                   6723:     $txt=~tr/K-T/0-9/;
                   6724:     $txt=~tr/k-t/0-9/;
                   6725:     $txt=~tr/U-Z/0-5/;
                   6726:     $txt=~tr/u-z/0-5/;
                   6727:     $txt=~s/\D//g;
                   6728:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   6729:     my $total;
                   6730:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 6731:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 6732:     return int($total);
                   6733: }
                   6734: 
1.575     albertel 6735: sub numval3 {
                   6736:     use integer;
                   6737:     my $txt=shift;
                   6738:     $txt=~tr/A-J/0-9/;
                   6739:     $txt=~tr/a-j/0-9/;
                   6740:     $txt=~tr/K-T/0-9/;
                   6741:     $txt=~tr/k-t/0-9/;
                   6742:     $txt=~tr/U-Z/0-5/;
                   6743:     $txt=~tr/u-z/0-5/;
                   6744:     $txt=~s/\D//g;
                   6745:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   6746:     my $total;
                   6747:     foreach my $val (@txts) { $total+=$val; }
                   6748:     if ($_64bit) { $total=(($total<<32)>>32); }
                   6749:     return $total;
                   6750: }
                   6751: 
1.675     albertel 6752: sub digest {
                   6753:     my ($data)=@_;
                   6754:     my $digest=&Digest::MD5::md5($data);
                   6755:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   6756:     my ($e,$f);
                   6757:     {
                   6758:         use integer;
                   6759:         $e=($a+$b);
                   6760:         $f=($c+$d);
                   6761:         if ($_64bit) {
                   6762:             $e=(($e<<32)>>32);
                   6763:             $f=(($f<<32)>>32);
                   6764:         }
                   6765:     }
                   6766:     if (wantarray) {
                   6767: 	return ($e,$f);
                   6768:     } else {
                   6769: 	my $g;
                   6770: 	{
                   6771: 	    use integer;
                   6772: 	    $g=($e+$f);
                   6773: 	    if ($_64bit) {
                   6774: 		$g=(($g<<32)>>32);
                   6775: 	    }
                   6776: 	}
                   6777: 	return $g;
                   6778:     }
                   6779: }
                   6780: 
1.368     albertel 6781: sub latest_rnd_algorithm_id {
1.675     albertel 6782:     return '64bit5';
1.366     albertel 6783: }
1.32      www      6784: 
1.503     albertel 6785: sub get_rand_alg {
                   6786:     my ($courseid)=@_;
1.790     albertel 6787:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 6788:     if ($courseid) {
1.620     albertel 6789: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 6790:     }
                   6791:     return &latest_rnd_algorithm_id();
                   6792: }
                   6793: 
1.562     albertel 6794: sub validCODE {
                   6795:     my ($CODE)=@_;
                   6796:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   6797:     return 0;
                   6798: }
                   6799: 
1.491     albertel 6800: sub getCODE {
1.620     albertel 6801:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 6802:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   6803: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   6804: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 6805: 	return $Apache::lonhomework::history{'resource.CODE'};
                   6806:     }
                   6807:     return undef;
                   6808: }
                   6809: 
1.31      www      6810: sub rndseed {
1.155     albertel 6811:     my ($symb,$courseid,$domain,$username)=@_;
1.366     albertel 6812: 
1.790     albertel 6813:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.155     albertel 6814:     if (!$symb) {
1.366     albertel 6815: 	unless ($symb=$wsymb) { return time; }
                   6816:     }
                   6817:     if (!$courseid) { $courseid=$wcourseid; }
                   6818:     if (!$domain) { $domain=$wdomain; }
                   6819:     if (!$username) { $username=$wusername }
1.503     albertel 6820:     my $which=&get_rand_alg();
1.803     albertel 6821: 
1.491     albertel 6822:     if (defined(&getCODE())) {
1.675     albertel 6823: 	if ($which eq '64bit5') {
                   6824: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   6825: 	} elsif ($which eq '64bit4') {
1.575     albertel 6826: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   6827: 	} else {
                   6828: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   6829: 	}
1.675     albertel 6830:     } elsif ($which eq '64bit5') {
                   6831: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 6832:     } elsif ($which eq '64bit4') {
                   6833: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 6834:     } elsif ($which eq '64bit3') {
                   6835: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 6836:     } elsif ($which eq '64bit2') {
                   6837: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 6838:     } elsif ($which eq '64bit') {
                   6839: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   6840:     }
                   6841:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   6842: }
                   6843: 
                   6844: sub rndseed_32bit {
                   6845:     my ($symb,$courseid,$domain,$username)=@_;
                   6846:     {
                   6847: 	use integer;
                   6848: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   6849: 	my $symbseed=numval($symb) << 22;
                   6850: 	my $namechck=unpack("%32C*",$username) << 17;
                   6851: 	my $nameseed=numval($username) << 12;
                   6852: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   6853: 	my $courseseed=unpack("%32C*",$courseid);
                   6854: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 6855: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6856: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 6857: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 6858: 	return $num;
                   6859:     }
                   6860: }
                   6861: 
                   6862: sub rndseed_64bit {
                   6863:     my ($symb,$courseid,$domain,$username)=@_;
                   6864:     {
                   6865: 	use integer;
                   6866: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   6867: 	my $symbseed=numval($symb) << 10;
                   6868: 	my $namechck=unpack("%32S*",$username);
                   6869: 	
                   6870: 	my $nameseed=numval($username) << 21;
                   6871: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   6872: 	my $courseseed=unpack("%32S*",$courseid);
                   6873: 	
                   6874: 	my $num1=$symbchck+$symbseed+$namechck;
                   6875: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6876: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6877: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 6878: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 6879: 	return "$num1,$num2";
1.155     albertel 6880:     }
1.366     albertel 6881: }
                   6882: 
1.443     albertel 6883: sub rndseed_64bit2 {
                   6884:     my ($symb,$courseid,$domain,$username)=@_;
                   6885:     {
                   6886: 	use integer;
                   6887: 	# strings need to be an even # of cahracters long, it it is odd the
                   6888:         # last characters gets thrown away
                   6889: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6890: 	my $symbseed=numval($symb) << 10;
                   6891: 	my $namechck=unpack("%32S*",$username.' ');
                   6892: 	
                   6893: 	my $nameseed=numval($username) << 21;
1.501     albertel 6894: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6895: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6896: 	
                   6897: 	my $num1=$symbchck+$symbseed+$namechck;
                   6898: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6899: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6900: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 6901: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 6902: 	return "$num1,$num2";
                   6903:     }
                   6904: }
                   6905: 
                   6906: sub rndseed_64bit3 {
                   6907:     my ($symb,$courseid,$domain,$username)=@_;
                   6908:     {
                   6909: 	use integer;
                   6910: 	# strings need to be an even # of cahracters long, it it is odd the
                   6911:         # last characters gets thrown away
                   6912: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6913: 	my $symbseed=numval2($symb) << 10;
                   6914: 	my $namechck=unpack("%32S*",$username.' ');
                   6915: 	
                   6916: 	my $nameseed=numval2($username) << 21;
1.443     albertel 6917: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6918: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6919: 	
                   6920: 	my $num1=$symbchck+$symbseed+$namechck;
                   6921: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6922: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6923: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 6924: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6925: 	
1.503     albertel 6926: 	return "$num1:$num2";
1.443     albertel 6927:     }
                   6928: }
                   6929: 
1.575     albertel 6930: sub rndseed_64bit4 {
                   6931:     my ($symb,$courseid,$domain,$username)=@_;
                   6932:     {
                   6933: 	use integer;
                   6934: 	# strings need to be an even # of cahracters long, it it is odd the
                   6935:         # last characters gets thrown away
                   6936: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6937: 	my $symbseed=numval3($symb) << 10;
                   6938: 	my $namechck=unpack("%32S*",$username.' ');
                   6939: 	
                   6940: 	my $nameseed=numval3($username) << 21;
                   6941: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6942: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6943: 	
                   6944: 	my $num1=$symbchck+$symbseed+$namechck;
                   6945: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6946: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6947: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 6948: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6949: 	
                   6950: 	return "$num1:$num2";
                   6951:     }
                   6952: }
                   6953: 
1.675     albertel 6954: sub rndseed_64bit5 {
                   6955:     my ($symb,$courseid,$domain,$username)=@_;
                   6956:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   6957:     return "$num1:$num2";
                   6958: }
                   6959: 
1.366     albertel 6960: sub rndseed_CODE_64bit {
                   6961:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 6962:     {
1.366     albertel 6963: 	use integer;
1.443     albertel 6964: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 6965: 	my $symbseed=numval2($symb);
1.491     albertel 6966: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   6967: 	my $CODEseed=numval(&getCODE());
1.443     albertel 6968: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 6969: 	my $num1=$symbseed+$CODEchck;
                   6970: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 6971: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   6972: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 6973: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   6974: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 6975: 	return "$num1:$num2";
1.366     albertel 6976:     }
                   6977: }
                   6978: 
1.575     albertel 6979: sub rndseed_CODE_64bit4 {
                   6980:     my ($symb,$courseid,$domain,$username)=@_;
                   6981:     {
                   6982: 	use integer;
                   6983: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   6984: 	my $symbseed=numval3($symb);
                   6985: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   6986: 	my $CODEseed=numval3(&getCODE());
                   6987: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6988: 	my $num1=$symbseed+$CODEchck;
                   6989: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 6990: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   6991: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 6992: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   6993: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   6994: 	return "$num1:$num2";
                   6995:     }
                   6996: }
                   6997: 
1.675     albertel 6998: sub rndseed_CODE_64bit5 {
                   6999:     my ($symb,$courseid,$domain,$username)=@_;
                   7000:     my $code = &getCODE();
                   7001:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   7002:     return "$num1:$num2";
                   7003: }
                   7004: 
1.366     albertel 7005: sub setup_random_from_rndseed {
                   7006:     my ($rndseed)=@_;
1.503     albertel 7007:     if ($rndseed =~/([,:])/) {
                   7008: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 7009: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   7010:     } else {
                   7011: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 7012:     }
1.36      albertel 7013: }
                   7014: 
1.474     albertel 7015: sub latest_receipt_algorithm_id {
                   7016:     return 'receipt2';
                   7017: }
                   7018: 
1.480     www      7019: sub recunique {
                   7020:     my $fucourseid=shift;
                   7021:     my $unique;
1.620     albertel 7022:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   7023: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      7024:     } else {
                   7025: 	$unique=$perlvar{'lonReceipt'};
                   7026:     }
                   7027:     return unpack("%32C*",$unique);
                   7028: }
                   7029: 
                   7030: sub recprefix {
                   7031:     my $fucourseid=shift;
                   7032:     my $prefix;
1.620     albertel 7033:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   7034: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      7035:     } else {
                   7036: 	$prefix=$perlvar{'lonHostID'};
                   7037:     }
                   7038:     return unpack("%32C*",$prefix);
                   7039: }
                   7040: 
1.76      www      7041: sub ireceipt {
1.474     albertel 7042:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.76      www      7043:     my $cuname=unpack("%32C*",$funame);
                   7044:     my $cudom=unpack("%32C*",$fudom);
                   7045:     my $cucourseid=unpack("%32C*",$fucourseid);
                   7046:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      7047:     my $cunique=&recunique($fucourseid);
1.474     albertel 7048:     my $cpart=unpack("%32S*",$part);
1.480     www      7049:     my $return =&recprefix($fucourseid).'-';
1.620     albertel 7050:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   7051: 	$env{'request.state'} eq 'construct') {
1.790     albertel 7052: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 7053: 			       
                   7054: 	$return.= ($cunique%$cuname+
                   7055: 		   $cunique%$cudom+
                   7056: 		   $cusymb%$cuname+
                   7057: 		   $cusymb%$cudom+
                   7058: 		   $cucourseid%$cuname+
                   7059: 		   $cucourseid%$cudom+
                   7060: 		   $cpart%$cuname+
                   7061: 		   $cpart%$cudom);
                   7062:     } else {
                   7063: 	$return.= ($cunique%$cuname+
                   7064: 		   $cunique%$cudom+
                   7065: 		   $cusymb%$cuname+
                   7066: 		   $cusymb%$cudom+
                   7067: 		   $cucourseid%$cuname+
                   7068: 		   $cucourseid%$cudom);
                   7069:     }
                   7070:     return $return;
1.76      www      7071: }
                   7072: 
                   7073: sub receipt {
1.474     albertel 7074:     my ($part)=@_;
1.790     albertel 7075:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 7076:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      7077: }
1.260     ng       7078: 
1.790     albertel 7079: sub whichuser {
                   7080:     my ($passedsymb)=@_;
                   7081:     my ($symb,$courseid,$domain,$name,$publicuser);
                   7082:     if (defined($env{'form.grade_symb'})) {
                   7083: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   7084: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   7085: 	if (!$allowed &&
                   7086: 	    exists($env{'request.course.sec'}) &&
                   7087: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   7088: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   7089: 			      '/'.$env{'request.course.sec'});
                   7090: 	}
                   7091: 	if ($allowed) {
                   7092: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   7093: 	    $courseid=$tmp_courseid;
                   7094: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   7095: 	    ($name)=&get_env_multiple('form.grade_username');
                   7096: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   7097: 	}
                   7098:     }
                   7099:     if (!$passedsymb) {
                   7100: 	$symb=&symbread();
                   7101:     } else {
                   7102: 	$symb=$passedsymb;
                   7103:     }
                   7104:     $courseid=$env{'request.course.id'};
                   7105:     $domain=$env{'user.domain'};
                   7106:     $name=$env{'user.name'};
                   7107:     if ($name eq 'public' && $domain eq 'public') {
                   7108: 	if (!defined($env{'form.username'})) {
                   7109: 	    $env{'form.username'}.=time.rand(10000000);
                   7110: 	}
                   7111: 	$name.=$env{'form.username'};
                   7112:     }
                   7113:     return ($symb,$courseid,$domain,$name,$publicuser);
                   7114: 
                   7115: }
                   7116: 
1.36      albertel 7117: # ------------------------------------------------------------ Serves up a file
1.472     albertel 7118: # returns either the contents of the file or 
                   7119: # -1 if the file doesn't exist
1.481     raeburn  7120: #
                   7121: # if the target is a file that was uploaded via DOCS, 
                   7122: # a check will be made to see if a current copy exists on the local server,
                   7123: # if it does this will be served, otherwise a copy will be retrieved from
                   7124: # the home server for the course and stored in /home/httpd/html/userfiles on
                   7125: # the local server.   
1.472     albertel 7126: 
1.36      albertel 7127: sub getfile {
1.538     albertel 7128:     my ($file) = @_;
1.609     banghart 7129:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 7130:     &repcopy($file);
                   7131:     return &readfile($file);
                   7132: }
                   7133: 
                   7134: sub repcopy_userfile {
                   7135:     my ($file)=@_;
1.609     banghart 7136:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 7137:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 7138:     my ($cdom,$cnum,$filename) = 
1.811     albertel 7139: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 7140:     my ($info,$rtncode);
                   7141:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   7142:     if (-e "$file") {
                   7143: 	my @fileinfo = stat($file);
                   7144: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 7145: 	if ($lwpresp ne 'ok') {
                   7146: 	    if ($rtncode eq '404') {
1.538     albertel 7147: 		unlink($file);
1.482     albertel 7148: 	    }
1.517     albertel 7149: 	    #my $ua=new LWP::UserAgent;
1.538     albertel 7150: 	    #my $request=new HTTP::Request('GET',&tokenwrapper($uri));
1.517     albertel 7151: 	    #my $response=$ua->request($request);
                   7152: 	    #if ($response->is_success()) {
                   7153: 	#	return $response->content;
                   7154: 	#    } else {
                   7155: 	#	return -1;
                   7156: 	#    }
1.482     albertel 7157: 	    return -1;
                   7158: 	}
                   7159: 	if ($info < $fileinfo[9]) {
1.607     raeburn  7160: 	    return 'ok';
1.482     albertel 7161: 	}
                   7162: 	$info = '';
1.538     albertel 7163: 	$lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 7164: 	if ($lwpresp ne 'ok') {
                   7165: 	    return -1;
                   7166: 	}
                   7167:     } else {
1.538     albertel 7168: 	my $lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 7169: 	if ($lwpresp ne 'ok') {
1.824.2.2! albertel 7170: 	    return -1;
1.482     albertel 7171: 	}
                   7172: 	my @parts = ($cdom,$cnum); 
                   7173: 	if ($filename =~ m|^(.+)/[^/]+$|) {
                   7174: 	    push @parts, split(/\//,$1);
1.518     albertel 7175: 	}
1.538     albertel 7176: 	my $path = $perlvar{'lonDocRoot'}.'/userfiles';
1.482     albertel 7177: 	foreach my $part (@parts) {
                   7178: 	    $path .= '/'.$part;
                   7179: 	    if (!-e $path) {
                   7180: 		mkdir($path,0770);
                   7181: 	    }
                   7182: 	}
                   7183:     }
1.538     albertel 7184:     open(FILE,">$file");
1.482     albertel 7185:     print FILE $info;
                   7186:     close(FILE);
1.607     raeburn  7187:     return 'ok';
1.481     raeburn  7188: }
                   7189: 
1.517     albertel 7190: sub tokenwrapper {
                   7191:     my $uri=shift;
1.552     albertel 7192:     $uri=~s|^http\://([^/]+)||;
                   7193:     $uri=~s|^/||;
1.620     albertel 7194:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 7195:     my $token=$1;
1.552     albertel 7196:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   7197:     if ($udom && $uname && $file) {
                   7198: 	$file=~s|(\?\.*)*$||;
1.620     albertel 7199:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
1.552     albertel 7200:         return 'http://'.$hostname{ &homeserver($uname,$udom)}.'/'.$uri.
1.517     albertel 7201:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   7202:                                '&tokenissued='.$perlvar{'lonHostID'};
                   7203:     } else {
                   7204:         return '/adm/notfound.html';
                   7205:     }
                   7206: }
                   7207: 
1.481     raeburn  7208: sub getuploaded {
                   7209:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   7210:     $uri=~s/^\///;
                   7211:     $uri = 'http://'.$hostname{ &homeserver($cnum,$cdom)}.'/raw/'.$uri;
                   7212:     my $ua=new LWP::UserAgent;
                   7213:     my $request=new HTTP::Request($reqtype,$uri);
                   7214:     my $response=$ua->request($request);
                   7215:     $$rtncode = $response->code;
1.482     albertel 7216:     if (! $response->is_success()) {
                   7217: 	return 'failed';
                   7218:     }      
                   7219:     if ($reqtype eq 'HEAD') {
1.486     www      7220: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 7221:     } elsif ($reqtype eq 'GET') {
                   7222: 	$$info = $response->content;
1.472     albertel 7223:     }
1.482     albertel 7224:     return 'ok';
1.36      albertel 7225: }
                   7226: 
1.481     raeburn  7227: sub readfile {
                   7228:     my $file = shift;
                   7229:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   7230:     my $fh;
                   7231:     open($fh,"<$file");
                   7232:     my $a='';
1.800     albertel 7233:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  7234:     return $a;
                   7235: }
                   7236: 
1.36      albertel 7237: sub filelocation {
1.590     banghart 7238:     my ($dir,$file) = @_;
                   7239:     my $location;
                   7240:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 7241: 
                   7242:     if ($file =~ m-^/adm/-) {
                   7243: 	$file=~s-^/adm/wrapper/-/-;
                   7244: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   7245:     }
1.590     banghart 7246:     if ($file=~m:^/~:) { # is a contruction space reference
                   7247:         $location = $file;
                   7248:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 7249:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 7250: 	# is a correct contruction space reference
                   7251:         $location = $file;
1.609     banghart 7252:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 7253:         my ($udom,$uname,$filename)=
1.811     albertel 7254:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 7255:         my $home=&homeserver($uname,$udom);
                   7256:         my $is_me=0;
                   7257:         my @ids=&current_machine_ids();
                   7258:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   7259:         if ($is_me) {
1.740     www      7260:   	    $location=&propath($udom,$uname).
1.590     banghart 7261:   	      '/userfiles/'.$filename;
                   7262:         } else {
                   7263:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   7264:   	      $udom.'/'.$uname.'/'.$filename;
                   7265:         }
                   7266:     } else {
                   7267:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   7268:         $file=~s:^/res/:/:;
                   7269:         if ( !( $file =~ m:^/:) ) {
                   7270:             $location = $dir. '/'.$file;
                   7271:         } else {
                   7272:             $location = '/home/httpd/html/res'.$file;
                   7273:         }
1.59      albertel 7274:     }
1.590     banghart 7275:     $location=~s://+:/:g; # remove duplicate /
                   7276:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
                   7277:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   7278:     return $location;
1.46      www      7279: }
1.36      albertel 7280: 
1.46      www      7281: sub hreflocation {
                   7282:     my ($dir,$file)=@_;
1.460     albertel 7283:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666     albertel 7284: 	$file=filelocation($dir,$file);
1.700     albertel 7285:     } elsif ($file=~m-^/adm/-) {
                   7286: 	$file=~s-^/adm/wrapper/-/-;
                   7287: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 7288:     }
                   7289:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   7290: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 7291:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   7292: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 7293:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 7294: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 7295: 	    -/uploaded/$1/$2/-x;
1.46      www      7296:     }
1.462     albertel 7297:     return $file;
1.465     albertel 7298: }
                   7299: 
                   7300: sub current_machine_domains {
                   7301:     my $hostname=$hostname{$perlvar{'lonHostID'}};
                   7302:     my @domains;
                   7303:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  7304: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 7305: 	if ($hostname eq $name) {
                   7306: 	    push(@domains,$hostdom{$id});
                   7307: 	}
                   7308:     }
                   7309:     return @domains;
                   7310: }
                   7311: 
                   7312: sub current_machine_ids {
                   7313:     my $hostname=$hostname{$perlvar{'lonHostID'}};
                   7314:     my @ids;
                   7315:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  7316: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 7317: 	if ($hostname eq $name) {
                   7318: 	    push(@ids,$id);
                   7319: 	}
                   7320:     }
                   7321:     return @ids;
1.31      www      7322: }
                   7323: 
1.824     raeburn  7324: sub additional_machine_domains {
                   7325:     my @domains;
                   7326:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   7327:     while( my $line = <$fh>) {
                   7328:         $line =~ s/\s//g;
                   7329:         push(@domains,$line);
                   7330:     }
                   7331:     return @domains;
                   7332: }
                   7333: 
                   7334: sub default_login_domain {
                   7335:     my $domain = $perlvar{'lonDefDomain'};
                   7336:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   7337:     foreach my $posdom (&current_machine_domains(),
                   7338:                         &additional_machine_domains()) {
                   7339:         if (lc($posdom) eq lc($testdomain)) {
                   7340:             $domain=$posdom;
                   7341:             last;
                   7342:         }
                   7343:     }
                   7344:     return $domain;
                   7345: }
                   7346: 
1.31      www      7347: # ------------------------------------------------------------- Declutters URLs
                   7348: 
                   7349: sub declutter {
                   7350:     my $thisfn=shift;
1.569     albertel 7351:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 7352:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      7353:     $thisfn=~s/^\///;
1.697     albertel 7354:     $thisfn=~s|^adm/wrapper/||;
                   7355:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      7356:     $thisfn=~s/^res\///;
1.235     www      7357:     $thisfn=~s/\?.+$//;
1.268     www      7358:     return $thisfn;
                   7359: }
                   7360: 
                   7361: # ------------------------------------------------------------- Clutter up URLs
                   7362: 
                   7363: sub clutter {
                   7364:     my $thisfn='/'.&declutter(shift);
1.609     banghart 7365:     unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) { 
1.270     www      7366:        $thisfn='/res'.$thisfn; 
                   7367:     }
1.694     albertel 7368:     if ($thisfn !~m|/adm|) {
1.695     albertel 7369: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 7370: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 7371: 	} else {
                   7372: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   7373: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 7374: 	    if ($embstyle eq 'ssi'
                   7375: 		|| ($embstyle eq 'hdn')
                   7376: 		|| ($embstyle eq 'rat')
                   7377: 		|| ($embstyle eq 'prv')
                   7378: 		|| ($embstyle eq 'ign')) {
                   7379: 		#do nothing with these
                   7380: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 7381: 		|| ($embstyle eq 'emb')
                   7382: 		|| ($embstyle eq 'wrp')) {
                   7383: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 7384: 	    } elsif ($embstyle eq 'unk'
                   7385: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 7386: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 7387: 	    } else {
1.718     www      7388: #		&logthis("Got a blank emb style");
1.695     albertel 7389: 	    }
1.694     albertel 7390: 	}
                   7391:     }
1.31      www      7392:     return $thisfn;
1.12      www      7393: }
                   7394: 
1.787     albertel 7395: sub clutter_with_no_wrapper {
                   7396:     my $uri = &clutter(shift);
                   7397:     if ($uri =~ m-^/adm/-) {
                   7398: 	$uri =~ s-^/adm/wrapper/-/-;
                   7399: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   7400:     }
                   7401:     return $uri;
                   7402: }
                   7403: 
1.557     albertel 7404: sub freeze_escape {
                   7405:     my ($value)=@_;
                   7406:     if (ref($value)) {
                   7407: 	$value=&nfreeze($value);
                   7408: 	return '__FROZEN__'.&escape($value);
                   7409:     }
                   7410:     return &escape($value);
                   7411: }
                   7412: 
1.11      www      7413: 
1.557     albertel 7414: sub thaw_unescape {
                   7415:     my ($value)=@_;
                   7416:     if ($value =~ /^__FROZEN__/) {
                   7417: 	substr($value,0,10,undef);
                   7418: 	$value=&unescape($value);
                   7419: 	return &thaw($value);
                   7420:     }
                   7421:     return &unescape($value);
                   7422: }
                   7423: 
1.436     albertel 7424: sub correct_line_ends {
                   7425:     my ($result)=@_;
                   7426:     $$result =~s/\r\n/\n/mg;
                   7427:     $$result =~s/\r/\n/mg;
1.415     albertel 7428: }
1.1       albertel 7429: # ================================================================ Main Program
                   7430: 
1.184     www      7431: sub goodbye {
1.204     albertel 7432:    &logthis("Starting Shut down");
1.443     albertel 7433: #not converted to using infrastruture and probably shouldn't be
1.599     albertel 7434:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&freeze(\%badServerCache))));
1.443     albertel 7435: #converted
1.599     albertel 7436: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
                   7437:    &logthis(sprintf("%-20s is %s",'%homecache',length(&freeze(\%homecache))));
                   7438: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&freeze(\%titlecache))));
                   7439: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&freeze(\%courseresdatacache))));
1.425     albertel 7440: #1.1 only
1.599     albertel 7441: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&freeze(\%userresdatacache))));
                   7442: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&freeze(\%getsectioncache))));
                   7443: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&freeze(\%courseresversioncache))));
                   7444: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&freeze(\%resversioncache))));
                   7445:    &logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
                   7446:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   7447:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      7448:    &flushcourselogs();
                   7449:    &logthis("Shutting down");
                   7450: }
                   7451: 
1.179     www      7452: BEGIN {
1.228     harris41 7453: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
1.195     www      7454:     unless ($readit) {
1.217     harris41 7455: {
1.781     raeburn  7456:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   7457:     %perlvar = (%perlvar,%{$configvars});
1.227     harris41 7458: }
1.1       albertel 7459: 
1.327     albertel 7460: # ------------------------------------------------------------ Read domain file
                   7461: {
                   7462:     %domaindescription = ();
                   7463:     %domain_auth_def = ();
                   7464:     %domain_auth_arg_def = ();
1.448     albertel 7465:     my $fh;
                   7466:     if (open($fh,"<".$Apache::lonnet::perlvar{'lonTabDir'}.'/domain.tab')) {
1.800     albertel 7467: 	while (my $line = <$fh>) {
                   7468:            next if ($line =~ /^(\#|\s*$)/);
1.390     matthew  7469: #           next if /^\#/;
1.801     foxr     7470:            chomp $line;
1.403     www      7471:            my ($domain, $domain_description, $def_auth, $def_auth_arg,
1.800     albertel 7472: 	       $def_lang, $city, $longi, $lati, $primary) = split(/:/,$line,9);
1.403     www      7473: 	   $domain_auth_def{$domain}=$def_auth;
1.327     albertel 7474:            $domain_auth_arg_def{$domain}=$def_auth_arg;
1.403     www      7475: 	   $domaindescription{$domain}=$domain_description;
                   7476: 	   $domain_lang_def{$domain}=$def_lang;
                   7477: 	   $domain_city{$domain}=$city;
                   7478: 	   $domain_longi{$domain}=$longi;
                   7479: 	   $domain_lati{$domain}=$lati;
1.685     raeburn  7480:            $domain_primary{$domain}=$primary;
1.403     www      7481: 
1.448     albertel 7482:  #         &logthis("Domain.tab: $domain, $domain_auth_def{$domain}, $domain_auth_arg_def{$domain},$domaindescription{$domain}");
1.327     albertel 7483: #          &logthis("Domain.tab: $domain ".$domaindescription{$domain} );
1.448     albertel 7484: 	}
1.327     albertel 7485:     }
1.448     albertel 7486:     close ($fh);
1.327     albertel 7487: }
                   7488: 
                   7489: 
1.1       albertel 7490: # ------------------------------------------------------------- Read hosts file
                   7491: {
1.448     albertel 7492:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
1.1       albertel 7493: 
                   7494:     while (my $configline=<$config>) {
1.303     matthew  7495:        next if ($configline =~ /^(\#|\s*$)/);
1.154     www      7496:        chomp($configline);
1.595     albertel 7497:        my ($id,$domain,$role,$name)=split(/:/,$configline);
1.597     albertel 7498:        $name=~s/\s//g;
1.595     albertel 7499:        if ($id && $domain && $role && $name) {
1.252     albertel 7500: 	 $hostname{$id}=$name;
                   7501: 	 $hostdom{$id}=$domain;
                   7502: 	 if ($role eq 'library') { $libserv{$id}=$name; }
1.245     www      7503:        }
1.1       albertel 7504:     }
1.448     albertel 7505:     close($config);
1.619     albertel 7506:     # FIXME: dev server don't want this, production servers _do_ want this
1.654     albertel 7507:     #&get_iphost();
1.1       albertel 7508: }
                   7509: 
1.598     albertel 7510: sub get_iphost {
                   7511:     if (%iphost) { return %iphost; }
1.653     albertel 7512:     my %name_to_ip;
1.598     albertel 7513:     foreach my $id (keys(%hostname)) {
                   7514: 	my $name=$hostname{$id};
1.653     albertel 7515: 	my $ip;
                   7516: 	if (!exists($name_to_ip{$name})) {
                   7517: 	    $ip = gethostbyname($name);
                   7518: 	    if (!$ip || length($ip) ne 4) {
                   7519: 		&logthis("Skipping host $id name $name no IP found\n");
                   7520: 		next;
                   7521: 	    }
                   7522: 	    $ip=inet_ntoa($ip);
                   7523: 	    $name_to_ip{$name} = $ip;
                   7524: 	} else {
                   7525: 	    $ip = $name_to_ip{$name};
1.598     albertel 7526: 	}
                   7527: 	push(@{$iphost{$ip}},$id);
                   7528:     }
                   7529:     return %iphost;
                   7530: }
                   7531: 
1.1       albertel 7532: # ------------------------------------------------------ Read spare server file
                   7533: {
1.448     albertel 7534:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 7535: 
                   7536:     while (my $configline=<$config>) {
                   7537:        chomp($configline);
1.284     matthew  7538:        if ($configline) {
1.784     albertel 7539: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 7540: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 7541: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 7542:        }
                   7543:     }
1.448     albertel 7544:     close($config);
1.1       albertel 7545: }
1.11      www      7546: # ------------------------------------------------------------ Read permissions
                   7547: {
1.448     albertel 7548:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      7549: 
                   7550:     while (my $configline=<$config>) {
1.448     albertel 7551: 	chomp($configline);
                   7552: 	if ($configline) {
                   7553: 	    my ($role,$perm)=split(/ /,$configline);
                   7554: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   7555: 	}
1.11      www      7556:     }
1.448     albertel 7557:     close($config);
1.11      www      7558: }
                   7559: 
                   7560: # -------------------------------------------- Read plain texts for permissions
                   7561: {
1.448     albertel 7562:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      7563: 
                   7564:     while (my $configline=<$config>) {
1.448     albertel 7565: 	chomp($configline);
                   7566: 	if ($configline) {
1.742     raeburn  7567: 	    my ($short,@plain)=split(/:/,$configline);
                   7568:             %{$prp{$short}} = ();
                   7569: 	    if (@plain > 0) {
                   7570:                 $prp{$short}{'std'} = $plain[0];
                   7571:                 for (my $i=1; $i<@plain; $i++) {
                   7572:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   7573:                 }
                   7574:             }
1.448     albertel 7575: 	}
1.135     www      7576:     }
1.448     albertel 7577:     close($config);
1.135     www      7578: }
                   7579: 
                   7580: # ---------------------------------------------------------- Read package table
                   7581: {
1.448     albertel 7582:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      7583: 
                   7584:     while (my $configline=<$config>) {
1.483     albertel 7585: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 7586: 	chomp($configline);
                   7587: 	my ($short,$plain)=split(/:/,$configline);
                   7588: 	my ($pack,$name)=split(/\&/,$short);
                   7589: 	if ($plain ne '') {
                   7590: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   7591: 	    $packagetab{$short}=$plain; 
                   7592: 	}
1.11      www      7593:     }
1.448     albertel 7594:     close($config);
1.329     matthew  7595: }
                   7596: 
                   7597: # ------------- set up temporary directory
                   7598: {
                   7599:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   7600: 
1.11      www      7601: }
                   7602: 
1.794     albertel 7603: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   7604: 				'compress_threshold'=> 20_000,
                   7605:  			        });
1.185     www      7606: 
1.281     www      7607: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      7608: $dumpcount=0;
1.22      www      7609: 
1.163     harris41 7610: &logtouch();
1.672     albertel 7611: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      7612: $readit=1;
1.564     albertel 7613:     {
                   7614: 	use integer;
                   7615: 	my $test=(2**32)+1;
1.568     albertel 7616: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 7617: 	&logthis(" Detected 64bit platform ($_64bit)");
                   7618:     }
1.195     www      7619: }
1.1       albertel 7620: }
1.179     www      7621: 
1.1       albertel 7622: 1;
1.191     harris41 7623: __END__
                   7624: 
1.243     albertel 7625: =pod
                   7626: 
1.191     harris41 7627: =head1 NAME
                   7628: 
1.243     albertel 7629: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 7630: 
                   7631: =head1 SYNOPSIS
                   7632: 
1.243     albertel 7633: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 7634: 
                   7635:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   7636: 
1.243     albertel 7637: Common parameters:
                   7638: 
                   7639: =over 4
                   7640: 
                   7641: =item *
                   7642: 
                   7643: $uname : an internal username (if $cname expecting a course Id specifically)
                   7644: 
                   7645: =item *
                   7646: 
                   7647: $udom : a domain (if $cdom expecting a course's domain specifically)
                   7648: 
                   7649: =item *
                   7650: 
                   7651: $symb : a resource instance identifier
                   7652: 
                   7653: =item *
                   7654: 
                   7655: $namespace : the name of a .db file that contains the data needed or
                   7656: being set.
                   7657: 
                   7658: =back
                   7659: 
1.394     bowersj2 7660: =head1 OVERVIEW
1.191     harris41 7661: 
1.394     bowersj2 7662: lonnet provides subroutines which interact with the
                   7663: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   7664: about classes, users, and resources.
1.243     albertel 7665: 
                   7666: For many of these objects you can also use this to store data about
                   7667: them or modify them in various ways.
1.191     harris41 7668: 
1.394     bowersj2 7669: =head2 Symbs
1.191     harris41 7670: 
1.394     bowersj2 7671: To identify a specific instance of a resource, LON-CAPA uses symbols
                   7672: or "symbs"X<symb>. These identifiers are built from the URL of the
                   7673: map, the resource number of the resource in the map, and the URL of
                   7674: the resource itself. The latter is somewhat redundant, but might help
                   7675: if maps change.
                   7676: 
                   7677: An example is
                   7678: 
                   7679:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   7680: 
                   7681: The respective map entry is
                   7682: 
                   7683:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   7684:   title="Problem 2">
                   7685:  </resource>
                   7686: 
                   7687: Symbs are used by the random number generator, as well as to store and
                   7688: restore data specific to a certain instance of for example a problem.
                   7689: 
                   7690: =head2 Storing And Retrieving Data
                   7691: 
                   7692: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   7693: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   7694: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   7695: is is the non-critical message twin of cstore. These functions are for
                   7696: handlers to store a perl hash to a user's permanent data space in an
                   7697: easy manner, and to retrieve it again on another call. It is expected
                   7698: that a handler would use this once at the beginning to retrieve data,
                   7699: and then again once at the end to send only the new data back.
                   7700: 
                   7701: The data is stored in the user's data directory on the user's
                   7702: homeserver under the ID of the course.
                   7703: 
                   7704: The hash that is returned by restore will have all of the previous
                   7705: value for all of the elements of the hash.
                   7706: 
                   7707: Example:
                   7708: 
                   7709:  #creating a hash
                   7710:  my %hash;
                   7711:  $hash{'foo'}='bar';
                   7712: 
                   7713:  #storing it
                   7714:  &Apache::lonnet::cstore(\%hash);
                   7715: 
                   7716:  #changing a value
                   7717:  $hash{'foo'}='notbar';
                   7718: 
                   7719:  #adding a new value
                   7720:  $hash{'bar'}='foo';
                   7721:  &Apache::lonnet::cstore(\%hash);
                   7722: 
                   7723:  #retrieving the hash
                   7724:  my %history=&Apache::lonnet::restore();
                   7725: 
                   7726:  #print the hash
                   7727:  foreach my $key (sort(keys(%history))) {
                   7728:    print("\%history{$key} = $history{$key}");
                   7729:  }
                   7730: 
                   7731: Will print out:
1.191     harris41 7732: 
1.394     bowersj2 7733:  %history{1:foo} = bar
                   7734:  %history{1:keys} = foo:timestamp
                   7735:  %history{1:timestamp} = 990455579
                   7736:  %history{2:bar} = foo
                   7737:  %history{2:foo} = notbar
                   7738:  %history{2:keys} = foo:bar:timestamp
                   7739:  %history{2:timestamp} = 990455580
                   7740:  %history{bar} = foo
                   7741:  %history{foo} = notbar
                   7742:  %history{timestamp} = 990455580
                   7743:  %history{version} = 2
                   7744: 
                   7745: Note that the special hash entries C<keys>, C<version> and
                   7746: C<timestamp> were added to the hash. C<version> will be equal to the
                   7747: total number of versions of the data that have been stored. The
                   7748: C<timestamp> attribute will be the UNIX time the hash was
                   7749: stored. C<keys> is available in every historical section to list which
                   7750: keys were added or changed at a specific historical revision of a
                   7751: hash.
                   7752: 
                   7753: B<Warning>: do not store the hash that restore returns directly. This
                   7754: will cause a mess since it will restore the historical keys as if the
                   7755: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 7756: 
1.394     bowersj2 7757: Calling convention:
1.191     harris41 7758: 
1.394     bowersj2 7759:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   7760:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 7761: 
1.394     bowersj2 7762: For more detailed information, see lonnet specific documentation.
1.191     harris41 7763: 
1.394     bowersj2 7764: =head1 RETURN MESSAGES
1.191     harris41 7765: 
1.394     bowersj2 7766: =over 4
1.191     harris41 7767: 
1.394     bowersj2 7768: =item * B<con_lost>: unable to contact remote host
1.191     harris41 7769: 
1.394     bowersj2 7770: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   7771: when the connection is brought back up
1.191     harris41 7772: 
1.394     bowersj2 7773: =item * B<con_failed>: unable to contact remote host and unable to save message
                   7774: for later delivery
1.191     harris41 7775: 
1.394     bowersj2 7776: =item * B<error:>: an error a occured, a description of the error follows the :
1.191     harris41 7777: 
1.394     bowersj2 7778: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 7779: that was requested
1.191     harris41 7780: 
1.243     albertel 7781: =back
1.191     harris41 7782: 
1.243     albertel 7783: =head1 PUBLIC SUBROUTINES
1.191     harris41 7784: 
1.243     albertel 7785: =head2 Session Environment Functions
1.191     harris41 7786: 
1.243     albertel 7787: =over 4
1.191     harris41 7788: 
1.394     bowersj2 7789: =item * 
                   7790: X<appenv()>
                   7791: B<appenv(%hash)>: the value of %hash is written to
                   7792: the user envirnoment file, and will be restored for each access this
1.620     albertel 7793: user makes during this session, also modifies the %env for the current
1.394     bowersj2 7794: process
1.191     harris41 7795: 
                   7796: =item *
1.394     bowersj2 7797: X<delenv()>
                   7798: B<delenv($regexp)>: removes all items from the session
                   7799: environment file that matches the regular expression in $regexp. The
1.620     albertel 7800: values are also delted from the current processes %env.
1.191     harris41 7801: 
1.795     albertel 7802: =item * get_env_multiple($name) 
                   7803: 
                   7804: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   7805: values may be defined and end up as an array ref.
                   7806: 
                   7807: returns an array of values
                   7808: 
1.243     albertel 7809: =back
                   7810: 
                   7811: =head2 User Information
1.191     harris41 7812: 
1.243     albertel 7813: =over 4
1.191     harris41 7814: 
                   7815: =item *
1.394     bowersj2 7816: X<queryauthenticate()>
                   7817: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 7818: authentication scheme
                   7819: 
                   7820: =item *
1.394     bowersj2 7821: X<authenticate()>
                   7822: B<authenticate($uname,$upass,$udom)>: try to
                   7823: authenticate user from domain's lib servers (first use the current
                   7824: one). C<$upass> should be the users password.
1.191     harris41 7825: 
                   7826: =item *
1.394     bowersj2 7827: X<homeserver()>
                   7828: B<homeserver($uname,$udom)>: find the server which has
                   7829: the user's directory and files (there must be only one), this caches
                   7830: the answer, and also caches if there is a borken connection.
1.191     harris41 7831: 
                   7832: =item *
1.394     bowersj2 7833: X<idget()>
                   7834: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   7835: (IDs are a unique resource in a domain, there must be only 1 ID per
                   7836: username, and only 1 username per ID in a specific domain) (returns
                   7837: hash: id=>name,id=>name)
1.191     harris41 7838: 
                   7839: =item *
1.394     bowersj2 7840: X<idrget()>
                   7841: B<idrget($udom,@unames)>: find the IDs behind a list of
                   7842: usernames (returns hash: name=>id,name=>id)
1.191     harris41 7843: 
                   7844: =item *
1.394     bowersj2 7845: X<idput()>
                   7846: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 7847: 
                   7848: =item *
1.394     bowersj2 7849: X<rolesinit()>
                   7850: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 7851: 
                   7852: =item *
1.551     albertel 7853: X<getsection()>
                   7854: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 7855: course $cname, return section name/number or '' for "not in course"
                   7856: and '-1' for "no section"
                   7857: 
                   7858: =item *
1.394     bowersj2 7859: X<userenvironment()>
                   7860: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 7861: passed in @what from the requested user's environment, returns a hash
                   7862: 
                   7863: =back
                   7864: 
                   7865: =head2 User Roles
                   7866: 
                   7867: =over 4
                   7868: 
                   7869: =item *
                   7870: 
1.810     raeburn  7871: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 7872:  F: full access
                   7873:  U,I,K: authentication modes (cxx only)
                   7874:  '': forbidden
                   7875:  1: user needs to choose course
                   7876:  2: browse allowed
1.766     albertel 7877:  A: passphrase authentication needed
1.243     albertel 7878: 
                   7879: =item *
                   7880: 
                   7881: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   7882: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   7883: and course level
                   7884: 
                   7885: =item *
                   7886: 
                   7887: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   7888: explanation of a user role term
                   7889: 
                   7890: =back
                   7891: 
                   7892: =head2 User Modification
                   7893: 
                   7894: =over 4
                   7895: 
                   7896: =item *
                   7897: 
                   7898: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
                   7899: user for the level given by URL.  Optional start and end dates (leave empty
                   7900: string or zero for "no date")
1.191     harris41 7901: 
                   7902: =item *
                   7903: 
1.243     albertel 7904: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   7905: change a users, password, possible return values are: ok,
                   7906: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   7907: refused
1.191     harris41 7908: 
                   7909: =item *
                   7910: 
1.243     albertel 7911: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 7912: 
                   7913: =item *
                   7914: 
1.243     albertel 7915: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
                   7916: modify user
1.191     harris41 7917: 
                   7918: =item *
                   7919: 
1.286     matthew  7920: modifystudent
                   7921: 
                   7922: modify a students enrollment and identification information.
                   7923: The course id is resolved based on the current users environment.  
                   7924: This means the envoking user must be a course coordinator or otherwise
                   7925: associated with a course.
                   7926: 
1.297     matthew  7927: This call is essentially a wrapper for lonnet::modifyuser and
                   7928: lonnet::modify_student_enrollment
1.286     matthew  7929: 
                   7930: Inputs: 
                   7931: 
                   7932: =over 4
                   7933: 
                   7934: =item B<$udom> Students loncapa domain
                   7935: 
                   7936: =item B<$uname> Students loncapa login name
                   7937: 
                   7938: =item B<$uid> Students id/student number
                   7939: 
                   7940: =item B<$umode> Students authentication mode
                   7941: 
                   7942: =item B<$upass> Students password
                   7943: 
                   7944: =item B<$first> Students first name
                   7945: 
                   7946: =item B<$middle> Students middle name
                   7947: 
                   7948: =item B<$last> Students last name
                   7949: 
                   7950: =item B<$gene> Students generation
                   7951: 
                   7952: =item B<$usec> Students section in course
                   7953: 
                   7954: =item B<$end> Unix time of the roles expiration
                   7955: 
                   7956: =item B<$start> Unix time of the roles start date
                   7957: 
                   7958: =item B<$forceid> If defined, allow $uid to be changed
                   7959: 
                   7960: =item B<$desiredhome> server to use as home server for student
                   7961: 
                   7962: =back
1.297     matthew  7963: 
                   7964: =item *
                   7965: 
                   7966: modify_student_enrollment
                   7967: 
                   7968: Change a students enrollment status in a class.  The environment variable
                   7969: 'role.request.course' must be defined for this function to proceed.
                   7970: 
                   7971: Inputs:
                   7972: 
                   7973: =over 4
                   7974: 
                   7975: =item $udom, students domain
                   7976: 
                   7977: =item $uname, students name
                   7978: 
                   7979: =item $uid, students user id
                   7980: 
                   7981: =item $first, students first name
                   7982: 
                   7983: =item $middle
                   7984: 
                   7985: =item $last
                   7986: 
                   7987: =item $gene
                   7988: 
                   7989: =item $usec
                   7990: 
                   7991: =item $end
                   7992: 
                   7993: =item $start
                   7994: 
                   7995: =back
                   7996: 
1.191     harris41 7997: 
                   7998: =item *
                   7999: 
1.243     albertel 8000: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   8001: custom role; give a custom role to a user for the level given by URL.  Specify
                   8002: name and domain of role author, and role name
1.191     harris41 8003: 
                   8004: =item *
                   8005: 
1.243     albertel 8006: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 8007: 
                   8008: =item *
                   8009: 
1.243     albertel 8010: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   8011: 
                   8012: =back
                   8013: 
                   8014: =head2 Course Infomation
                   8015: 
                   8016: =over 4
1.191     harris41 8017: 
                   8018: =item *
                   8019: 
1.631     albertel 8020: coursedescription($courseid) : returns a hash of information about the
                   8021: specified course id, including all environment settings for the
                   8022: course, the description of the course will be in the hash under the
                   8023: key 'description'
1.191     harris41 8024: 
                   8025: =item *
                   8026: 
1.624     albertel 8027: resdata($name,$domain,$type,@which) : request for current parameter
                   8028: setting for a specific $type, where $type is either 'course' or 'user',
                   8029: @what should be a list of parameters to ask about. This routine caches
                   8030: answers for 5 minutes.
1.243     albertel 8031: 
                   8032: =back
                   8033: 
                   8034: =head2 Course Modification
                   8035: 
                   8036: =over 4
1.191     harris41 8037: 
                   8038: =item *
                   8039: 
1.243     albertel 8040: writecoursepref($courseid,%prefs) : write preferences (environment
                   8041: database) for a course
1.191     harris41 8042: 
                   8043: =item *
                   8044: 
1.243     albertel 8045: createcourse($udom,$description,$url) : make/modify course
                   8046: 
                   8047: =back
                   8048: 
                   8049: =head2 Resource Subroutines
                   8050: 
                   8051: =over 4
1.191     harris41 8052: 
                   8053: =item *
                   8054: 
1.243     albertel 8055: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 8056: 
                   8057: =item *
                   8058: 
1.243     albertel 8059: repcopy($filename) : subscribes to the requested file, and attempts to
                   8060: replicate from the owning library server, Might return
1.607     raeburn  8061: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   8062: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 8063: resource. Expects the local filesystem pathname
                   8064: (/home/httpd/html/res/....)
                   8065: 
                   8066: =back
                   8067: 
                   8068: =head2 Resource Information
                   8069: 
                   8070: =over 4
1.191     harris41 8071: 
                   8072: =item *
                   8073: 
1.243     albertel 8074: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   8075: a vairety of different possible values, $varname should be a request
                   8076: string, and the other parameters can be used to specify who and what
                   8077: one is asking about.
                   8078: 
                   8079: Possible values for $varname are environment.lastname (or other item
                   8080: from the envirnment hash), user.name (or someother aspect about the
                   8081: user), resource.0.maxtries (or some other part and parameter of a
                   8082: resource)
1.204     albertel 8083: 
                   8084: =item *
                   8085: 
1.243     albertel 8086: directcondval($number) : get current value of a condition; reads from a state
                   8087: string
1.204     albertel 8088: 
                   8089: =item *
                   8090: 
1.243     albertel 8091: condval($condidx) : value of condition index based on state
1.204     albertel 8092: 
                   8093: =item *
                   8094: 
1.243     albertel 8095: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   8096: resource's metadata, $what should be either a specific key, or either
                   8097: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   8098: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   8099: 
                   8100: this function automatically caches all requests
1.191     harris41 8101: 
                   8102: =item *
                   8103: 
1.243     albertel 8104: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   8105: network of library servers; returns file handle of where SQL and regex results
                   8106: will be stored for query
1.191     harris41 8107: 
                   8108: =item *
                   8109: 
1.243     albertel 8110: symbread($filename) : return symbolic list entry (filename argument optional);
                   8111: returns the data handle
1.191     harris41 8112: 
                   8113: =item *
                   8114: 
1.243     albertel 8115: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 8116: a possible symb for the URL in $thisfn, and if is an encryypted
                   8117: resource that the user accessed using /enc/ returns a 1 on success, 0
                   8118: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 8119: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 8120: 
1.191     harris41 8121: 
                   8122: =item *
                   8123: 
1.243     albertel 8124: symbclean($symb) : removes versions numbers from a symb, returns the
                   8125: cleaned symb
1.191     harris41 8126: 
                   8127: =item *
                   8128: 
1.243     albertel 8129: is_on_map($uri) : checks if the $uri is somewhere on the current
                   8130: course map, user must be in a course for it to work.
1.191     harris41 8131: 
                   8132: =item *
                   8133: 
1.243     albertel 8134: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 8135: 
                   8136: =item *
                   8137: 
1.243     albertel 8138: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   8139: a random seed, all arguments are optional, if they aren't sent it uses the
                   8140: environment to derive them. Note: if symb isn't sent and it can't get one
                   8141: from &symbread it will use the current time as its return value
1.191     harris41 8142: 
                   8143: =item *
                   8144: 
1.243     albertel 8145: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   8146: unfakeable, receipt
1.191     harris41 8147: 
                   8148: =item *
                   8149: 
1.620     albertel 8150: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 8151: 
                   8152: =item *
                   8153: 
1.243     albertel 8154: countacc($url) : count the number of accesses to a given URL
1.191     harris41 8155: 
                   8156: =item *
                   8157: 
1.243     albertel 8158: 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 8159: 
                   8160: =item *
                   8161: 
1.243     albertel 8162: 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 8163: 
                   8164: =item *
                   8165: 
1.243     albertel 8166: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 8167: 
                   8168: =item *
                   8169: 
1.243     albertel 8170: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   8171: forcing spreadsheet to reevaluate the resource scores next time.
                   8172: 
                   8173: =back
                   8174: 
                   8175: =head2 Storing/Retreiving Data
                   8176: 
                   8177: =over 4
1.191     harris41 8178: 
                   8179: =item *
                   8180: 
1.243     albertel 8181: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   8182: for this url; hashref needs to be given and should be a \%hashname; the
                   8183: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 8184: be derived from the env
1.191     harris41 8185: 
                   8186: =item *
                   8187: 
1.243     albertel 8188: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   8189: uses critical subroutine
1.191     harris41 8190: 
                   8191: =item *
                   8192: 
1.243     albertel 8193: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   8194: all args are optional
1.191     harris41 8195: 
                   8196: =item *
                   8197: 
1.717     albertel 8198: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   8199: dumps the complete (or key matching regexp) namespace into a hash
                   8200: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   8201: normally &store()ed into
                   8202: 
                   8203: $range should be either an integer '100' (give me the first 100
                   8204:                                            matching records)
                   8205:               or be  two integers sperated by a - with no spaces
                   8206:                  '30-50' (give me the 30th through the 50th matching
                   8207:                           records)
                   8208: 
                   8209: 
                   8210: =item *
                   8211: 
                   8212: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   8213: replaces a &store() version of data with a replacement set of data
                   8214: for a particular resource in a namespace passed in the $storehash hash 
                   8215: reference
                   8216: 
                   8217: =item *
                   8218: 
1.243     albertel 8219: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   8220: works very similar to store/cstore, but all data is stored in a
                   8221: temporary location and can be reset using tmpreset, $storehash should
                   8222: be a hash reference, returns nothing on success
1.191     harris41 8223: 
                   8224: =item *
                   8225: 
1.243     albertel 8226: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   8227: similar to restore, but all data is stored in a temporary location and
                   8228: can be reset using tmpreset. Returns a hash of values on success,
                   8229: error string otherwise.
1.191     harris41 8230: 
                   8231: =item *
                   8232: 
1.243     albertel 8233: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   8234: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 8235: 
                   8236: =item *
                   8237: 
1.243     albertel 8238: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   8239: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 8240: 
                   8241: =item *
                   8242: 
1.243     albertel 8243: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   8244: namesp ($udom and $uname are optional)
1.191     harris41 8245: 
                   8246: =item *
                   8247: 
1.702     albertel 8248: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 8249: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 8250: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  8251: 
1.702     albertel 8252: $range should be either an integer '100' (give me the first 100
                   8253:                                            matching records)
                   8254:               or be  two integers sperated by a - with no spaces
                   8255:                  '30-50' (give me the 30th through the 50th matching
                   8256:                           records)
1.449     matthew  8257: =item *
                   8258: 
                   8259: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   8260: $store can be a scalar, an array reference, or if the amount to be 
                   8261: incremented is > 1, a hash reference.
                   8262: 
                   8263: ($udom and $uname are optional)
1.191     harris41 8264: 
                   8265: =item *
                   8266: 
1.243     albertel 8267: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   8268: ($udom and $uname are optional)
1.191     harris41 8269: 
                   8270: =item *
                   8271: 
1.243     albertel 8272: cput($namespace,$storehash,$udom,$uname) : critical put
                   8273: ($udom and $uname are optional)
1.191     harris41 8274: 
                   8275: =item *
                   8276: 
1.748     albertel 8277: newput($namespace,$storehash,$udom,$uname) :
                   8278: 
                   8279: Attempts to store the items in the $storehash, but only if they don't
                   8280: currently exist, if this succeeds you can be certain that you have 
                   8281: successfully created a new key value pair in the $namespace db.
                   8282: 
                   8283: 
                   8284: Args:
                   8285:  $namespace: name of database to store values to
                   8286:  $storehash: hashref to store to the db
                   8287:  $udom: (optional) domain of user containing the db
                   8288:  $uname: (optional) name of user caontaining the db
                   8289: 
                   8290: Returns:
                   8291:  'ok' -> succeeded in storing all keys of $storehash
                   8292:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   8293:                         least <key> already existed in the db (other
                   8294:                         requested keys may also already exist)
                   8295:  'error: <msg>' -> unable to tie the DB or other erorr occured
                   8296:  'con_lost' -> unable to contact request server
                   8297:  'refused' -> action was not allowed by remote machine
                   8298: 
                   8299: 
                   8300: =item *
                   8301: 
1.243     albertel 8302: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   8303: reference filled in from namesp (encrypts the return communication)
                   8304: ($udom and $uname are optional)
1.191     harris41 8305: 
                   8306: =item *
                   8307: 
1.243     albertel 8308: log($udom,$name,$home,$message) : write to permanent log for user; use
                   8309: critical subroutine
                   8310: 
1.806     raeburn  8311: =item *
                   8312: 
                   8313: get_dom($namespace,$storearr,$udomain) : returns hash with keys from array
                   8314: reference filled in from namespace found in domain level on primary domain server ($udomain is optional)
                   8315: 
                   8316: =item *
                   8317: 
                   8318: put_dom($namespace,$storehash,$udomain) :  stores hash in namespace at domain level on primary domain server ($udomain is optional)
                   8319: 
1.243     albertel 8320: =back
                   8321: 
                   8322: =head2 Network Status Functions
                   8323: 
                   8324: =over 4
1.191     harris41 8325: 
                   8326: =item *
                   8327: 
                   8328: dirlist($uri) : return directory list based on URI
                   8329: 
                   8330: =item *
                   8331: 
1.243     albertel 8332: spareserver() : find server with least workload from spare.tab
                   8333: 
                   8334: =back
                   8335: 
                   8336: =head2 Apache Request
                   8337: 
                   8338: =over 4
1.191     harris41 8339: 
                   8340: =item *
                   8341: 
1.243     albertel 8342: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   8343: localhost, posts hash
                   8344: 
                   8345: =back
                   8346: 
                   8347: =head2 Data to String to Data
                   8348: 
                   8349: =over 4
1.191     harris41 8350: 
                   8351: =item *
                   8352: 
1.243     albertel 8353: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   8354: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 8355: 
                   8356: =item *
                   8357: 
1.243     albertel 8358: hashref2str($hashref) : convert a hashref into a string complete with
                   8359: escaping and '=' and '&' separators, supports elements that are
                   8360: arrayrefs and hashrefs
1.191     harris41 8361: 
                   8362: =item *
                   8363: 
1.243     albertel 8364: arrayref2str($arrayref) : convert an arrayref into a string complete
                   8365: with escaping and '&' separators, supports elements that are arrayrefs
                   8366: and hashrefs
1.191     harris41 8367: 
                   8368: =item *
                   8369: 
1.243     albertel 8370: str2hash($string) : convert string to hash using unescaping and
                   8371: splitting on '=' and '&', supports elements that are arrayrefs and
                   8372: hashrefs
1.191     harris41 8373: 
                   8374: =item *
                   8375: 
1.243     albertel 8376: str2array($string) : convert string to hash using unescaping and
                   8377: splitting on '&', supports elements that are arrayrefs and hashrefs
                   8378: 
                   8379: =back
                   8380: 
                   8381: =head2 Logging Routines
                   8382: 
                   8383: =over 4
                   8384: 
                   8385: These routines allow one to make log messages in the lonnet.log and
                   8386: lonnet.perm logfiles.
1.191     harris41 8387: 
                   8388: =item *
                   8389: 
1.243     albertel 8390: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 8391: 
                   8392: =item *
                   8393: 
1.243     albertel 8394: logthis() : append message to the normal lonnet.log file, it gets
                   8395: preiodically rolled over and deleted.
1.191     harris41 8396: 
                   8397: =item *
                   8398: 
1.243     albertel 8399: logperm() : append a permanent message to lonnet.perm.log, this log
                   8400: file never gets deleted by any automated portion of the system, only
                   8401: messages of critical importance should go in here.
                   8402: 
                   8403: =back
                   8404: 
                   8405: =head2 General File Helper Routines
                   8406: 
                   8407: =over 4
1.191     harris41 8408: 
                   8409: =item *
                   8410: 
1.481     raeburn  8411: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   8412: (a) files in /uploaded
                   8413:   (i) If a local copy of the file exists - 
                   8414:       compares modification date of local copy with last-modified date for 
                   8415:       definitive version stored on home server for course. If local copy is 
                   8416:       stale, requests a new version from the home server and stores it. 
                   8417:       If the original has been removed from the home server, then local copy 
                   8418:       is unlinked.
                   8419:   (ii) If local copy does not exist -
                   8420:       requests the file from the home server and stores it. 
                   8421:   
                   8422:   If $caller is 'uploadrep':  
                   8423:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   8424:     for request for files originally uploaded via DOCS. 
                   8425:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   8426:   
                   8427:   Otherwise:
                   8428:      This indicates a call from the content generation phase of the request.
                   8429:      -  returns the entire contents of the file or -1.
                   8430:      
                   8431: (b) files in /res
                   8432:    - returns the entire contents of a file or -1; 
                   8433:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 8434: 
1.712     albertel 8435: 
                   8436: =item *
                   8437: 
                   8438: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   8439:                   reference
                   8440: 
                   8441: returns either a stat() list of data about the file or an empty list
                   8442: if the file doesn't exist or couldn't find out about it (connection
                   8443: problems or user unknown)
                   8444: 
1.191     harris41 8445: =item *
                   8446: 
1.243     albertel 8447: filelocation($dir,$file) : returns file system location of a file
                   8448: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   8449: directory that relative $file lookups are to looked in ($dir of /a/dir
                   8450: and a file of ../bob will become /a/bob)
1.191     harris41 8451: 
                   8452: =item *
                   8453: 
                   8454: hreflocation($dir,$file) : returns file system location or a URL; same as
                   8455: filelocation except for hrefs
                   8456: 
                   8457: =item *
                   8458: 
                   8459: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   8460: 
1.243     albertel 8461: =back
                   8462: 
1.608     albertel 8463: =head2 Usererfile file routines (/uploaded*)
                   8464: 
                   8465: =over 4
                   8466: 
                   8467: =item *
                   8468: 
                   8469: userfileupload(): main rotine for putting a file in a user or course's
                   8470:                   filespace, arguments are,
                   8471: 
1.620     albertel 8472:  formname - required - this is the name of the element in $env where the
1.608     albertel 8473:            filename, and the contents of the file to create/modifed exist
1.620     albertel 8474:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   8475:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 8476:  coursedoc - if true, store the file in the course of the active role
                   8477:              of the current user
                   8478:  subdir - required - subdirectory to put the file in under ../userfiles/
                   8479:          if undefined, it will be placed in "unknown"
                   8480: 
                   8481:  (This routine calls clean_filename() to remove any dangerous
                   8482:  characters from the filename, and then calls finuserfileupload() to
                   8483:  complete the transaction)
                   8484: 
                   8485:  returns either the url of the uploaded file (/uploaded/....) if successful
                   8486:  and /adm/notfound.html if unsuccessful
                   8487: 
                   8488: =item *
                   8489: 
                   8490: clean_filename(): routine for cleaing a filename up for storage in
                   8491:                  userfile space, argument is:
                   8492: 
                   8493:  filename - proposed filename
                   8494: 
                   8495: returns: the new clean filename
                   8496: 
                   8497: =item *
                   8498: 
                   8499: finishuserfileupload(): routine that creaes and sends the file to
                   8500: userspace, probably shouldn't be called directly
                   8501: 
                   8502:   docuname: username or courseid of destination for the file
                   8503:   docudom: domain of user/course of destination for the file
                   8504:   formname: same as for userfileupload()
                   8505:   fname: filename (inculding subdirectories) for the file
                   8506: 
                   8507:  returns either the url of the uploaded file (/uploaded/....) if successful
                   8508:  and /adm/notfound.html if unsuccessful
                   8509: 
                   8510: =item *
                   8511: 
                   8512: renameuserfile(): renames an existing userfile to a new name
                   8513: 
                   8514:   Args:
                   8515:    docuname: username or courseid of destination for the file
                   8516:    docudom: domain of user/course of destination for the file
                   8517:    old: current file name (including any subdirs under userfiles)
                   8518:    new: desired file name (including any subdirs under userfiles)
                   8519: 
                   8520: =item *
                   8521: 
                   8522: mkdiruserfile(): creates a directory is a userfiles dir
                   8523: 
                   8524:   Args:
                   8525:    docuname: username or courseid of destination for the file
                   8526:    docudom: domain of user/course of destination for the file
                   8527:    dir: dir to create (including any subdirs under userfiles)
                   8528: 
                   8529: =item *
                   8530: 
                   8531: removeuserfile(): removes a file that exists in userfiles
                   8532: 
                   8533:   Args:
                   8534:    docuname: username or courseid of destination for the file
                   8535:    docudom: domain of user/course of destination for the file
                   8536:    fname: filname to delete (including any subdirs under userfiles)
                   8537: 
                   8538: =item *
                   8539: 
                   8540: removeuploadedurl(): convience function for removeuserfile()
                   8541: 
                   8542:   Args:
                   8543:    url:  a full /uploaded/... url to delete
                   8544: 
1.747     albertel 8545: =item * 
                   8546: 
                   8547: get_portfile_permissions():
                   8548:   Args:
                   8549:     domain: domain of user or course contain the portfolio files
                   8550:     user: name of user or num of course contain the portfolio files
                   8551:   Returns:
                   8552:     hashref of a dump of the proper file_permissions.db
                   8553:    
                   8554: 
                   8555: =item * 
                   8556: 
                   8557: get_access_controls():
                   8558: 
                   8559: Args:
                   8560:   current_permissions: the hash ref returned from get_portfile_permissions()
                   8561:   group: (optional) the group you want the files associated with
                   8562:   file: (optional) the file you want access info on
                   8563: 
                   8564: Returns:
1.749     raeburn  8565:     a hash (keys are file names) of hashes containing
                   8566:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   8567:         values are XML containing access control settings (see below) 
1.747     albertel 8568: 
                   8569: Internal notes:
                   8570: 
1.749     raeburn  8571:  access controls are stored in file_permissions.db as key=value pairs.
                   8572:     key -> path to file/file_name\0uniqueID:scope_end_start
                   8573:         where scope -> public,guest,course,group,domains or users.
                   8574:               end -> UNIX time for end of access (0 -> no end date)
                   8575:               start -> UNIX time for start of access
                   8576: 
                   8577:     value -> XML description of access control
                   8578:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   8579:             <start></start>
                   8580:             <end></end>
                   8581: 
                   8582:             <password></password>  for scope type = guest
                   8583: 
                   8584:             <domain></domain>     for scope type = course or group
                   8585:             <number></number>
                   8586:             <roles id="">
                   8587:              <role></role>
                   8588:              <access></access>
                   8589:              <section></section>
                   8590:              <group></group>
                   8591:             </roles>
                   8592: 
                   8593:             <dom></dom>         for scope type = domains
                   8594: 
                   8595:             <users>             for scope type = users
                   8596:              <user>
                   8597:               <uname></uname>
                   8598:               <udom></udom>
                   8599:              </user>
                   8600:             </users>
                   8601:            </scope> 
                   8602:               
                   8603:  Access data is also aggregated for each file in an additional key=value pair:
                   8604:  key -> path to file/file_name\0accesscontrol 
                   8605:  value -> reference to hash
                   8606:           hash contains key = value pairs
                   8607:           where key = uniqueID:scope_end_start
                   8608:                 value = UNIX time record was last updated
                   8609: 
                   8610:           Used to improve speed of look-ups of access controls for each file.  
                   8611:  
                   8612:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   8613: 
                   8614: modify_access_controls():
                   8615: 
                   8616: Modifies access controls for a portfolio file
                   8617: Args
                   8618: 1. file name
                   8619: 2. reference to hash of required changes,
                   8620: 3. domain
                   8621: 4. username
                   8622:   where domain,username are the domain of the portfolio owner 
                   8623:   (either a user or a course) 
                   8624: 
                   8625: Returns:
                   8626: 1. result of additions or updates ('ok' or 'error', with error message). 
                   8627: 2. result of deletions ('ok' or 'error', with error message).
                   8628: 3. reference to hash of any new or updated access controls.
                   8629: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   8630:    key = integer (inbound ID)
                   8631:    value = uniqueID  
1.747     albertel 8632: 
1.608     albertel 8633: =back
                   8634: 
1.243     albertel 8635: =head2 HTTP Helper Routines
                   8636: 
                   8637: =over 4
                   8638: 
1.191     harris41 8639: =item *
                   8640: 
                   8641: escape() : unpack non-word characters into CGI-compatible hex codes
                   8642: 
                   8643: =item *
                   8644: 
                   8645: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   8646: 
1.243     albertel 8647: =back
                   8648: 
                   8649: =head1 PRIVATE SUBROUTINES
                   8650: 
                   8651: =head2 Underlying communication routines (Shouldn't call)
                   8652: 
                   8653: =over 4
                   8654: 
                   8655: =item *
                   8656: 
                   8657: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   8658: 
                   8659: =item *
                   8660: 
                   8661: reply() : uses subreply to send a message to remote machine, logs all failures
                   8662: 
                   8663: =item *
                   8664: 
                   8665: critical() : passes a critical message to another server; if cannot
                   8666: get through then place message in connection buffer directory and
                   8667: returns con_delayed, if incapable of saving message, returns
                   8668: con_failed
                   8669: 
                   8670: =item *
                   8671: 
                   8672: reconlonc() : tries to reconnect lonc client processes.
                   8673: 
                   8674: =back
                   8675: 
                   8676: =head2 Resource Access Logging
                   8677: 
                   8678: =over 4
                   8679: 
                   8680: =item *
                   8681: 
                   8682: flushcourselogs() : flush (save) buffer logs and access logs
                   8683: 
                   8684: =item *
                   8685: 
                   8686: courselog($what) : save message for course in hash
                   8687: 
                   8688: =item *
                   8689: 
                   8690: courseacclog($what) : save message for course using &courselog().  Perform
                   8691: special processing for specific resource types (problems, exams, quizzes, etc).
                   8692: 
1.191     harris41 8693: =item *
                   8694: 
                   8695: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   8696: as a PerlChildExitHandler
1.243     albertel 8697: 
                   8698: =back
                   8699: 
                   8700: =head2 Other
                   8701: 
                   8702: =over 4
                   8703: 
                   8704: =item *
                   8705: 
                   8706: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 8707: 
                   8708: =back
                   8709: 
                   8710: =cut

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