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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.824.2.5! albertel    4: # $Id: lonnet.pm,v 1.824.2.4 2007/04/24 19:38:15 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;
1.824.2.3  albertel  993: sub make_key {
                    994:     my ($name,$id) = @_;
1.824.2.5! albertel  995:     if (length($id) > 65 
        !           996: 	&& length(&escape($id)) > 200) {
        !           997: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
        !           998:     }
1.824.2.3  albertel  999:     return &escape($name.':'.$id);
                   1000: }
                   1001: 
1.599     albertel 1002: sub devalidate_cache_new {
                   1003:     my ($name,$id,$debug) = @_;
                   1004:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.824.2.3  albertel 1005:     $id=&make_key($name,$id);
1.599     albertel 1006:     $memcache->delete($id);
                   1007:     delete($remembered{$id});
                   1008:     delete($accessed{$id});
                   1009: }
                   1010: 
                   1011: sub is_cached_new {
                   1012:     my ($name,$id,$debug) = @_;
1.824.2.3  albertel 1013:     $id=&make_key($name,$id);
1.599     albertel 1014:     if (exists($remembered{$id})) {
                   1015: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                   1016: 	$accessed{$id}=[&gettimeofday()];
                   1017: 	$hits++;
                   1018: 	return ($remembered{$id},1);
                   1019:     }
                   1020:     my $value = $memcache->get($id);
                   1021:     if (!(defined($value))) {
                   1022: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 1023: 	return (undef,undef);
1.416     albertel 1024:     }
1.599     albertel 1025:     if ($value eq '__undef__') {
                   1026: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   1027: 	$value=undef;
                   1028:     }
                   1029:     &make_room($id,$value,$debug);
                   1030:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   1031:     return ($value,1);
                   1032: }
                   1033: 
                   1034: sub do_cache_new {
                   1035:     my ($name,$id,$value,$time,$debug) = @_;
1.824.2.3  albertel 1036:     $id=&make_key($name,$id);
1.599     albertel 1037:     my $setvalue=$value;
                   1038:     if (!defined($setvalue)) {
                   1039: 	$setvalue='__undef__';
                   1040:     }
1.623     albertel 1041:     if (!defined($time) ) {
                   1042: 	$time=600;
                   1043:     }
1.599     albertel 1044:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.824.2.5! albertel 1045:     if (!($memcache->set($id,$setvalue,$time))) {
        !          1046: 	&logthis("caching of id -> $id  failed");
        !          1047:     }
1.600     albertel 1048:     # need to make a copy of $value
                   1049:     #&make_room($id,$value,$debug);
1.599     albertel 1050:     return $value;
                   1051: }
                   1052: 
                   1053: sub make_room {
                   1054:     my ($id,$value,$debug)=@_;
                   1055:     $remembered{$id}=$value;
                   1056:     if ($to_remember<0) { return; }
                   1057:     $accessed{$id}=[&gettimeofday()];
                   1058:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   1059:     my $to_kick;
                   1060:     my $max_time=0;
                   1061:     foreach my $other (keys(%accessed)) {
                   1062: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   1063: 	    $to_kick=$other;
                   1064: 	    $max_time=&tv_interval($accessed{$other});
                   1065: 	}
                   1066:     }
                   1067:     delete($remembered{$to_kick});
                   1068:     delete($accessed{$to_kick});
                   1069:     $kicks++;
                   1070:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 1071:     return;
                   1072: }
                   1073: 
1.599     albertel 1074: sub purge_remembered {
1.604     albertel 1075:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   1076:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 1077:     undef(%remembered);
                   1078:     undef(%accessed);
1.428     albertel 1079: }
1.70      www      1080: # ------------------------------------- Read an entry from a user's environment
                   1081: 
                   1082: sub userenvironment {
                   1083:     my ($udom,$unam,@what)=@_;
                   1084:     my %returnhash=();
                   1085:     my @answer=split(/\&/,
                   1086:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
                   1087:                       &homeserver($unam,$udom)));
                   1088:     my $i;
                   1089:     for ($i=0;$i<=$#what;$i++) {
                   1090: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                   1091:     }
                   1092:     return %returnhash;
1.1       albertel 1093: }
                   1094: 
1.617     albertel 1095: # ---------------------------------------------------------- Get a studentphoto
                   1096: sub studentphoto {
                   1097:     my ($udom,$unam,$ext) = @_;
                   1098:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1099:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1100:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1101:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1102:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1103:             } else {
                   1104:                 my ($result,$perm_reqd)=
1.707     albertel 1105: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1106:                 if ($result eq 'ok') {
                   1107:                     if (!($perm_reqd eq 'yes')) {
                   1108:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1109:                     }
                   1110:                 }
                   1111:             }
                   1112:         }
                   1113:     } else {
                   1114:         my ($result,$perm_reqd) = 
1.707     albertel 1115: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1116:         if ($result eq 'ok') {
                   1117:             if (!($perm_reqd eq 'yes')) {
                   1118:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1119:             }
                   1120:         }
                   1121:     }
                   1122:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1123: }
                   1124: 
                   1125: sub retrievestudentphoto {
                   1126:     my ($udom,$unam,$ext,$type) = @_;
                   1127:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1128:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1129:     if ($ret eq 'ok') {
                   1130:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1131:         if ($type eq 'thumbnail') {
                   1132:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1133:         }
                   1134:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1135:         return $tokenurl;
                   1136:     } else {
                   1137:         if ($type eq 'thumbnail') {
                   1138:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1139:         } else { 
                   1140:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1141:         }
1.617     albertel 1142:     }
                   1143: }
                   1144: 
1.263     www      1145: # -------------------------------------------------------------------- New chat
                   1146: 
                   1147: sub chatsend {
1.724     raeburn  1148:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1149:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1150:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1151:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1152:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1153: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1154: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1155: }
                   1156: 
                   1157: # ------------------------------------------ Find current version of a resource
                   1158: 
                   1159: sub getversion {
                   1160:     my $fname=&clutter(shift);
                   1161:     unless ($fname=~/^\/res\//) { return -1; }
                   1162:     return &currentversion(&filelocation('',$fname));
                   1163: }
                   1164: 
                   1165: sub currentversion {
                   1166:     my $fname=shift;
1.599     albertel 1167:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1168:     if (defined($cached)) { return $result; }
1.292     www      1169:     my $author=$fname;
                   1170:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1171:     my ($udom,$uname)=split(/\//,$author);
                   1172:     my $home=homeserver($uname,$udom);
                   1173:     if ($home eq 'no_host') { 
                   1174:         return -1; 
                   1175:     }
                   1176:     my $answer=reply("currentversion:$fname",$home);
                   1177:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1178: 	return -1;
                   1179:     }
1.599     albertel 1180:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1181: }
                   1182: 
1.1       albertel 1183: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1184: 
1.1       albertel 1185: sub subscribe {
                   1186:     my $fname=shift;
1.761     raeburn  1187:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1188:     $fname=~s/[\n\r]//g;
1.1       albertel 1189:     my $author=$fname;
                   1190:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1191:     my ($udom,$uname)=split(/\//,$author);
                   1192:     my $home=homeserver($uname,$udom);
1.335     albertel 1193:     if ($home eq 'no_host') {
                   1194:         return 'not_found';
1.1       albertel 1195:     }
                   1196:     my $answer=reply("sub:$fname",$home);
1.64      www      1197:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1198: 	$answer.=' by '.$home;
                   1199:     }
1.1       albertel 1200:     return $answer;
                   1201: }
                   1202:     
1.8       www      1203: # -------------------------------------------------------------- Replicate file
                   1204: 
                   1205: sub repcopy {
                   1206:     my $filename=shift;
1.23      www      1207:     $filename=~s/\/+/\//g;
1.607     raeburn  1208:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1209:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1210:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1211: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1212: 	return &repcopy_userfile($filename);
                   1213:     }
1.532     albertel 1214:     $filename=~s/[\n\r]//g;
1.8       www      1215:     my $transname="$filename.in.transfer";
1.607     raeburn  1216:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1217:     my $remoteurl=subscribe($filename);
1.64      www      1218:     if ($remoteurl =~ /^con_lost by/) {
                   1219: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1220:            return 'unavailable';
1.8       www      1221:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1222: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1223: 	   return 'not_found';
1.64      www      1224:     } elsif ($remoteurl =~ /^rejected by/) {
                   1225: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1226:            return 'forbidden';
1.20      www      1227:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1228:            return 'ok';
1.8       www      1229:     } else {
1.290     www      1230:         my $author=$filename;
                   1231:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1232:         my ($udom,$uname)=split(/\//,$author);
                   1233:         my $home=homeserver($uname,$udom);
                   1234:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1235:            my @parts=split(/\//,$filename);
                   1236:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1237:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1238:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1239: 	       return 'bad_request';
1.8       www      1240:            }
                   1241:            my $count;
                   1242:            for ($count=5;$count<$#parts;$count++) {
                   1243:                $path.="/$parts[$count]";
                   1244:                if ((-e $path)!=1) {
                   1245: 		   mkdir($path,0777);
                   1246:                }
                   1247:            }
                   1248:            my $ua=new LWP::UserAgent;
                   1249:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1250:            my $response=$ua->request($request,$transname);
                   1251:            if ($response->is_error()) {
                   1252: 	       unlink($transname);
                   1253:                my $message=$response->status_line;
1.672     albertel 1254:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      1255:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1256:                return 'unavailable';
1.8       www      1257:            } else {
1.16      www      1258: 	       if ($remoteurl!~/\.meta$/) {
                   1259:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1260:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1261:                   if ($mresponse->is_error()) {
                   1262: 		      unlink($filename.'.meta');
                   1263:                       &logthis(
1.672     albertel 1264:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      1265:                   }
                   1266: 	       }
1.8       www      1267:                rename($transname,$filename);
1.607     raeburn  1268:                return 'ok';
1.8       www      1269:            }
1.290     www      1270:        }
1.8       www      1271:     }
1.330     www      1272: }
                   1273: 
                   1274: # ------------------------------------------------ Get server side include body
                   1275: sub ssi_body {
1.381     albertel 1276:     my ($filelink,%form)=@_;
1.606     matthew  1277:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1278:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1279:     }
1.330     www      1280:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
1.381     albertel 1281:                                      &ssi($filelink,%form));
1.778     albertel 1282:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1283:     $output=~s/^.*?\<body[^\>]*\>//si;
                   1284:     $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
1.330     www      1285:     return $output;
1.8       www      1286: }
                   1287: 
1.15      www      1288: # --------------------------------------------------------- Server Side Include
                   1289: 
1.782     albertel 1290: sub absolute_url {
                   1291:     my ($host_name) = @_;
                   1292:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   1293:     if ($host_name eq '') {
                   1294: 	$host_name = $ENV{'SERVER_NAME'};
                   1295:     }
                   1296:     return $protocol.$host_name;
                   1297: }
                   1298: 
1.15      www      1299: sub ssi {
                   1300: 
1.23      www      1301:     my ($fn,%form)=@_;
1.15      www      1302: 
                   1303:     my $ua=new LWP::UserAgent;
1.23      www      1304:     
                   1305:     my $request;
1.711     albertel 1306: 
                   1307:     $form{'no_update_last_known'}=1;
                   1308: 
1.23      www      1309:     if (%form) {
1.782     albertel 1310:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.201     albertel 1311:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www      1312:     } else {
1.782     albertel 1313:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      1314:     }
                   1315: 
1.15      www      1316:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1317:     my $response=$ua->request($request);
                   1318: 
1.324     www      1319:     return $response->content;
                   1320: }
                   1321: 
                   1322: sub externalssi {
                   1323:     my ($url)=@_;
                   1324:     my $ua=new LWP::UserAgent;
                   1325:     my $request=new HTTP::Request('GET',$url);
                   1326:     my $response=$ua->request($request);
1.15      www      1327:     return $response->content;
                   1328: }
1.254     www      1329: 
1.492     albertel 1330: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1331: 
                   1332: sub allowuploaded {
                   1333:     my ($srcurl,$url)=@_;
                   1334:     $url=&clutter(&declutter($url));
                   1335:     my $dir=$url;
                   1336:     $dir=~s/\/[^\/]+$//;
                   1337:     my %httpref=();
                   1338:     my $httpurl=&hreflocation('',$url);
                   1339:     $httpref{'httpref.'.$httpurl}=$srcurl;
                   1340:     &Apache::lonnet::appenv(%httpref);
1.254     www      1341: }
1.477     raeburn  1342: 
1.478     albertel 1343: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 1344: # input: action, courseID, current domain, intended
1.637     raeburn  1345: #        path to file, source of file, instruction to parse file for objects,
                   1346: #        ref to hash for embedded objects,
                   1347: #        ref to hash for codebase of java objects.
                   1348: #
1.485     raeburn  1349: # output: url to file (if action was uploaddoc), 
                   1350: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  1351: #
1.478     albertel 1352: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   1353: # course.
1.477     raeburn  1354: #
1.478     albertel 1355: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1356: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   1357: #          course's home server.
1.477     raeburn  1358: #
1.478     albertel 1359: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   1360: #          be copied from $source (current location) to 
                   1361: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1362: #         and will then be copied to
                   1363: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   1364: #         course's home server.
1.485     raeburn  1365: #
1.481     raeburn  1366: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 1367: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  1368: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1369: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   1370: #         in course's home server.
1.637     raeburn  1371: #
1.477     raeburn  1372: 
                   1373: sub process_coursefile {
1.638     albertel 1374:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  1375:     my $fetchresult;
1.638     albertel 1376:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  1377:     if ($action eq 'propagate') {
1.638     albertel 1378:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1379: 			     $home);
1.481     raeburn  1380:     } else {
1.477     raeburn  1381:         my $fpath = '';
                   1382:         my $fname = $file;
1.478     albertel 1383:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  1384:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  1385:         my $filepath = &build_filepath($fpath);
1.481     raeburn  1386:         if ($action eq 'copy') {
                   1387:             if ($source eq '') {
                   1388:                 $fetchresult = 'no source file';
                   1389:                 return $fetchresult;
                   1390:             } else {
                   1391:                 my $destination = $filepath.'/'.$fname;
                   1392:                 rename($source,$destination);
                   1393:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1394:                                  $home);
1.481     raeburn  1395:             }
                   1396:         } elsif ($action eq 'uploaddoc') {
                   1397:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 1398:             print $fh $env{'form.'.$source};
1.481     raeburn  1399:             close($fh);
1.637     raeburn  1400:             if ($parser eq 'parse') {
                   1401:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
                   1402:                 unless ($parse_result eq 'ok') {
                   1403:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   1404:                 }
                   1405:             }
1.477     raeburn  1406:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1407:                                  $home);
1.481     raeburn  1408:             if ($fetchresult eq 'ok') {
                   1409:                 return '/uploaded/'.$fpath.'/'.$fname;
                   1410:             } else {
                   1411:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1412:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  1413:                 return '/adm/notfound.html';
                   1414:             }
1.477     raeburn  1415:         }
                   1416:     }
1.485     raeburn  1417:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  1418:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1419:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  1420:     }
                   1421:     return $fetchresult;
                   1422: }
                   1423: 
1.637     raeburn  1424: sub build_filepath {
                   1425:     my ($fpath) = @_;
                   1426:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   1427:     unless ($fpath eq '') {
                   1428:         my @parts=split('/',$fpath);
                   1429:         foreach my $part (@parts) {
                   1430:             $filepath.= '/'.$part;
                   1431:             if ((-e $filepath)!=1) {
                   1432:                 mkdir($filepath,0777);
                   1433:             }
                   1434:         }
                   1435:     }
                   1436:     return $filepath;
                   1437: }
                   1438: 
                   1439: sub store_edited_file {
1.638     albertel 1440:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  1441:     my $file = $primary_url;
                   1442:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   1443:     my $fpath = '';
                   1444:     my $fname = $file;
                   1445:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   1446:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   1447:     my $filepath = &build_filepath($fpath);
                   1448:     open(my $fh,'>'.$filepath.'/'.$fname);
                   1449:     print $fh $content;
                   1450:     close($fh);
1.638     albertel 1451:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  1452:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1453: 			  $home);
1.637     raeburn  1454:     if ($$fetchresult eq 'ok') {
                   1455:         return '/uploaded/'.$fpath.'/'.$fname;
                   1456:     } else {
1.638     albertel 1457:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   1458: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  1459:         return '/adm/notfound.html';
                   1460:     }
                   1461: }
                   1462: 
1.531     albertel 1463: sub clean_filename {
                   1464:     my ($fname)=@_;
1.315     www      1465: # Replace Windows backslashes by forward slashes
1.257     www      1466:     $fname=~s/\\/\//g;
1.315     www      1467: # Get rid of everything but the actual filename
1.257     www      1468:     $fname=~s/^.*\/([^\/]+)$/$1/;
1.315     www      1469: # Replace spaces by underscores
                   1470:     $fname=~s/\s+/\_/g;
                   1471: # Replace all other weird characters by nothing
1.317     www      1472:     $fname=~s/[^\w\.\-]//g;
1.540     albertel 1473: # Replace all .\d. sequences with _\d. so they no longer look like version
                   1474: # numbers
                   1475:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 1476:     return $fname;
                   1477: }
                   1478: 
1.608     albertel 1479: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 1480: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 1481: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 1482: #        $coursedoc - if true up to the current course
                   1483: #                     if false
                   1484: #        $subdir - directory in userfile to store the file into
                   1485: #        $parser, $allfiles, $codebase - unknown
                   1486: #
                   1487: # output: url of file in userspace, or error: <message> 
                   1488: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 1489: 
                   1490: 
1.531     albertel 1491: sub userfileupload {
1.719     banghart 1492:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,$destudom)=@_;
1.531     albertel 1493:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 1494:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 1495:     $fname=&clean_filename($fname);
1.315     www      1496: # See if there is anything left
1.257     www      1497:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 1498:     chop($env{'form.'.$formname});
1.523     raeburn  1499:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   1500:         my $now = time;
                   1501:         my $filepath = 'tmp/helprequests/'.$now;
                   1502:         my @parts=split(/\//,$filepath);
                   1503:         my $fullpath = $perlvar{'lonDaemons'};
                   1504:         for (my $i=0;$i<@parts;$i++) {
                   1505:             $fullpath .= '/'.$parts[$i];
                   1506:             if ((-e $fullpath)!=1) {
                   1507:                 mkdir($fullpath,0777);
                   1508:             }
                   1509:         }
                   1510:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 1511:         print $fh $env{'form.'.$formname};
1.523     raeburn  1512:         close($fh);
1.741     raeburn  1513:         return $fullpath.'/'.$fname;
                   1514:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   1515:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   1516:                        '_'.$env{'user.domain'}.'/pending';
                   1517:         my @parts=split(/\//,$filepath);
                   1518:         my $fullpath = $perlvar{'lonDaemons'};
                   1519:         for (my $i=0;$i<@parts;$i++) {
                   1520:             $fullpath .= '/'.$parts[$i];
                   1521:             if ((-e $fullpath)!=1) {
                   1522:                 mkdir($fullpath,0777);
                   1523:             }
                   1524:         }
                   1525:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   1526:         print $fh $env{'form.'.$formname};
                   1527:         close($fh);
                   1528:         return $fullpath.'/'.$fname;
1.523     raeburn  1529:     }
1.719     banghart 1530:     
1.258     www      1531: # Create the directory if not present
1.493     albertel 1532:     $fname="$subdir/$fname";
1.259     www      1533:     if ($coursedoc) {
1.638     albertel 1534: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1535: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  1536:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 1537:             return &finishuserfileupload($docuname,$docudom,
                   1538: 					 $formname,$fname,$parser,$allfiles,
                   1539: 					 $codebase);
1.481     raeburn  1540:         } else {
1.620     albertel 1541:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 1542:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   1543: 				       $fname,$formname,$parser,
                   1544: 				       $allfiles,$codebase);
1.481     raeburn  1545:         }
1.719     banghart 1546:     } elsif (defined($destuname)) {
                   1547:         my $docuname=$destuname;
                   1548:         my $docudom=$destudom;
                   1549: 	return &finishuserfileupload($docuname,$docudom,$formname,
                   1550: 				     $fname,$parser,$allfiles,$codebase);
                   1551:         
1.259     www      1552:     } else {
1.638     albertel 1553:         my $docuname=$env{'user.name'};
                   1554:         my $docudom=$env{'user.domain'};
1.714     raeburn  1555:         if (exists($env{'form.group'})) {
                   1556:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1557:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1558:         }
1.638     albertel 1559: 	return &finishuserfileupload($docuname,$docudom,$formname,
                   1560: 				     $fname,$parser,$allfiles,$codebase);
1.259     www      1561:     }
1.271     www      1562: }
                   1563: 
                   1564: sub finishuserfileupload {
1.638     albertel 1565:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase) = @_;
1.477     raeburn  1566:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      1567:     my $filepath=$perlvar{'lonDocRoot'};
1.494     albertel 1568:     my ($fnamepath,$file);
                   1569:     $file=$fname;
                   1570:     if ($fname=~m|/|) {
                   1571:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   1572: 	$path.=$fnamepath.'/';
                   1573:     }
1.259     www      1574:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      1575:     my $count;
                   1576:     for ($count=4;$count<=$#parts;$count++) {
                   1577:         $filepath.="/$parts[$count]";
                   1578:         if ((-e $filepath)!=1) {
                   1579: 	    mkdir($filepath,0777);
                   1580:         }
                   1581:     }
                   1582: # Save the file
                   1583:     {
1.701     albertel 1584: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   1585: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   1586: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   1587: 	    return '/adm/notfound.html';
                   1588: 	}
                   1589: 	if (!print FH ($env{'form.'.$formname})) {
                   1590: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   1591: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   1592: 	    return '/adm/notfound.html';
                   1593: 	}
1.570     albertel 1594: 	close(FH);
1.258     www      1595:     }
1.637     raeburn  1596:     if ($parser eq 'parse') {
1.638     albertel 1597:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
                   1598: 						   $codebase);
1.637     raeburn  1599:         unless ($parse_result eq 'ok') {
1.638     albertel 1600:             &logthis('Failed to parse '.$filepath.$file.
                   1601: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  1602:         }
                   1603:     }
1.259     www      1604: # Notify homeserver to grep it
                   1605: #
1.638     albertel 1606:     my $docuhome=&homeserver($docuname,$docudom);
1.494     albertel 1607:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      1608:     if ($fetchresult eq 'ok') {
1.259     www      1609: #
1.258     www      1610: # Return the URL to it
1.494     albertel 1611:         return '/uploaded/'.$path.$file;
1.263     www      1612:     } else {
1.494     albertel 1613:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   1614: 		 ': '.$fetchresult);
1.263     www      1615:         return '/adm/notfound.html';
                   1616:     }    
1.493     albertel 1617: }
                   1618: 
1.637     raeburn  1619: sub extract_embedded_items {
1.648     raeburn  1620:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
1.637     raeburn  1621:     my @state = ();
                   1622:     my %javafiles = (
                   1623:                       codebase => '',
                   1624:                       code => '',
                   1625:                       archive => ''
                   1626:                     );
                   1627:     my %mediafiles = (
                   1628:                       src => '',
                   1629:                       movie => '',
                   1630:                      );
1.648     raeburn  1631:     my $p;
                   1632:     if ($content) {
                   1633:         $p = HTML::LCParser->new($content);
                   1634:     } else {
                   1635:         $p = HTML::LCParser->new($filepath.'/'.$file);
                   1636:     }
1.641     albertel 1637:     while (my $t=$p->get_token()) {
1.640     albertel 1638: 	if ($t->[0] eq 'S') {
                   1639: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
                   1640: 	    push (@state, $tagname);
1.648     raeburn  1641:             if (lc($tagname) eq 'allow') {
                   1642:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   1643:             }
1.640     albertel 1644: 	    if (lc($tagname) eq 'img') {
                   1645: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   1646: 	    }
1.645     raeburn  1647:             if (lc($tagname) eq 'script') {
                   1648:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   1649:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   1650:                 } else {
                   1651:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   1652:                 }
                   1653:             }
                   1654:             if (lc($tagname) eq 'link') {
                   1655:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   1656:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   1657:                 }
                   1658:             }
1.640     albertel 1659: 	    if (lc($tagname) eq 'object' ||
                   1660: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   1661: 		foreach my $item (keys(%javafiles)) {
                   1662: 		    $javafiles{$item} = '';
                   1663: 		}
                   1664: 	    }
                   1665: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   1666: 		my $name = lc($attr->{'name'});
                   1667: 		foreach my $item (keys(%javafiles)) {
                   1668: 		    if ($name eq $item) {
                   1669: 			$javafiles{$item} = $attr->{'value'};
                   1670: 			last;
                   1671: 		    }
                   1672: 		}
                   1673: 		foreach my $item (keys(%mediafiles)) {
                   1674: 		    if ($name eq $item) {
                   1675: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   1676: 			last;
                   1677: 		    }
                   1678: 		}
                   1679: 	    }
                   1680: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   1681: 		foreach my $item (keys(%javafiles)) {
                   1682: 		    if ($attr->{$item}) {
                   1683: 			$javafiles{$item} = $attr->{$item};
                   1684: 			last;
                   1685: 		    }
                   1686: 		}
                   1687: 		foreach my $item (keys(%mediafiles)) {
                   1688: 		    if ($attr->{$item}) {
                   1689: 			&add_filetype($allfiles,$attr->{$item},$item);
                   1690: 			last;
                   1691: 		    }
                   1692: 		}
                   1693: 	    }
                   1694: 	} elsif ($t->[0] eq 'E') {
                   1695: 	    my ($tagname) = ($t->[1]);
                   1696: 	    if ($javafiles{'codebase'} ne '') {
                   1697: 		$javafiles{'codebase'} .= '/';
                   1698: 	    }  
                   1699: 	    if (lc($tagname) eq 'applet' ||
                   1700: 		lc($tagname) eq 'object' ||
                   1701: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   1702: 		) {
                   1703: 		foreach my $item (keys(%javafiles)) {
                   1704: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   1705: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   1706: 			&add_filetype($allfiles,$file,$item);
                   1707: 		    }
                   1708: 		}
                   1709: 	    } 
                   1710: 	    pop @state;
                   1711: 	}
                   1712:     }
1.637     raeburn  1713:     return 'ok';
                   1714: }
                   1715: 
1.639     albertel 1716: sub add_filetype {
                   1717:     my ($allfiles,$file,$type)=@_;
                   1718:     if (exists($allfiles->{$file})) {
                   1719: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   1720: 	    push(@{$allfiles->{$file}}, &escape($type));
                   1721: 	}
                   1722:     } else {
                   1723: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  1724:     }
                   1725: }
                   1726: 
1.493     albertel 1727: sub removeuploadedurl {
                   1728:     my ($url)=@_;
                   1729:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613     albertel 1730:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 1731: }
                   1732: 
                   1733: sub removeuserfile {
                   1734:     my ($docuname,$docudom,$fname)=@_;
                   1735:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  1736:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
                   1737:     if ($result eq 'ok') {
                   1738:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   1739:             my $metafile = $fname.'.meta';
                   1740:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 1741: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
                   1742:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  1743:             my $sqlresult = 
1.823     albertel 1744:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  1745:                                         'portfolio_metadata',$group,
                   1746:                                         'delete');
1.798     raeburn  1747:         }
                   1748:     }
                   1749:     return $result;
1.257     www      1750: }
1.15      www      1751: 
1.530     albertel 1752: sub mkdiruserfile {
                   1753:     my ($docuname,$docudom,$dir)=@_;
                   1754:     my $home=&homeserver($docuname,$docudom);
                   1755:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   1756: }
                   1757: 
1.531     albertel 1758: sub renameuserfile {
                   1759:     my ($docuname,$docudom,$old,$new)=@_;
                   1760:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  1761:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   1762:                         &escape("$old").':'.&escape("$new"),$home);
                   1763:     if ($result eq 'ok') {
                   1764:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   1765:             my $oldmeta = $old.'.meta';
                   1766:             my $newmeta = $new.'.meta';
                   1767:             my $metaresult = 
                   1768:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 1769: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   1770:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  1771:             my $sqlresult = 
1.823     albertel 1772:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  1773:                                         'portfolio_metadata',$group,
                   1774:                                         'delete');
1.798     raeburn  1775:         }
                   1776:     }
                   1777:     return $result;
1.531     albertel 1778: }
                   1779: 
1.14      www      1780: # ------------------------------------------------------------------------- Log
                   1781: 
                   1782: sub log {
                   1783:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      1784:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      1785: }
                   1786: 
                   1787: # ------------------------------------------------------------------ Course Log
1.352     www      1788: #
                   1789: # This routine flushes several buffers of non-mission-critical nature
                   1790: #
1.157     www      1791: 
                   1792: sub flushcourselogs {
1.352     www      1793:     &logthis('Flushing log buffers');
                   1794: #
                   1795: # course logs
                   1796: # This is a log of all transactions in a course, which can be used
                   1797: # for data mining purposes
                   1798: #
                   1799: # It also collects the courseid database, which lists last transaction
                   1800: # times and course titles for all courseids
                   1801: #
                   1802:     my %courseidbuffer=();
1.800     albertel 1803:     foreach my $crsid (keys %courselogs) {
1.352     www      1804:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      1805: 		          &escape($courselogs{$crsid}),
                   1806: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      1807: 	    delete $courselogs{$crsid};
                   1808:         } else {
                   1809:             &logthis('Failed to flush log buffer for '.$crsid);
                   1810:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 1811:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      1812:                         " exceeded maximum size, deleting.</font>");
                   1813:                delete $courselogs{$crsid};
                   1814:             }
1.352     www      1815:         }
                   1816:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
                   1817:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
1.516     raeburn  1818: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  1819:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.352     www      1820:         } else {
                   1821:            $courseidbuffer{$coursehombuf{$crsid}}=
1.516     raeburn  1822: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  1823:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.571     raeburn  1824:         }
1.191     harris41 1825:     }
1.352     www      1826: #
                   1827: # Write course id database (reverse lookup) to homeserver of courses 
                   1828: # Is used in pickcourse
                   1829: #
1.800     albertel 1830:     foreach my $crsid (keys(%courseidbuffer)) {
                   1831:         &courseidput($hostdom{$crsid},$courseidbuffer{$crsid},$crsid);
1.352     www      1832:     }
                   1833: #
                   1834: # File accesses
                   1835: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   1836: #
1.449     matthew  1837:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  1838:         if ($entry =~ /___count$/) {
                   1839:             my ($dom,$name);
1.807     albertel 1840:             ($dom,$name,undef)=
1.811     albertel 1841: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  1842:             if (! defined($dom) || $dom eq '' || 
                   1843:                 ! defined($name) || $name eq '') {
1.620     albertel 1844:                 my $cid = $env{'request.course.id'};
                   1845:                 $dom  = $env{'request.'.$cid.'.domain'};
                   1846:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  1847:             }
1.450     matthew  1848:             my $value = $accesshash{$entry};
                   1849:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   1850:             my %temphash=($url => $value);
1.449     matthew  1851:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   1852:             if ($result eq 'ok') {
                   1853:                 delete $accesshash{$entry};
                   1854:             } elsif ($result eq 'unknown_cmd') {
                   1855:                 # Target server has old code running on it.
1.450     matthew  1856:                 my %temphash=($entry => $value);
1.449     matthew  1857:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1858:                     delete $accesshash{$entry};
                   1859:                 }
                   1860:             }
                   1861:         } else {
1.811     albertel 1862:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  1863:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  1864:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1865:                 delete $accesshash{$entry};
                   1866:             }
1.185     www      1867:         }
1.191     harris41 1868:     }
1.352     www      1869: #
                   1870: # Roles
                   1871: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   1872: #
1.800     albertel 1873:     foreach my $entry (keys(%userrolehash)) {
1.351     www      1874:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      1875: 	    split(/\:/,$entry);
                   1876:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      1877:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      1878:                 $rudom,$runame) eq 'ok') {
                   1879: 	    delete $userrolehash{$entry};
                   1880:         }
                   1881:     }
1.662     raeburn  1882: #
                   1883: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   1884: #
                   1885:     my %domrolebuffer = ();
                   1886:     foreach my $entry (keys %domainrolehash) {
                   1887:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split/:/,$entry;
                   1888:         if ($domrolebuffer{$rudom}) {
                   1889:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   1890:                       '='.&escape($domainrolehash{$entry});
                   1891:         } else {
                   1892:             $domrolebuffer{$rudom}.=&escape($entry).
                   1893:                       '='.&escape($domainrolehash{$entry});
                   1894:         }
                   1895:         delete $domainrolehash{$entry};
                   1896:     }
                   1897:     foreach my $dom (keys(%domrolebuffer)) {
                   1898:         foreach my $tryserver (keys %libserv) {
                   1899:             if ($hostdom{$tryserver} eq $dom) {
                   1900:                 unless (&reply('domroleput:'.$dom.':'.
                   1901:                   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   1902:                     &logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   1903:                 }
                   1904:             }
                   1905:         }
                   1906:     }
1.186     www      1907:     $dumpcount++;
1.157     www      1908: }
                   1909: 
                   1910: sub courselog {
                   1911:     my $what=shift;
1.158     www      1912:     $what=time.':'.$what;
1.620     albertel 1913:     unless ($env{'request.course.id'}) { return ''; }
                   1914:     $coursedombuf{$env{'request.course.id'}}=
                   1915:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   1916:     $coursenumbuf{$env{'request.course.id'}}=
                   1917:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   1918:     $coursehombuf{$env{'request.course.id'}}=
                   1919:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   1920:     $coursedescrbuf{$env{'request.course.id'}}=
                   1921:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   1922:     $courseinstcodebuf{$env{'request.course.id'}}=
                   1923:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   1924:     $courseownerbuf{$env{'request.course.id'}}=
                   1925:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  1926:     $coursetypebuf{$env{'request.course.id'}}=
                   1927:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 1928:     if (defined $courselogs{$env{'request.course.id'}}) {
                   1929: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      1930:     } else {
1.620     albertel 1931: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      1932:     }
1.620     albertel 1933:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      1934: 	&flushcourselogs();
                   1935:     }
1.158     www      1936: }
                   1937: 
                   1938: sub courseacclog {
                   1939:     my $fnsymb=shift;
1.620     albertel 1940:     unless ($env{'request.course.id'}) { return ''; }
                   1941:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 1942:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      1943:         $what.=':POST';
1.583     matthew  1944:         # FIXME: Probably ought to escape things....
1.800     albertel 1945: 	foreach my $key (keys(%env)) {
                   1946:             if ($key=~/^form\.(.*)/) {
                   1947: 		$what.=':'.$1.'='.$env{$key};
1.158     www      1948:             }
1.191     harris41 1949:         }
1.583     matthew  1950:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   1951:         # FIXME: We should not be depending on a form parameter that someone
                   1952:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 1953:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  1954:             $what.= ':POST';
                   1955:             # FIXME: Probably ought to escape things....
                   1956:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   1957:                                  'crsdiscuss') {
1.620     albertel 1958:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  1959:             }
                   1960:         }
1.158     www      1961:     }
                   1962:     &courselog($what);
1.149     www      1963: }
                   1964: 
1.185     www      1965: sub countacc {
                   1966:     my $url=&declutter(shift);
1.458     matthew  1967:     return if (! defined($url) || $url eq '');
1.620     albertel 1968:     unless ($env{'request.course.id'}) { return ''; }
                   1969:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      1970:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  1971:     $accesshash{$key}++;
1.185     www      1972: }
1.349     www      1973: 
1.361     www      1974: sub linklog {
                   1975:     my ($from,$to)=@_;
                   1976:     $from=&declutter($from);
                   1977:     $to=&declutter($to);
                   1978:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   1979:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   1980: }
                   1981:   
1.349     www      1982: sub userrolelog {
                   1983:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  1984:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  1985:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  1986:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   1987:         ($trole=~/^ta/)) {
1.350     www      1988:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   1989:        $userrolehash
                   1990:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      1991:                     =$tend.':'.$tstart;
1.662     raeburn  1992:     }
                   1993:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   1994:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   1995:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   1996:         ($trole=~/^sc/)) {
                   1997:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   1998:        $domainrolehash
                   1999:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   2000:                     = $tend.':'.$tstart;
                   2001:     }
1.351     www      2002: }
                   2003: 
                   2004: sub get_course_adv_roles {
                   2005:     my $cid=shift;
1.620     albertel 2006:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      2007:     my %coursehash=&coursedescription($cid);
1.470     www      2008:     my %nothide=();
1.800     albertel 2009:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2010: 	$nothide{join(':',split(/[\@\:]/,$user))}=1;
1.470     www      2011:     }
1.351     www      2012:     my %returnhash=();
                   2013:     my %dumphash=
                   2014:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   2015:     my $now=time;
1.800     albertel 2016:     foreach my $entry (keys %dumphash) {
                   2017: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      2018:         if (($tstart) && ($tstart<0)) { next; }
                   2019:         if (($tend) && ($tend<$now)) { next; }
                   2020:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 2021:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 2022: 	if ($username eq '' || $domain eq '') { next; }
1.470     www      2023: 	if ((&privileged($username,$domain)) && 
                   2024: 	    (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 2025: 	if ($role eq 'cr') { next; }
1.351     www      2026:         my $key=&plaintext($role);
                   2027:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
                   2028:         if ($returnhash{$key}) {
                   2029: 	    $returnhash{$key}.=','.$username.':'.$domain;
                   2030:         } else {
                   2031:             $returnhash{$key}=$username.':'.$domain;
                   2032:         }
1.400     www      2033:      }
                   2034:     return %returnhash;
                   2035: }
                   2036: 
                   2037: sub get_my_roles {
                   2038:     my ($uname,$udom)=@_;
1.620     albertel 2039:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   2040:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.400     www      2041:     my %dumphash=
                   2042:             &dump('nohist_userroles',$udom,$uname);
                   2043:     my %returnhash=();
                   2044:     my $now=time;
1.800     albertel 2045:     foreach my $entry (keys(%dumphash)) {
                   2046: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.400     www      2047:         if (($tstart) && ($tstart<0)) { next; }
                   2048:         if (($tend) && ($tend<$now)) { next; }
                   2049:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 2050:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.400     www      2051: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
1.373     www      2052:      }
                   2053:     return %returnhash;
1.399     www      2054: }
                   2055: 
                   2056: # ----------------------------------------------------- Frontpage Announcements
                   2057: #
                   2058: #
                   2059: 
                   2060: sub postannounce {
                   2061:     my ($server,$text)=@_;
                   2062:     unless (&allowed('psa',$hostdom{$server})) { return 'refused'; }
                   2063:     unless ($text=~/\w/) { $text=''; }
                   2064:     return &reply('setannounce:'.&escape($text),$server);
                   2065: }
                   2066: 
                   2067: sub getannounce {
1.448     albertel 2068: 
                   2069:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      2070: 	my $announcement='';
1.800     albertel 2071: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 2072: 	close($fh);
1.399     www      2073: 	if ($announcement=~/\w/) { 
                   2074: 	    return 
                   2075:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 2076:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      2077: 	} else {
                   2078: 	    return '';
                   2079: 	}
                   2080:     } else {
                   2081: 	return '';
                   2082:     }
1.351     www      2083: }
1.353     www      2084: 
                   2085: # ---------------------------------------------------------- Course ID routines
                   2086: # Deal with domain's nohist_courseid.db files
                   2087: #
                   2088: 
                   2089: sub courseidput {
                   2090:     my ($domain,$what,$coursehome)=@_;
                   2091:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   2092: }
                   2093: 
                   2094: sub courseiddump {
1.791     raeburn  2095:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok)=@_;
1.353     www      2096:     my %returnhash=();
1.355     www      2097:     unless ($domfilter) { $domfilter=''; }
1.353     www      2098:     foreach my $tryserver (keys %libserv) {
1.511     raeburn  2099:         if ( ($hostidflag == 1 && grep/^$tryserver$/,@{$hostidref}) || (!defined($hostidflag)) ) {
1.506     raeburn  2100: 	    if ((!$domfilter) || ($hostdom{$tryserver} eq $domfilter)) {
1.800     albertel 2101: 	        foreach my $line (
1.506     raeburn  2102:                  split(/\&/,&reply('courseiddump:'.$hostdom{$tryserver}.':'.
1.571     raeburn  2103: 			       $sincefilter.':'.&escape($descfilter).':'.
1.791     raeburn  2104:                                &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter).':'.&escape($typefilter).':'.&escape($regexp_ok),
1.354     www      2105:                                $tryserver))) {
1.800     albertel 2106: 		    my ($key,$value)=split(/\=/,$line,2);
1.506     raeburn  2107:                     if (($key) && ($value)) {
1.516     raeburn  2108: 		        $returnhash{&unescape($key)}=$value;
1.506     raeburn  2109:                     }
1.353     www      2110:                 }
                   2111:             }
                   2112:         }
                   2113:     }
                   2114:     return %returnhash;
                   2115: }
                   2116: 
1.658     raeburn  2117: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  2118: 
                   2119: sub dcmailput {
1.685     raeburn  2120:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  2121:     my $status = &Apache::lonnet::critical(
1.740     www      2122:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   2123:        &escape($message),$server);
1.662     raeburn  2124:     return $status;
                   2125: }
                   2126: 
1.658     raeburn  2127: sub dcmaildump {
                   2128:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  2129:     my %returnhash=();
                   2130:     if (exists($domain_primary{$dom})) {
                   2131:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   2132:                                                          &escape($enddate).':';
                   2133: 	my @esc_senders=map { &escape($_)} @$senders;
                   2134: 	$cmd.=&escape(join('&',@esc_senders));
1.800     albertel 2135: 	foreach my $line (split(/\&/,&reply($cmd,$domain_primary{$dom}))) {
                   2136:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  2137:             if (($key) && ($value)) {
                   2138:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  2139:             }
                   2140:         }
                   2141:     }
                   2142:     return %returnhash;
                   2143: }
1.662     raeburn  2144: # ---------------------------------------------------------- Domain roles
                   2145: 
                   2146: sub get_domain_roles {
                   2147:     my ($dom,$roles,$startdate,$enddate)=@_;
                   2148:     if (undef($startdate) || $startdate eq '') {
                   2149:         $startdate = '.';
                   2150:     }
                   2151:     if (undef($enddate) || $enddate eq '') {
                   2152:         $enddate = '.';
                   2153:     }
                   2154:     my $rolelist = join(':',@{$roles});
                   2155:     my %personnel = ();
                   2156:     foreach my $tryserver (keys(%libserv)) {
                   2157:         if ($hostdom{$tryserver} eq $dom) {
                   2158:             %{$personnel{$tryserver}}=();
1.800     albertel 2159:             foreach my $line (
1.662     raeburn  2160:                 split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   2161:                    &escape($startdate).':'.&escape($enddate).':'.
                   2162:                    &escape($rolelist), $tryserver))) {
1.800     albertel 2163:                 my ($key,$value) = split(/\=/,$line,2);
1.662     raeburn  2164:                 if (($key) && ($value)) {
                   2165:                     $personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   2166:                 }
                   2167:             }
                   2168:         }
                   2169:     }
                   2170:     return %personnel;
                   2171: }
1.658     raeburn  2172: 
1.149     www      2173: # ----------------------------------------------------------- Check out an item
                   2174: 
1.504     albertel 2175: sub get_first_access {
                   2176:     my ($type,$argsymb)=@_;
1.790     albertel 2177:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2178:     if ($argsymb) { $symb=$argsymb; }
                   2179:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2180:     if ($type eq 'map') {
                   2181: 	$res=&symbread($map);
                   2182:     } else {
                   2183: 	$res=$symb;
                   2184:     }
                   2185:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   2186:     return $times{"$courseid\0$res"};
1.504     albertel 2187: }
                   2188: 
                   2189: sub set_first_access {
                   2190:     my ($type)=@_;
1.790     albertel 2191:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2192:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2193:     if ($type eq 'map') {
                   2194: 	$res=&symbread($map);
                   2195:     } else {
                   2196: 	$res=$symb;
                   2197:     }
                   2198:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 2199:     if (!$firstaccess) {
1.588     albertel 2200: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 2201:     }
                   2202:     return 'already_set';
1.504     albertel 2203: }
                   2204: 
1.149     www      2205: sub checkout {
                   2206:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   2207:     my $now=time;
                   2208:     my $lonhost=$perlvar{'lonHostID'};
                   2209:     my $infostr=&escape(
1.234     www      2210:                  'CHECKOUTTOKEN&'.
1.149     www      2211:                  $tuname.'&'.
                   2212:                  $tudom.'&'.
                   2213:                  $tcrsid.'&'.
                   2214:                  $symb.'&'.
                   2215: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   2216:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      2217:     if ($token=~/^error\:/) { 
1.672     albertel 2218:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2219:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2220:                  "</font>");
                   2221:         return ''; 
                   2222:     }
                   2223: 
1.149     www      2224:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   2225:     $token=~tr/a-z/A-Z/;
                   2226: 
1.153     www      2227:     my %infohash=('resource.0.outtoken' => $token,
                   2228:                   'resource.0.checkouttime' => $now,
                   2229:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      2230: 
                   2231:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2232:        return '';
1.151     www      2233:     } else {
1.672     albertel 2234:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2235:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2236:                  "</font>");
1.149     www      2237:     }    
                   2238: 
                   2239:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2240:                          &escape('Checkout '.$infostr.' - '.
                   2241:                                                  $token)) ne 'ok') {
                   2242: 	return '';
1.151     www      2243:     } else {
1.672     albertel 2244:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2245:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2246:                  "</font>");
1.149     www      2247:     }
1.151     www      2248:     return $token;
1.149     www      2249: }
                   2250: 
                   2251: # ------------------------------------------------------------ Check in an item
                   2252: 
                   2253: sub checkin {
                   2254:     my $token=shift;
1.150     www      2255:     my $now=time;
                   2256:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   2257:     $lonhost=~tr/A-Z/a-z/;
1.595     albertel 2258:     my $dtoken=$ta.'_'.$hostname{$lonhost}.'_'.$tb;
1.150     www      2259:     $dtoken=~s/\W/\_/g;
1.234     www      2260:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      2261:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   2262: 
1.154     www      2263:     unless (($tuname) && ($tudom)) {
                   2264:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   2265:         return '';
                   2266:     }
                   2267:     
                   2268:     unless (&allowed('mgr',$tcrsid)) {
                   2269:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 2270:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      2271:         return '';
                   2272:     }
                   2273: 
1.153     www      2274:     my %infohash=('resource.0.intoken' => $token,
                   2275:                   'resource.0.checkintime' => $now,
                   2276:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      2277: 
                   2278:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2279:        return '';
                   2280:     }    
                   2281: 
                   2282:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2283:                          &escape('Checkin - '.$token)) ne 'ok') {
                   2284: 	return '';
                   2285:     }
                   2286: 
                   2287:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      2288: }
                   2289: 
                   2290: # --------------------------------------------- Set Expire Date for Spreadsheet
                   2291: 
                   2292: sub expirespread {
                   2293:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 2294:     my $cid=$env{'request.course.id'}; 
1.110     www      2295:     if ($cid) {
                   2296:        my $now=time;
                   2297:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 2298:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   2299:                             $env{'course.'.$cid.'.num'}.
1.110     www      2300: 	        	    ':nohist_expirationdates:'.
                   2301:                             &escape($key).'='.$now,
1.620     albertel 2302:                             $env{'course.'.$cid.'.home'})
1.110     www      2303:     }
                   2304:     return 'ok';
1.14      www      2305: }
                   2306: 
1.109     www      2307: # ----------------------------------------------------- Devalidate Spreadsheets
                   2308: 
                   2309: sub devalidate {
1.325     www      2310:     my ($symb,$uname,$udom)=@_;
1.620     albertel 2311:     my $cid=$env{'request.course.id'}; 
1.109     www      2312:     if ($cid) {
1.391     matthew  2313:         # delete the stored spreadsheets for
                   2314:         # - the student level sheet of this user in course's homespace
                   2315:         # - the assessment level sheet for this resource 
                   2316:         #   for this user in user's homespace
1.553     albertel 2317: 	# - current conditional state info
1.325     www      2318: 	my $key=$uname.':'.$udom.':';
1.109     www      2319:         my $status=
1.299     matthew  2320: 	    &del('nohist_calculatedsheets',
1.391     matthew  2321: 		 [$key.'studentcalc:'],
1.620     albertel 2322: 		 $env{'course.'.$cid.'.domain'},
                   2323: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 2324: 		.' '.
                   2325: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  2326: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      2327:         unless ($status eq 'ok ok') {
                   2328:            &logthis('Could not devalidate spreadsheet '.
1.325     www      2329:                     $uname.' at '.$udom.' for '.
1.109     www      2330: 		    $symb.': '.$status);
1.133     albertel 2331:         }
1.553     albertel 2332: 	&delenv('user.state.'.$cid);
1.109     www      2333:     }
                   2334: }
                   2335: 
1.265     albertel 2336: sub get_scalar {
                   2337:     my ($string,$end) = @_;
                   2338:     my $value;
                   2339:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   2340: 	$value = $1;
                   2341:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   2342: 	$value = $1;
                   2343:     }
                   2344:     return &unescape($value);
                   2345: }
                   2346: 
                   2347: sub array2str {
                   2348:   my (@array) = @_;
                   2349:   my $result=&arrayref2str(\@array);
                   2350:   $result=~s/^__ARRAY_REF__//;
                   2351:   $result=~s/__END_ARRAY_REF__$//;
                   2352:   return $result;
                   2353: }
                   2354: 
1.204     albertel 2355: sub arrayref2str {
                   2356:   my ($arrayref) = @_;
1.265     albertel 2357:   my $result='__ARRAY_REF__';
1.204     albertel 2358:   foreach my $elem (@$arrayref) {
1.265     albertel 2359:     if(ref($elem) eq 'ARRAY') {
                   2360:       $result.=&arrayref2str($elem).'&';
                   2361:     } elsif(ref($elem) eq 'HASH') {
                   2362:       $result.=&hashref2str($elem).'&';
                   2363:     } elsif(ref($elem)) {
                   2364:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 2365:     } else {
                   2366:       $result.=&escape($elem).'&';
                   2367:     }
                   2368:   }
                   2369:   $result=~s/\&$//;
1.265     albertel 2370:   $result .= '__END_ARRAY_REF__';
1.204     albertel 2371:   return $result;
                   2372: }
                   2373: 
1.168     albertel 2374: sub hash2str {
1.204     albertel 2375:   my (%hash) = @_;
                   2376:   my $result=&hashref2str(\%hash);
1.265     albertel 2377:   $result=~s/^__HASH_REF__//;
                   2378:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 2379:   return $result;
                   2380: }
                   2381: 
                   2382: sub hashref2str {
                   2383:   my ($hashref)=@_;
1.265     albertel 2384:   my $result='__HASH_REF__';
1.800     albertel 2385:   foreach my $key (sort(keys(%$hashref))) {
                   2386:     if (ref($key) eq 'ARRAY') {
                   2387:       $result.=&arrayref2str($key).'=';
                   2388:     } elsif (ref($key) eq 'HASH') {
                   2389:       $result.=&hashref2str($key).'=';
                   2390:     } elsif (ref($key)) {
1.265     albertel 2391:       $result.='=';
1.800     albertel 2392:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 2393:     } else {
1.800     albertel 2394: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 2395:     }
                   2396: 
1.800     albertel 2397:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   2398:       $result.=&arrayref2str($hashref->{$key}).'&';
                   2399:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   2400:       $result.=&hashref2str($hashref->{$key}).'&';
                   2401:     } elsif(ref($hashref->{$key})) {
1.265     albertel 2402:        $result.='&';
1.800     albertel 2403:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 2404:     } else {
1.800     albertel 2405:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 2406:     }
                   2407:   }
1.168     albertel 2408:   $result=~s/\&$//;
1.265     albertel 2409:   $result .= '__END_HASH_REF__';
1.168     albertel 2410:   return $result;
                   2411: }
                   2412: 
                   2413: sub str2hash {
1.265     albertel 2414:     my ($string)=@_;
                   2415:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   2416:     return %$hash;
                   2417: }
                   2418: 
                   2419: sub str2hashref {
1.168     albertel 2420:   my ($string) = @_;
1.265     albertel 2421: 
                   2422:   my %hash;
                   2423: 
                   2424:   if($string !~ /^__HASH_REF__/) {
                   2425:       if (! ($string eq '' || !defined($string))) {
                   2426: 	  $hash{'error'}='Not hash reference';
                   2427:       }
                   2428:       return (\%hash, $string);
                   2429:   }
                   2430: 
                   2431:   $string =~ s/^__HASH_REF__//;
                   2432: 
                   2433:   while($string !~ /^__END_HASH_REF__/) {
                   2434:       #key
                   2435:       my $key='';
                   2436:       if($string =~ /^__HASH_REF__/) {
                   2437:           ($key, $string)=&str2hashref($string);
                   2438:           if(defined($key->{'error'})) {
                   2439:               $hash{'error'}='Bad data';
                   2440:               return (\%hash, $string);
                   2441:           }
                   2442:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2443:           ($key, $string)=&str2arrayref($string);
                   2444:           if($key->[0] eq 'Array reference error') {
                   2445:               $hash{'error'}='Bad data';
                   2446:               return (\%hash, $string);
                   2447:           }
                   2448:       } else {
                   2449:           $string =~ s/^(.*?)=//;
1.267     albertel 2450: 	  $key=&unescape($1);
1.265     albertel 2451:       }
                   2452:       $string =~ s/^=//;
                   2453: 
                   2454:       #value
                   2455:       my $value='';
                   2456:       if($string =~ /^__HASH_REF__/) {
                   2457:           ($value, $string)=&str2hashref($string);
                   2458:           if(defined($value->{'error'})) {
                   2459:               $hash{'error'}='Bad data';
                   2460:               return (\%hash, $string);
                   2461:           }
                   2462:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2463:           ($value, $string)=&str2arrayref($string);
                   2464:           if($value->[0] eq 'Array reference error') {
                   2465:               $hash{'error'}='Bad data';
                   2466:               return (\%hash, $string);
                   2467:           }
                   2468:       } else {
                   2469: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   2470:       }
                   2471:       $string =~ s/^&//;
                   2472: 
                   2473:       $hash{$key}=$value;
1.204     albertel 2474:   }
1.265     albertel 2475: 
                   2476:   $string =~ s/^__END_HASH_REF__//;
                   2477: 
                   2478:   return (\%hash, $string);
1.204     albertel 2479: }
                   2480: 
                   2481: sub str2array {
1.265     albertel 2482:     my ($string)=@_;
                   2483:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   2484:     return @$array;
                   2485: }
                   2486: 
                   2487: sub str2arrayref {
1.204     albertel 2488:   my ($string) = @_;
1.265     albertel 2489:   my @array;
                   2490: 
                   2491:   if($string !~ /^__ARRAY_REF__/) {
                   2492:       if (! ($string eq '' || !defined($string))) {
                   2493: 	  $array[0]='Array reference error';
                   2494:       }
                   2495:       return (\@array, $string);
                   2496:   }
                   2497: 
                   2498:   $string =~ s/^__ARRAY_REF__//;
                   2499: 
                   2500:   while($string !~ /^__END_ARRAY_REF__/) {
                   2501:       my $value='';
                   2502:       if($string =~ /^__HASH_REF__/) {
                   2503:           ($value, $string)=&str2hashref($string);
                   2504:           if(defined($value->{'error'})) {
                   2505:               $array[0] ='Array reference error';
                   2506:               return (\@array, $string);
                   2507:           }
                   2508:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2509:           ($value, $string)=&str2arrayref($string);
                   2510:           if($value->[0] eq 'Array reference error') {
                   2511:               $array[0] ='Array reference error';
                   2512:               return (\@array, $string);
                   2513:           }
                   2514:       } else {
                   2515: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   2516:       }
                   2517:       $string =~ s/^&//;
                   2518: 
                   2519:       push(@array, $value);
1.191     harris41 2520:   }
1.265     albertel 2521: 
                   2522:   $string =~ s/^__END_ARRAY_REF__//;
                   2523: 
                   2524:   return (\@array, $string);
1.168     albertel 2525: }
                   2526: 
1.167     albertel 2527: # -------------------------------------------------------------------Temp Store
                   2528: 
1.168     albertel 2529: sub tmpreset {
                   2530:   my ($symb,$namespace,$domain,$stuname) = @_;
                   2531:   if (!$symb) {
                   2532:     $symb=&symbread();
1.620     albertel 2533:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2534:   }
                   2535:   $symb=escape($symb);
                   2536: 
1.620     albertel 2537:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 2538:   $namespace=~s/\//\_/g;
                   2539:   $namespace=~s/\W//g;
                   2540: 
1.620     albertel 2541:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2542:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2543:   if ($domain eq 'public' && $stuname eq 'public') {
                   2544:       $stuname=$ENV{'REMOTE_ADDR'};
                   2545:   }
1.168     albertel 2546:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2547:   my %hash;
                   2548:   if (tie(%hash,'GDBM_File',
                   2549: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2550: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2551:     foreach my $key (keys %hash) {
1.180     albertel 2552:       if ($key=~ /:$symb/) {
1.168     albertel 2553: 	delete($hash{$key});
                   2554:       }
                   2555:     }
                   2556:   }
                   2557: }
                   2558: 
1.167     albertel 2559: sub tmpstore {
1.168     albertel 2560:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2561: 
                   2562:   if (!$symb) {
                   2563:     $symb=&symbread();
1.620     albertel 2564:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2565:   }
                   2566:   $symb=escape($symb);
                   2567: 
                   2568:   if (!$namespace) {
                   2569:     # I don't think we would ever want to store this for a course.
                   2570:     # it seems this will only be used if we don't have a course.
1.620     albertel 2571:     #$namespace=$env{'request.course.id'};
1.168     albertel 2572:     #if (!$namespace) {
1.620     albertel 2573:       $namespace=$env{'request.state'};
1.168     albertel 2574:     #}
                   2575:   }
                   2576:   $namespace=~s/\//\_/g;
                   2577:   $namespace=~s/\W//g;
1.620     albertel 2578:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2579:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2580:   if ($domain eq 'public' && $stuname eq 'public') {
                   2581:       $stuname=$ENV{'REMOTE_ADDR'};
                   2582:   }
1.168     albertel 2583:   my $now=time;
                   2584:   my %hash;
                   2585:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2586:   if (tie(%hash,'GDBM_File',
                   2587: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2588: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2589:     $hash{"version:$symb"}++;
                   2590:     my $version=$hash{"version:$symb"};
                   2591:     my $allkeys=''; 
                   2592:     foreach my $key (keys(%$storehash)) {
                   2593:       $allkeys.=$key.':';
1.591     albertel 2594:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 2595:     }
                   2596:     $hash{"$version:$symb:timestamp"}=$now;
                   2597:     $allkeys.='timestamp';
                   2598:     $hash{"$version:keys:$symb"}=$allkeys;
                   2599:     if (untie(%hash)) {
                   2600:       return 'ok';
                   2601:     } else {
                   2602:       return "error:$!";
                   2603:     }
                   2604:   } else {
                   2605:     return "error:$!";
                   2606:   }
                   2607: }
1.167     albertel 2608: 
1.168     albertel 2609: # -----------------------------------------------------------------Temp Restore
1.167     albertel 2610: 
1.168     albertel 2611: sub tmprestore {
                   2612:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 2613: 
1.168     albertel 2614:   if (!$symb) {
                   2615:     $symb=&symbread();
1.620     albertel 2616:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2617:   }
                   2618:   $symb=escape($symb);
                   2619: 
1.620     albertel 2620:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 2621: 
1.620     albertel 2622:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2623:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2624:   if ($domain eq 'public' && $stuname eq 'public') {
                   2625:       $stuname=$ENV{'REMOTE_ADDR'};
                   2626:   }
1.168     albertel 2627:   my %returnhash;
                   2628:   $namespace=~s/\//\_/g;
                   2629:   $namespace=~s/\W//g;
                   2630:   my %hash;
                   2631:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2632:   if (tie(%hash,'GDBM_File',
                   2633: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2634: 	  &GDBM_READER(),0640)) {
1.168     albertel 2635:     my $version=$hash{"version:$symb"};
                   2636:     $returnhash{'version'}=$version;
                   2637:     my $scope;
                   2638:     for ($scope=1;$scope<=$version;$scope++) {
                   2639:       my $vkeys=$hash{"$scope:keys:$symb"};
                   2640:       my @keys=split(/:/,$vkeys);
                   2641:       my $key;
                   2642:       $returnhash{"$scope:keys"}=$vkeys;
                   2643:       foreach $key (@keys) {
1.591     albertel 2644: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   2645: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 2646:       }
                   2647:     }
1.168     albertel 2648:     if (!(untie(%hash))) {
                   2649:       return "error:$!";
                   2650:     }
                   2651:   } else {
                   2652:     return "error:$!";
                   2653:   }
                   2654:   return %returnhash;
1.167     albertel 2655: }
                   2656: 
1.9       www      2657: # ----------------------------------------------------------------------- Store
                   2658: 
                   2659: sub store {
1.124     www      2660:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2661:     my $home='';
                   2662: 
1.168     albertel 2663:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2664: 
1.213     www      2665:     $symb=&symbclean($symb);
1.122     albertel 2666:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2667: 
1.620     albertel 2668:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2669:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2670: 
                   2671:     &devalidate($symb,$stuname,$domain);
1.109     www      2672: 
                   2673:     $symb=escape($symb);
1.187     www      2674:     if (!$namespace) { 
1.620     albertel 2675:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2676:           return ''; 
                   2677:        } 
                   2678:     }
1.620     albertel 2679:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2680: 
                   2681:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2682:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   2683: 
1.12      www      2684:     my $namevalue='';
1.800     albertel 2685:     foreach my $key (keys(%$storehash)) {
                   2686:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 2687:     }
1.12      www      2688:     $namevalue=~s/\&$//;
1.187     www      2689:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      2690:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      2691: }
                   2692: 
1.47      www      2693: # -------------------------------------------------------------- Critical Store
                   2694: 
                   2695: sub cstore {
1.124     www      2696:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2697:     my $home='';
                   2698: 
1.168     albertel 2699:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2700: 
1.213     www      2701:     $symb=&symbclean($symb);
1.122     albertel 2702:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2703: 
1.620     albertel 2704:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2705:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2706: 
                   2707:     &devalidate($symb,$stuname,$domain);
1.109     www      2708: 
                   2709:     $symb=escape($symb);
1.187     www      2710:     if (!$namespace) { 
1.620     albertel 2711:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2712:           return ''; 
                   2713:        } 
                   2714:     }
1.620     albertel 2715:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2716: 
                   2717:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2718:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 2719: 
1.47      www      2720:     my $namevalue='';
1.800     albertel 2721:     foreach my $key (keys(%$storehash)) {
                   2722:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 2723:     }
1.47      www      2724:     $namevalue=~s/\&$//;
1.187     www      2725:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      2726:     return critical
                   2727:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      2728: }
                   2729: 
1.9       www      2730: # --------------------------------------------------------------------- Restore
                   2731: 
                   2732: sub restore {
1.124     www      2733:     my ($symb,$namespace,$domain,$stuname) = @_;
                   2734:     my $home='';
                   2735: 
1.168     albertel 2736:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2737: 
1.122     albertel 2738:     if (!$symb) {
                   2739:       unless ($symb=escape(&symbread())) { return ''; }
                   2740:     } else {
1.213     www      2741:       $symb=&escape(&symbclean($symb));
1.122     albertel 2742:     }
1.188     www      2743:     if (!$namespace) { 
1.620     albertel 2744:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      2745:           return ''; 
                   2746:        } 
                   2747:     }
1.620     albertel 2748:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2749:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   2750:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 2751:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   2752: 
1.12      www      2753:     my %returnhash=();
1.800     albertel 2754:     foreach my $line (split(/\&/,$answer)) {
                   2755: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 2756:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 2757:     }
1.75      www      2758:     my $version;
                   2759:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 2760:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   2761:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 2762:        }
1.75      www      2763:     }
1.13      www      2764:     return %returnhash;
1.34      www      2765: }
                   2766: 
                   2767: # ---------------------------------------------------------- Course Description
                   2768: 
                   2769: sub coursedescription {
1.731     albertel 2770:     my ($courseid,$args)=@_;
1.34      www      2771:     $courseid=~s/^\///;
1.49      www      2772:     $courseid=~s/\_/\//g;
1.34      www      2773:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 2774:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 2775:     my $normalid=$cdomain.'_'.$cnum;
                   2776:     # need to always cache even if we get errors otherwise we keep 
                   2777:     # trying and trying and trying to get the course description.
                   2778:     my %envhash=();
                   2779:     my %returnhash=();
1.731     albertel 2780:     
                   2781:     my $expiretime=600;
                   2782:     if ($env{'request.course.id'} eq $normalid) {
                   2783: 	$expiretime=120;
                   2784:     }
                   2785: 
                   2786:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   2787:     if (!$args->{'freshen_cache'}
                   2788: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   2789: 	foreach my $key (keys(%env)) {
                   2790: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   2791: 	    my ($setting) = $1;
                   2792: 	    $returnhash{$setting} = $env{$key};
                   2793: 	}
                   2794: 	return %returnhash;
                   2795:     }
                   2796: 
                   2797:     # get the data agin
                   2798:     if (!$args->{'one_time'}) {
                   2799: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   2800:     }
1.811     albertel 2801: 
1.34      www      2802:     if ($chome ne 'no_host') {
1.302     albertel 2803:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 2804:        if (!exists($returnhash{'con_lost'})) {
                   2805:            $returnhash{'home'}= $chome;
                   2806: 	   $returnhash{'domain'} = $cdomain;
                   2807: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  2808:            if (!defined($returnhash{'type'})) {
                   2809:                $returnhash{'type'} = 'Course';
                   2810:            }
1.130     albertel 2811:            while (my ($name,$value) = each %returnhash) {
1.53      www      2812:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 2813:            }
1.270     www      2814:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      2815:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 2816: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      2817:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   2818:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   2819:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      2820:        }
                   2821:     }
1.731     albertel 2822:     if (!$args->{'one_time'}) {
                   2823: 	&appenv(%envhash);
                   2824:     }
1.302     albertel 2825:     return %returnhash;
1.461     www      2826: }
                   2827: 
                   2828: # -------------------------------------------------See if a user is privileged
                   2829: 
                   2830: sub privileged {
                   2831:     my ($username,$domain)=@_;
                   2832:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   2833: 			&homeserver($username,$domain));
                   2834:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   2835:     my $now=time;
                   2836:     if ($rolesdump ne '') {
1.800     albertel 2837:         foreach my $entry (split(/&/,$rolesdump)) {
                   2838: 	    if ($entry!~/^rolesdef_/) {
                   2839: 		my ($area,$role)=split(/=/,$entry);
1.461     www      2840: 		$area=~s/\_\w\w$//;
                   2841: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   2842: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   2843: 		    my $active=1;
                   2844: 		    if ($tend) {
                   2845: 			if ($tend<$now) { $active=0; }
                   2846: 		    }
                   2847: 		    if ($tstart) {
                   2848: 			if ($tstart>$now) { $active=0; }
                   2849: 		    }
                   2850: 		    if ($active) { return 1; }
                   2851: 		}
                   2852: 	    }
                   2853: 	}
                   2854:     }
                   2855:     return 0;
1.9       www      2856: }
1.1       albertel 2857: 
1.103     harris41 2858: # -------------------------------------------------------- Get user privileges
1.11      www      2859: 
                   2860: sub rolesinit {
                   2861:     my ($domain,$username,$authhost)=@_;
                   2862:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12      www      2863:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11      www      2864:     my %allroles=();
1.678     raeburn  2865:     my %allgroups=();   
1.11      www      2866:     my $now=time;
1.743     albertel 2867:     my %userroles = ('user.login.time' => $now);
1.678     raeburn  2868:     my $group_privs;
1.11      www      2869: 
                   2870:     if ($rolesdump ne '') {
1.800     albertel 2871:         foreach my $entry (split(/&/,$rolesdump)) {
                   2872: 	  if ($entry!~/^rolesdef_/) {
                   2873:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 2874: 	    $area=~s/\_\w\w$//;
1.678     raeburn  2875:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 2876: 	    if ($role=~/^cr/) { 
1.807     albertel 2877: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   2878: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 2879: 		    ($tend,$tstart)=split('_',$trest);
                   2880: 		} else {
                   2881: 		    $trole=$role;
                   2882: 		}
1.678     raeburn  2883:             } elsif ($role =~ m|^gr/|) {
                   2884:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   2885:                 ($trole,$group_privs) = split(/\//,$trole);
                   2886:                 $group_privs = &unescape($group_privs);
1.587     albertel 2887: 	    } else {
                   2888: 		($trole,$tend,$tstart)=split(/_/,$role);
                   2889: 	    }
1.743     albertel 2890: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   2891: 					 $username);
                   2892: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  2893:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   2894:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      2895:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 2896: 		my $spec=$trole.'.'.$area;
                   2897: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   2898: 		if ($trole =~ /^cr\//) {
1.567     raeburn  2899:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  2900:                 } elsif ($trole eq 'gr') {
                   2901:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 2902: 		} else {
1.567     raeburn  2903:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 2904: 		}
1.12      www      2905:             }
1.662     raeburn  2906:           }
1.191     harris41 2907:         }
1.743     albertel 2908:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   2909:         $userroles{'user.adv'}    = $adv;
                   2910: 	$userroles{'user.author'} = $author;
1.620     albertel 2911:         $env{'user.adv'}=$adv;
1.11      www      2912:     }
1.743     albertel 2913:     return \%userroles;  
1.11      www      2914: }
                   2915: 
1.567     raeburn  2916: sub set_arearole {
                   2917:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   2918: # log the associated role with the area
                   2919:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 2920:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  2921: }
                   2922: 
                   2923: sub custom_roleprivs {
                   2924:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   2925:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   2926:     my $homsvr=homeserver($rauthor,$rdomain);
                   2927:     if ($hostname{$homsvr} ne '') {
                   2928:         my ($rdummy,$roledef)=
                   2929:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   2930:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   2931:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   2932:             if (defined($syspriv)) {
                   2933:                 $$allroles{'cm./'}.=':'.$syspriv;
                   2934:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   2935:             }
                   2936:             if ($tdomain ne '') {
                   2937:                 if (defined($dompriv)) {
                   2938:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   2939:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   2940:                 }
                   2941:                 if (($trest ne '') && (defined($coursepriv))) {
                   2942:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   2943:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   2944:                 }
                   2945:             }
                   2946:         }
                   2947:     }
                   2948: }
                   2949: 
1.678     raeburn  2950: sub group_roleprivs {
                   2951:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   2952:     my $access = 1;
                   2953:     my $now = time;
                   2954:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   2955:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   2956:     if ($access) {
1.811     albertel 2957:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  2958:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   2959:     }
                   2960: }
1.567     raeburn  2961: 
                   2962: sub standard_roleprivs {
                   2963:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   2964:     if (defined($pr{$trole.':s'})) {
                   2965:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   2966:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   2967:     }
                   2968:     if ($tdomain ne '') {
                   2969:         if (defined($pr{$trole.':d'})) {
                   2970:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   2971:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   2972:         }
                   2973:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   2974:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   2975:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   2976:         }
                   2977:     }
                   2978: }
                   2979: 
                   2980: sub set_userprivs {
1.678     raeburn  2981:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  2982:     my $author=0;
                   2983:     my $adv=0;
1.678     raeburn  2984:     my %grouproles = ();
                   2985:     if (keys(%{$allgroups}) > 0) {
                   2986:         foreach my $role (keys %{$allroles}) {
1.681     raeburn  2987:             my ($trole,$area,$sec,$extendedarea);
1.811     albertel 2988:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)-) {
1.678     raeburn  2989:                 $trole = $1;
                   2990:                 $area = $2;
1.681     raeburn  2991:                 $sec = $3;
                   2992:                 $extendedarea = $area.$sec;
                   2993:                 if (exists($$allgroups{$area})) {
                   2994:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   2995:                         my $spec = $trole.'.'.$extendedarea;
                   2996:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   2997:                                                 $$allgroups{$area}{$group};
1.678     raeburn  2998:                     }
                   2999:                 }
                   3000:             }
                   3001:         }
                   3002:     }
1.800     albertel 3003:     foreach my $group (keys(%grouproles)) {
                   3004:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  3005:     }
1.800     albertel 3006:     foreach my $role (keys(%{$allroles})) {
                   3007:         my %thesepriv;
                   3008:         if (($role=~/^au/) || ($role=~/^ca/)) { $author=1; }
                   3009:         foreach my $item (split(/:/,$$allroles{$role})) {
                   3010:             if ($item ne '') {
                   3011:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  3012:                 if ($restrictions eq '') {
                   3013:                     $thesepriv{$privilege}='F';
                   3014:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   3015:                     $thesepriv{$privilege}.=$restrictions;
                   3016:                 }
                   3017:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   3018:             }
                   3019:         }
                   3020:         my $thesestr='';
1.800     albertel 3021:         foreach my $priv (keys(%thesepriv)) {
                   3022: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   3023: 	}
                   3024:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  3025:     }
                   3026:     return ($author,$adv);
                   3027: }
                   3028: 
1.12      www      3029: # --------------------------------------------------------------- get interface
                   3030: 
                   3031: sub get {
1.131     albertel 3032:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3033:    my $items='';
1.800     albertel 3034:    foreach my $item (@$storearr) {
                   3035:        $items.=&escape($item).'&';
1.191     harris41 3036:    }
1.12      www      3037:    $items=~s/\&$//;
1.620     albertel 3038:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3039:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 3040:    my $uhome=&homeserver($uname,$udomain);
                   3041: 
1.133     albertel 3042:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3043:    my @pairs=split(/\&/,$rep);
1.273     albertel 3044:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   3045:      return @pairs;
                   3046:    }
1.15      www      3047:    my %returnhash=();
1.42      www      3048:    my $i=0;
1.800     albertel 3049:    foreach my $item (@$storearr) {
                   3050:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3051:       $i++;
1.191     harris41 3052:    }
1.15      www      3053:    return %returnhash;
1.27      www      3054: }
                   3055: 
                   3056: # --------------------------------------------------------------- del interface
                   3057: 
                   3058: sub del {
1.133     albertel 3059:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      3060:    my $items='';
1.800     albertel 3061:    foreach my $item (@$storearr) {
                   3062:        $items.=&escape($item).'&';
1.191     harris41 3063:    }
1.27      www      3064:    $items=~s/\&$//;
1.620     albertel 3065:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3066:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3067:    my $uhome=&homeserver($uname,$udomain);
                   3068: 
                   3069:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3070: }
                   3071: 
                   3072: # -------------------------------------------------------------- dump interface
                   3073: 
                   3074: sub dump {
1.755     albertel 3075:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   3076:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3077:     if (!$uname) { $uname=$env{'user.name'}; }
                   3078:     my $uhome=&homeserver($uname,$udomain);
                   3079:     if ($regexp) {
                   3080: 	$regexp=&escape($regexp);
                   3081:     } else {
                   3082: 	$regexp='.';
                   3083:     }
                   3084:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3085:     my @pairs=split(/\&/,$rep);
                   3086:     my %returnhash=();
                   3087:     foreach my $item (@pairs) {
                   3088: 	my ($key,$value)=split(/=/,$item,2);
                   3089: 	$key = &unescape($key);
                   3090: 	next if ($key =~ /^error: 2 /);
                   3091: 	$returnhash{$key}=&thaw_unescape($value);
                   3092:     }
                   3093:     return %returnhash;
1.407     www      3094: }
                   3095: 
1.717     albertel 3096: # --------------------------------------------------------- dumpstore interface
                   3097: 
                   3098: sub dumpstore {
                   3099:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 3100:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3101:    if (!$uname) { $uname=$env{'user.name'}; }
                   3102:    my $uhome=&homeserver($uname,$udomain);
                   3103:    if ($regexp) {
                   3104:        $regexp=&escape($regexp);
                   3105:    } else {
                   3106:        $regexp='.';
                   3107:    }
                   3108:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3109:    my @pairs=split(/\&/,$rep);
                   3110:    my %returnhash=();
                   3111:    foreach my $item (@pairs) {
                   3112:        my ($key,$value)=split(/=/,$item,2);
                   3113:        next if ($key =~ /^error: 2 /);
                   3114:        $returnhash{$key}=&thaw_unescape($value);
                   3115:    }
                   3116:    return %returnhash;
1.717     albertel 3117: }
                   3118: 
1.407     www      3119: # -------------------------------------------------------------- keys interface
                   3120: 
                   3121: sub getkeys {
                   3122:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 3123:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3124:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      3125:    my $uhome=&homeserver($uname,$udomain);
                   3126:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   3127:    my @keyarray=();
1.800     albertel 3128:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  3129:       next if ($key =~ /^error: 2 /);
1.800     albertel 3130:       push(@keyarray,&unescape($key));
1.407     www      3131:    }
                   3132:    return @keyarray;
1.318     matthew  3133: }
                   3134: 
1.319     matthew  3135: # --------------------------------------------------------------- currentdump
                   3136: sub currentdump {
1.328     matthew  3137:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 3138:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   3139:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   3140:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  3141:    my $uhome = &homeserver($sname,$sdom);
                   3142:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  3143:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  3144:    #
1.318     matthew  3145:    my %returnhash=();
1.319     matthew  3146:    #
                   3147:    if ($rep eq "unknown_cmd") { 
                   3148:        # an old lond will not know currentdump
                   3149:        # Do a dump and make it look like a currentdump
1.822     albertel 3150:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  3151:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   3152:        my %hash = @tmp;
                   3153:        @tmp=();
1.424     matthew  3154:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  3155:    } else {
                   3156:        my @pairs=split(/\&/,$rep);
1.800     albertel 3157:        foreach my $pair (@pairs) {
                   3158:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  3159:            my ($symb,$param) = split(/:/,$key);
                   3160:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 3161:                                                         &thaw_unescape($value);
1.319     matthew  3162:        }
1.191     harris41 3163:    }
1.12      www      3164:    return %returnhash;
1.424     matthew  3165: }
                   3166: 
                   3167: sub convert_dump_to_currentdump{
                   3168:     my %hash = %{shift()};
                   3169:     my %returnhash;
                   3170:     # Code ripped from lond, essentially.  The only difference
                   3171:     # here is the unescaping done by lonnet::dump().  Conceivably
                   3172:     # we might run in to problems with parameter names =~ /^v\./
                   3173:     while (my ($key,$value) = each(%hash)) {
                   3174:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 3175: 	$symb  = &unescape($symb);
                   3176: 	$param = &unescape($param);
1.424     matthew  3177:         next if ($v eq 'version' || $symb eq 'keys');
                   3178:         next if (exists($returnhash{$symb}) &&
                   3179:                  exists($returnhash{$symb}->{$param}) &&
                   3180:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   3181:         $returnhash{$symb}->{$param}=$value;
                   3182:         $returnhash{$symb}->{'v.'.$param}=$v;
                   3183:     }
                   3184:     #
                   3185:     # Remove all of the keys in the hashes which keep track of
                   3186:     # the version of the parameter.
                   3187:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   3188:         # use a foreach because we are going to delete from the hash.
                   3189:         foreach my $key (keys(%$param_hash)) {
                   3190:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   3191:         }
                   3192:     }
                   3193:     return \%returnhash;
1.12      www      3194: }
                   3195: 
1.627     albertel 3196: # ------------------------------------------------------ critical inc interface
                   3197: 
                   3198: sub cinc {
                   3199:     return &inc(@_,'critical');
                   3200: }
                   3201: 
1.449     matthew  3202: # --------------------------------------------------------------- inc interface
                   3203: 
                   3204: sub inc {
1.627     albertel 3205:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 3206:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3207:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  3208:     my $uhome=&homeserver($uname,$udomain);
                   3209:     my $items='';
                   3210:     if (! ref($store)) {
                   3211:         # got a single value, so use that instead
                   3212:         $items = &escape($store).'=&';
                   3213:     } elsif (ref($store) eq 'SCALAR') {
                   3214:         $items = &escape($$store).'=&';        
                   3215:     } elsif (ref($store) eq 'ARRAY') {
                   3216:         $items = join('=&',map {&escape($_);} @{$store});
                   3217:     } elsif (ref($store) eq 'HASH') {
                   3218:         while (my($key,$value) = each(%{$store})) {
                   3219:             $items.= &escape($key).'='.&escape($value).'&';
                   3220:         }
                   3221:     }
                   3222:     $items=~s/\&$//;
1.627     albertel 3223:     if ($critical) {
                   3224: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3225:     } else {
                   3226: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3227:     }
1.449     matthew  3228: }
                   3229: 
1.12      www      3230: # --------------------------------------------------------------- put interface
                   3231: 
                   3232: sub put {
1.134     albertel 3233:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3234:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3235:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3236:    my $uhome=&homeserver($uname,$udomain);
1.12      www      3237:    my $items='';
1.800     albertel 3238:    foreach my $item (keys(%$storehash)) {
                   3239:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3240:    }
1.12      www      3241:    $items=~s/\&$//;
1.134     albertel 3242:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      3243: }
                   3244: 
1.631     albertel 3245: # ------------------------------------------------------------ newput interface
                   3246: 
                   3247: sub newput {
                   3248:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   3249:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3250:    if (!$uname) { $uname=$env{'user.name'}; }
                   3251:    my $uhome=&homeserver($uname,$udomain);
                   3252:    my $items='';
                   3253:    foreach my $key (keys(%$storehash)) {
                   3254:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   3255:    }
                   3256:    $items=~s/\&$//;
                   3257:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   3258: }
                   3259: 
                   3260: # ---------------------------------------------------------  putstore interface
                   3261: 
1.524     raeburn  3262: sub putstore {
1.715     albertel 3263:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 3264:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3265:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  3266:    my $uhome=&homeserver($uname,$udomain);
                   3267:    my $items='';
1.715     albertel 3268:    foreach my $key (keys(%$storehash)) {
                   3269:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  3270:    }
1.715     albertel 3271:    $items=~s/\&$//;
1.716     albertel 3272:    my $esc_symb=&escape($symb);
                   3273:    my $esc_v=&escape($version);
1.715     albertel 3274:    my $reply =
1.716     albertel 3275:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 3276: 	      $uhome);
                   3277:    if ($reply eq 'unknown_cmd') {
1.716     albertel 3278:        # gfall back to way things use to be done
1.715     albertel 3279:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   3280: 			    $uname);
1.524     raeburn  3281:    }
1.715     albertel 3282:    return $reply;
                   3283: }
                   3284: 
                   3285: sub old_putstore {
1.716     albertel 3286:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   3287:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3288:     if (!$uname) { $uname=$env{'user.name'}; }
                   3289:     my $uhome=&homeserver($uname,$udomain);
                   3290:     my %newstorehash;
1.800     albertel 3291:     foreach my $item (keys(%$storehash)) {
                   3292: 	my $key = $version.':'.&escape($symb).':'.$item;
                   3293: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 3294:     }
                   3295:     my $items='';
                   3296:     my %allitems = ();
1.800     albertel 3297:     foreach my $item (keys(%newstorehash)) {
                   3298: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 3299: 	    my $key = $1.':keys:'.$2;
                   3300: 	    $allitems{$key} .= $3.':';
                   3301: 	}
1.800     albertel 3302: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 3303:     }
1.800     albertel 3304:     foreach my $item (keys(%allitems)) {
                   3305: 	$allitems{$item} =~ s/\:$//;
                   3306: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 3307:     }
                   3308:     $items=~s/\&$//;
                   3309:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  3310: }
                   3311: 
1.47      www      3312: # ------------------------------------------------------ critical put interface
                   3313: 
                   3314: sub cput {
1.134     albertel 3315:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3316:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3317:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3318:    my $uhome=&homeserver($uname,$udomain);
1.47      www      3319:    my $items='';
1.800     albertel 3320:    foreach my $item (keys(%$storehash)) {
                   3321:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3322:    }
1.47      www      3323:    $items=~s/\&$//;
1.134     albertel 3324:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3325: }
                   3326: 
                   3327: # -------------------------------------------------------------- eget interface
                   3328: 
                   3329: sub eget {
1.133     albertel 3330:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3331:    my $items='';
1.800     albertel 3332:    foreach my $item (@$storearr) {
                   3333:        $items.=&escape($item).'&';
1.191     harris41 3334:    }
1.12      www      3335:    $items=~s/\&$//;
1.620     albertel 3336:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3337:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3338:    my $uhome=&homeserver($uname,$udomain);
                   3339:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3340:    my @pairs=split(/\&/,$rep);
                   3341:    my %returnhash=();
1.42      www      3342:    my $i=0;
1.800     albertel 3343:    foreach my $item (@$storearr) {
                   3344:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3345:       $i++;
1.191     harris41 3346:    }
1.12      www      3347:    return %returnhash;
                   3348: }
                   3349: 
1.667     albertel 3350: # ------------------------------------------------------------ tmpput interface
                   3351: sub tmpput {
1.802     raeburn  3352:     my ($storehash,$server,$context)=@_;
1.667     albertel 3353:     my $items='';
1.800     albertel 3354:     foreach my $item (keys(%$storehash)) {
                   3355: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 3356:     }
                   3357:     $items=~s/\&$//;
1.802     raeburn  3358:     if (defined($context)) {
                   3359:         $items .= ':'.&escape($context);
                   3360:     }
1.667     albertel 3361:     return &reply("tmpput:$items",$server);
                   3362: }
                   3363: 
                   3364: # ------------------------------------------------------------ tmpget interface
                   3365: sub tmpget {
1.688     albertel 3366:     my ($token,$server)=@_;
                   3367:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3368:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 3369:     my %returnhash;
                   3370:     foreach my $item (split(/\&/,$rep)) {
                   3371: 	my ($key,$value)=split(/=/,$item);
                   3372: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   3373:     }
                   3374:     return %returnhash;
                   3375: }
                   3376: 
1.688     albertel 3377: # ------------------------------------------------------------ tmpget interface
                   3378: sub tmpdel {
                   3379:     my ($token,$server)=@_;
                   3380:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3381:     return &reply("tmpdel:$token",$server);
                   3382: }
                   3383: 
1.765     albertel 3384: # -------------------------------------------------- portfolio access checking
                   3385: 
                   3386: sub portfolio_access {
1.766     albertel 3387:     my ($requrl) = @_;
1.765     albertel 3388:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   3389:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  3390:     if ($result) {
                   3391:         my %setters;
                   3392:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3393:             my ($startblock,$endblock) =
                   3394:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   3395:             if ($startblock && $endblock) {
                   3396:                 return 'B';
                   3397:             }
                   3398:         } else {
                   3399:             my ($startblock,$endblock) =
                   3400:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   3401:             if ($startblock && $endblock) {
                   3402:                 return 'B';
                   3403:             }
                   3404:         }
                   3405:     }
1.765     albertel 3406:     if ($result eq 'ok') {
1.766     albertel 3407:        return 'F';
1.765     albertel 3408:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 3409:        return 'A';
1.765     albertel 3410:     }
1.766     albertel 3411:     return '';
1.765     albertel 3412: }
                   3413: 
                   3414: sub get_portfolio_access {
1.767     albertel 3415:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   3416: 
                   3417:     if (!ref($access_hash)) {
                   3418: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   3419: 	my %access_controls = &get_access_controls($current_perms,$group,
                   3420: 						   $file_name);
                   3421: 	$access_hash = $access_controls{$file_name};
                   3422:     }
                   3423: 
1.765     albertel 3424:     my ($public,$guest,@domains,@users,@courses,@groups);
                   3425:     my $now = time;
                   3426:     if (ref($access_hash) eq 'HASH') {
                   3427:         foreach my $key (keys(%{$access_hash})) {
                   3428:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   3429:             if ($start > $now) {
                   3430:                 next;
                   3431:             }
                   3432:             if ($end && $end<$now) {
                   3433:                 next;
                   3434:             }
                   3435:             if ($scope eq 'public') {
                   3436:                 $public = $key;
                   3437:                 last;
                   3438:             } elsif ($scope eq 'guest') {
                   3439:                 $guest = $key;
                   3440:             } elsif ($scope eq 'domains') {
                   3441:                 push(@domains,$key);
                   3442:             } elsif ($scope eq 'users') {
                   3443:                 push(@users,$key);
                   3444:             } elsif ($scope eq 'course') {
                   3445:                 push(@courses,$key);
                   3446:             } elsif ($scope eq 'group') {
                   3447:                 push(@groups,$key);
                   3448:             }
                   3449:         }
                   3450:         if ($public) {
                   3451:             return 'ok';
                   3452:         }
                   3453:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3454:             if ($guest) {
                   3455:                 return $guest;
                   3456:             }
                   3457:         } else {
                   3458:             if (@domains > 0) {
                   3459:                 foreach my $domkey (@domains) {
                   3460:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   3461:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   3462:                             return 'ok';
                   3463:                         }
                   3464:                     }
                   3465:                 }
                   3466:             }
                   3467:             if (@users > 0) {
                   3468:                 foreach my $userkey (@users) {
1.824.2.4  albertel 3469:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   3470:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   3471:                             if (ref($item) eq 'HASH') {
                   3472:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   3473:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   3474:                                     return 'ok';
                   3475:                                 }
                   3476:                             }
                   3477:                         }
                   3478:                     } 
1.765     albertel 3479:                 }
                   3480:             }
                   3481:             my %roleshash;
                   3482:             my @courses_and_groups = @courses;
                   3483:             push(@courses_and_groups,@groups); 
                   3484:             if (@courses_and_groups > 0) {
                   3485:                 my (%allgroups,%allroles); 
                   3486:                 my ($start,$end,$role,$sec,$group);
                   3487:                 foreach my $envkey (%env) {
1.811     albertel 3488:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 3489:                         my $cid = $2.'_'.$3; 
                   3490:                         if ($1 eq 'gr') {
                   3491:                             $group = $4;
                   3492:                             $allgroups{$cid}{$group} = $env{$envkey};
                   3493:                         } else {
                   3494:                             if ($4 eq '') {
                   3495:                                 $sec = 'none';
                   3496:                             } else {
                   3497:                                 $sec = $4;
                   3498:                             }
                   3499:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3500:                         }
1.811     albertel 3501:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 3502:                         my $cid = $2.'_'.$3;
                   3503:                         if ($4 eq '') {
                   3504:                             $sec = 'none';
                   3505:                         } else {
                   3506:                             $sec = $4;
                   3507:                         }
                   3508:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3509:                     }
                   3510:                 }
                   3511:                 if (keys(%allroles) == 0) {
                   3512:                     return;
                   3513:                 }
                   3514:                 foreach my $key (@courses_and_groups) {
                   3515:                     my %content = %{$$access_hash{$key}};
                   3516:                     my $cnum = $content{'number'};
                   3517:                     my $cdom = $content{'domain'};
                   3518:                     my $cid = $cdom.'_'.$cnum;
                   3519:                     if (!exists($allroles{$cid})) {
                   3520:                         next;
                   3521:                     }    
                   3522:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   3523:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   3524:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   3525:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   3526:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   3527:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   3528:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   3529:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   3530:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   3531:                                         if (grep/^all$/,@sections) {
                   3532:                                             return 'ok';
                   3533:                                         } else {
                   3534:                                             if (grep/^$sec$/,@sections) {
                   3535:                                                 return 'ok';
                   3536:                                             }
                   3537:                                         }
                   3538:                                     }
                   3539:                                 }
                   3540:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   3541:                                     if (grep/^none$/,@groups) {
                   3542:                                         return 'ok';
                   3543:                                     }
                   3544:                                 } else {
                   3545:                                     if (grep/^all$/,@groups) {
                   3546:                                         return 'ok';
                   3547:                                     } 
                   3548:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   3549:                                         if (grep/^$group$/,@groups) {
                   3550:                                             return 'ok';
                   3551:                                         }
                   3552:                                     }
                   3553:                                 } 
                   3554:                             }
                   3555:                         }
                   3556:                     }
                   3557:                 }
                   3558:             }
                   3559:             if ($guest) {
                   3560:                 return $guest;
                   3561:             }
                   3562:         }
                   3563:     }
                   3564:     return;
                   3565: }
                   3566: 
                   3567: sub course_group_datechecker {
                   3568:     my ($dates,$now,$status) = @_;
                   3569:     my ($start,$end) = split(/\./,$dates);
                   3570:     if (!$start && !$end) {
                   3571:         return 'ok';
                   3572:     }
                   3573:     if (grep/^active$/,@{$status}) {
                   3574:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   3575:             return 'ok';
                   3576:         }
                   3577:     }
                   3578:     if (grep/^previous$/,@{$status}) {
                   3579:         if ($end > $now ) {
                   3580:             return 'ok';
                   3581:         }
                   3582:     }
                   3583:     if (grep/^future$/,@{$status}) {
                   3584:         if ($start > $now) {
                   3585:             return 'ok';
                   3586:         }
                   3587:     }
                   3588:     return; 
                   3589: }
                   3590: 
                   3591: sub parse_portfolio_url {
                   3592:     my ($url) = @_;
                   3593: 
                   3594:     my ($type,$udom,$unum,$group,$file_name);
                   3595:     
1.823     albertel 3596:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 3597: 	$type = 1;
                   3598:         $udom = $1;
                   3599:         $unum = $2;
                   3600:         $file_name = $3;
1.823     albertel 3601:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 3602: 	$type = 2;
                   3603:         $udom = $1;
                   3604:         $unum = $2;
                   3605:         $group = $3;
                   3606:         $file_name = $3.'/'.$4;
                   3607:     }
                   3608:     if (wantarray) {
                   3609: 	return ($type,$udom,$unum,$file_name,$group);
                   3610:     }
                   3611:     return $type;
                   3612: }
                   3613: 
                   3614: sub is_portfolio_url {
                   3615:     my ($url) = @_;
                   3616:     return scalar(&parse_portfolio_url($url));
                   3617: }
                   3618: 
1.798     raeburn  3619: sub is_portfolio_file {
                   3620:     my ($file) = @_;
1.820     raeburn  3621:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  3622:         return 1;
                   3623:     }
                   3624:     return;
                   3625: }
                   3626: 
                   3627: 
1.341     www      3628: # ---------------------------------------------- Custom access rule evaluation
                   3629: 
                   3630: sub customaccess {
                   3631:     my ($priv,$uri)=@_;
1.807     albertel 3632:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      3633:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 3634:     $udom = &LONCAPA::clean_domain($udom);
                   3635:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      3636:     my $access=0;
1.800     albertel 3637:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
                   3638: 	my ($effect,$realm,$role)=split(/\:/,$right);
1.343     www      3639:         if ($role) {
                   3640: 	   if ($role ne $urole) { next; }
                   3641:         }
1.800     albertel 3642:         foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   3643:             my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
1.343     www      3644:             if ($tdom) {
                   3645: 		if ($tdom ne $udom) { next; }
                   3646:             }
                   3647:             if ($tcrs) {
                   3648: 		if ($tcrs ne $ucrs) { next; }
                   3649:             }
                   3650:             if ($tsec) {
                   3651: 		if ($tsec ne $usec) { next; }
                   3652:             }
                   3653:             $access=($effect eq 'allow');
                   3654:             last;
1.342     www      3655:         }
1.402     bowersj2 3656: 	if ($realm eq '' && $role eq '') {
                   3657:             $access=($effect eq 'allow');
                   3658: 	}
1.341     www      3659:     }
                   3660:     return $access;
                   3661: }
                   3662: 
1.103     harris41 3663: # ------------------------------------------------- Check for a user privilege
1.12      www      3664: 
                   3665: sub allowed {
1.810     raeburn  3666:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 3667:     my $ver_orguri=$uri;
1.439     www      3668:     $uri=&deversion($uri);
1.152     www      3669:     my $orguri=$uri;
1.52      www      3670:     $uri=&declutter($uri);
1.809     raeburn  3671: 
1.810     raeburn  3672:     if ($priv eq 'evb') {
                   3673: # Evade communication block restrictions for specified role in a course
                   3674:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   3675:             return $1;
                   3676:         } else {
                   3677:             return;
                   3678:         }
                   3679:     }
                   3680: 
1.620     albertel 3681:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      3682: # Free bre access to adm and meta resources
1.775     albertel 3683:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 3684: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   3685: 	&& ($priv eq 'bre')) {
1.14      www      3686: 	return 'F';
1.159     www      3687:     }
                   3688: 
1.545     banghart 3689: # Free bre access to user's own portfolio contents
1.714     raeburn  3690:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  3691:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  3692: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  3693:         my %setters;
                   3694:         my ($startblock,$endblock) = 
                   3695:             &Apache::loncommon::blockcheck(\%setters,'port');
                   3696:         if ($startblock && $endblock) {
                   3697:             return 'B';
                   3698:         } else {
                   3699:             return 'F';
                   3700:         }
1.545     banghart 3701:     }
                   3702: 
1.762     raeburn  3703: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  3704:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   3705:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   3706:         if (exists($env{'request.course.id'})) {
                   3707:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3708:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3709:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   3710:                 my $courseprivid=$env{'request.course.id'};
                   3711:                 $courseprivid=~s/\_/\//;
                   3712:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   3713:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   3714:                     return $1; 
1.762     raeburn  3715:                 } else {
                   3716:                     if ($env{'request.course.sec'}) {
                   3717:                         $courseprivid.='/'.$env{'request.course.sec'};
                   3718:                     }
                   3719:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   3720:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   3721:                         return $2;
                   3722:                     }
1.714     raeburn  3723:                 }
                   3724:             }
                   3725:         }
                   3726:     }
                   3727: 
1.159     www      3728: # Free bre to public access
                   3729: 
                   3730:     if ($priv eq 'bre') {
1.238     www      3731:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 3732: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      3733:            return 'F'; 
                   3734:         }
1.238     www      3735:         if ($copyright eq 'priv') {
                   3736:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3737: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      3738: 		return '';
                   3739:             }
                   3740:         }
                   3741:         if ($copyright eq 'domain') {
                   3742:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3743: 	    unless (($env{'user.domain'} eq $1) ||
                   3744:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      3745: 		return '';
                   3746:             }
1.262     matthew  3747:         }
1.620     albertel 3748:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  3749:             # Library role, so allow browsing of resources in this domain.
                   3750:             return 'F';
1.238     www      3751:         }
1.341     www      3752:         if ($copyright eq 'custom') {
                   3753: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   3754:         }
1.14      www      3755:     }
1.264     matthew  3756:     # Domain coordinator is trying to create a course
1.620     albertel 3757:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  3758:         # uri is the requested domain in this case.
                   3759:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  3760:         # a role of dc for the domain in question.
1.620     albertel 3761:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  3762:     }
1.29      www      3763: 
1.52      www      3764:     my $thisallowed='';
                   3765:     my $statecond=0;
                   3766:     my $courseprivid='';
                   3767: 
                   3768: # Course
                   3769: 
1.620     albertel 3770:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3771:        $thisallowed.=$1;
                   3772:     }
1.29      www      3773: 
1.52      www      3774: # Domain
                   3775: 
1.620     albertel 3776:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 3777:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3778:        $thisallowed.=$1;
                   3779:     }
1.52      www      3780: 
                   3781: # Course: uri itself is a course
1.66      www      3782:     my $courseuri=$uri;
                   3783:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      3784:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      3785: 
1.620     albertel 3786:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 3787:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3788:        $thisallowed.=$1;
                   3789:     }
1.29      www      3790: 
1.665     albertel 3791: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 3792: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 3793:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 3794: 	$thisallowed='';
1.671     raeburn  3795:         my ($match)=&is_on_map($uri);
                   3796:         if ($match) {
                   3797:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   3798:                   =~/\Q$priv\E\&([^\:]*)/) {
                   3799:                 $thisallowed.=$1;
                   3800:             }
                   3801:         } else {
1.705     albertel 3802:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  3803:             if ($refuri) {
                   3804:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  3805:                     $thisallowed='F';
1.671     raeburn  3806:                 } else {
                   3807:                     $refuri=&declutter($refuri);
                   3808:                     my ($match) = &is_on_map($refuri);
                   3809:                     if ($match) {
                   3810:                         $thisallowed='F';
                   3811:                     }
1.669     raeburn  3812:                 }
1.671     raeburn  3813:             }
                   3814:         }
1.314     www      3815:     }
1.492     albertel 3816: 
1.766     albertel 3817:     if ($priv eq 'bre'
                   3818: 	&& $thisallowed ne 'F' 
                   3819: 	&& $thisallowed ne '2'
                   3820: 	&& &is_portfolio_url($uri)) {
                   3821: 	$thisallowed = &portfolio_access($uri);
                   3822:     }
                   3823:     
1.52      www      3824: # Full access at system, domain or course-wide level? Exit.
1.29      www      3825: 
                   3826:     if ($thisallowed=~/F/) {
                   3827: 	return 'F';
                   3828:     }
                   3829: 
1.52      www      3830: # If this is generating or modifying users, exit with special codes
1.29      www      3831: 
1.643     www      3832:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   3833: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 3834: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      3835: # no author name given, so this just checks on the general right to make a co-author in this domain
                   3836: 	    unless ($auname) { return $thisallowed; }
                   3837: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 3838: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   3839: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   3840: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   3841: 	}
1.52      www      3842: 	return $thisallowed;
                   3843:     }
                   3844: #
1.103     harris41 3845: # Gathered so far: system, domain and course wide privileges
1.52      www      3846: #
                   3847: # Course: See if uri or referer is an individual resource that is part of 
                   3848: # the course
                   3849: 
1.620     albertel 3850:     if ($env{'request.course.id'}) {
1.232     www      3851: 
1.620     albertel 3852:        $courseprivid=$env{'request.course.id'};
                   3853:        if ($env{'request.course.sec'}) {
                   3854:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      3855:        }
                   3856:        $courseprivid=~s/\_/\//;
                   3857:        my $checkreferer=1;
1.232     www      3858:        my ($match,$cond)=&is_on_map($uri);
                   3859:        if ($match) {
                   3860:            $statecond=$cond;
1.620     albertel 3861:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 3862:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3863:                $thisallowed.=$1;
                   3864:                $checkreferer=0;
                   3865:            }
1.29      www      3866:        }
1.83      www      3867:        
1.148     www      3868:        if ($checkreferer) {
1.620     albertel 3869: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      3870:             unless ($refuri) {
1.800     albertel 3871:                 foreach my $key (keys(%env)) {
                   3872: 		    if ($key=~/^httpref\..*\*/) {
                   3873: 			my $pattern=$key;
1.156     www      3874:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      3875:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   3876:                         $pattern=~s/\//\\\//g;
1.152     www      3877:                         if ($orguri=~/$pattern/) {
1.800     albertel 3878: 			    $refuri=$env{$key};
1.148     www      3879:                         }
                   3880:                     }
1.191     harris41 3881:                 }
1.148     www      3882:             }
1.232     www      3883: 
1.148     www      3884:          if ($refuri) { 
1.152     www      3885: 	  $refuri=&declutter($refuri);
1.232     www      3886:           my ($match,$cond)=&is_on_map($refuri);
                   3887:             if ($match) {
                   3888:               my $refstatecond=$cond;
1.620     albertel 3889:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 3890:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3891:                   $thisallowed.=$1;
1.53      www      3892:                   $uri=$refuri;
                   3893:                   $statecond=$refstatecond;
1.52      www      3894:               }
                   3895:           }
1.148     www      3896:         }
1.29      www      3897:        }
1.52      www      3898:    }
1.29      www      3899: 
1.52      www      3900: #
1.103     harris41 3901: # Gathered now: all privileges that could apply, and condition number
1.52      www      3902: # 
                   3903: #
                   3904: # Full or no access?
                   3905: #
1.29      www      3906: 
1.52      www      3907:     if ($thisallowed=~/F/) {
                   3908: 	return 'F';
                   3909:     }
1.29      www      3910: 
1.52      www      3911:     unless ($thisallowed) {
                   3912:         return '';
                   3913:     }
1.29      www      3914: 
1.52      www      3915: # Restrictions exist, deal with them
                   3916: #
                   3917: #   C:according to course preferences
                   3918: #   R:according to resource settings
                   3919: #   L:unless locked
                   3920: #   X:according to user session state
                   3921: #
                   3922: 
                   3923: # Possibly locked functionality, check all courses
1.54      www      3924: # Locks might take effect only after 10 minutes cache expiration for other
                   3925: # courses, and 2 minutes for current course
1.52      www      3926: 
                   3927:     my $envkey;
                   3928:     if ($thisallowed=~/L/) {
1.620     albertel 3929:         foreach $envkey (keys %env) {
1.54      www      3930:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   3931:                my $courseid=$2;
                   3932:                my $roleid=$1.'.'.$2;
1.92      www      3933:                $courseid=~s/^\///;
1.54      www      3934:                my $expiretime=600;
1.620     albertel 3935:                if ($env{'request.role'} eq $roleid) {
1.54      www      3936: 		  $expiretime=120;
                   3937:                }
                   3938: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   3939:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 3940:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 3941: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      3942:                }
1.620     albertel 3943:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   3944:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   3945: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   3946:                        &log($env{'user.domain'},$env{'user.name'},
                   3947:                             $env{'user.home'},
1.57      www      3948:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      3949:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 3950:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      3951: 		       return '';
                   3952:                    }
                   3953:                }
1.620     albertel 3954:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   3955:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   3956: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   3957:                        &log($env{'user.domain'},$env{'user.name'},
                   3958:                             $env{'user.home'},
1.57      www      3959:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      3960:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 3961:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      3962: 		       return '';
                   3963:                    }
                   3964:                }
                   3965: 	   }
1.29      www      3966:        }
1.52      www      3967:     }
                   3968:    
                   3969: #
                   3970: # Rest of the restrictions depend on selected course
                   3971: #
                   3972: 
1.620     albertel 3973:     unless ($env{'request.course.id'}) {
1.766     albertel 3974: 	if ($thisallowed eq 'A') {
                   3975: 	    return 'A';
1.814     raeburn  3976:         } elsif ($thisallowed eq 'B') {
                   3977:             return 'B';
1.766     albertel 3978: 	} else {
                   3979: 	    return '1';
                   3980: 	}
1.52      www      3981:     }
1.29      www      3982: 
1.52      www      3983: #
                   3984: # Now user is definitely in a course
                   3985: #
1.53      www      3986: 
                   3987: 
                   3988: # Course preferences
                   3989: 
                   3990:    if ($thisallowed=~/C/) {
1.620     albertel 3991:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   3992:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   3993:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 3994: 	   =~/\Q$rolecode\E/) {
1.689     albertel 3995: 	   if ($priv ne 'pch') { 
                   3996: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   3997: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   3998: 			$env{'request.course.id'});
                   3999: 	   }
1.237     www      4000:            return '';
                   4001:        }
                   4002: 
1.620     albertel 4003:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 4004: 	   =~/\Q$unamedom\E/) {
1.689     albertel 4005: 	   if ($priv ne 'pch') { 
                   4006: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   4007: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   4008: 			$env{'request.course.id'});
                   4009: 	   }
1.54      www      4010:            return '';
                   4011:        }
1.53      www      4012:    }
                   4013: 
                   4014: # Resource preferences
                   4015: 
                   4016:    if ($thisallowed=~/R/) {
1.620     albertel 4017:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 4018:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 4019: 	   if ($priv ne 'pch') { 
                   4020: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4021: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   4022: 	   }
                   4023: 	   return '';
1.54      www      4024:        }
1.53      www      4025:    }
1.30      www      4026: 
1.246     www      4027: # Restricted by state or randomout?
1.30      www      4028: 
1.52      www      4029:    if ($thisallowed=~/X/) {
1.620     albertel 4030:       if ($env{'acc.randomout'}) {
1.579     albertel 4031: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 4032:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      4033:             return ''; 
                   4034:          }
1.247     www      4035:       }
                   4036:       if (&condval($statecond)) {
1.52      www      4037: 	 return '2';
                   4038:       } else {
                   4039:          return '';
                   4040:       }
                   4041:    }
1.30      www      4042: 
1.766     albertel 4043:     if ($thisallowed eq 'A') {
                   4044: 	return 'A';
1.814     raeburn  4045:     } elsif ($thisallowed eq 'B') {
                   4046:         return 'B';
1.766     albertel 4047:     }
1.52      www      4048:    return 'F';
1.232     www      4049: }
                   4050: 
1.710     albertel 4051: sub split_uri_for_cond {
                   4052:     my $uri=&deversion(&declutter(shift));
                   4053:     my @uriparts=split(/\//,$uri);
                   4054:     my $filename=pop(@uriparts);
                   4055:     my $pathname=join('/',@uriparts);
                   4056:     return ($pathname,$filename);
                   4057: }
1.232     www      4058: # --------------------------------------------------- Is a resource on the map?
                   4059: 
                   4060: sub is_on_map {
1.710     albertel 4061:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 4062:     #Trying to find the conditional for the file
1.620     albertel 4063:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 4064: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      4065:     if ($match) {
1.289     bowersj2 4066: 	return (1,$1);
                   4067:     } else {
1.434     www      4068: 	return (0,0);
1.289     bowersj2 4069:     }
1.12      www      4070: }
                   4071: 
1.427     www      4072: # --------------------------------------------------------- Get symb from alias
                   4073: 
                   4074: sub get_symb_from_alias {
                   4075:     my $symb=shift;
                   4076:     my ($map,$resid,$url)=&decode_symb($symb);
                   4077: # Already is a symb
                   4078:     if ($url) { return $symb; }
                   4079: # Must be an alias
                   4080:     my $aliassymb='';
                   4081:     my %bighash;
1.620     albertel 4082:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      4083:                             &GDBM_READER(),0640)) {
                   4084:         my $rid=$bighash{'mapalias_'.$symb};
                   4085: 	if ($rid) {
                   4086: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 4087: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   4088: 				    $resid,$bighash{'src_'.$rid});
1.427     www      4089: 	}
                   4090:         untie %bighash;
                   4091:     }
                   4092:     return $aliassymb;
                   4093: }
                   4094: 
1.12      www      4095: # ----------------------------------------------------------------- Define Role
                   4096: 
                   4097: sub definerole {
                   4098:   if (allowed('mcr','/')) {
                   4099:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 4100:     foreach my $role (split(':',$sysrole)) {
                   4101: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4102:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   4103:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   4104: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4105:                return "refused:s:$crole&$cqual"; 
                   4106:             }
                   4107:         }
1.191     harris41 4108:     }
1.800     albertel 4109:     foreach my $role (split(':',$domrole)) {
                   4110: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4111:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   4112:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   4113: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      4114:                return "refused:d:$crole&$cqual"; 
                   4115:             }
                   4116:         }
1.191     harris41 4117:     }
1.800     albertel 4118:     foreach my $role (split(':',$courole)) {
                   4119: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4120:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   4121:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   4122: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4123:                return "refused:c:$crole&$cqual"; 
                   4124:             }
                   4125:         }
1.191     harris41 4126:     }
1.620     albertel 4127:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   4128:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4129: 	        "rolesdef_$rolename=".
                   4130:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 4131:     return reply($command,$env{'user.home'});
1.12      www      4132:   } else {
                   4133:     return 'refused';
                   4134:   }
1.105     harris41 4135: }
                   4136: 
                   4137: # ---------------- Make a metadata query against the network of library servers
                   4138: 
                   4139: sub metadata_query {
1.244     matthew  4140:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 4141:     my %rhash;
1.244     matthew  4142:     my @server_list = (defined($server_array) ? @$server_array
                   4143:                                               : keys(%libserv) );
                   4144:     for my $server (@server_list) {
1.118     harris41 4145: 	unless ($custom or $customshow) {
                   4146: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   4147: 	    $rhash{$server}=$reply;
                   4148: 	}
                   4149: 	else {
                   4150: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   4151: 			     &escape($custom).':'.&escape($customshow),
                   4152: 			     $server);
                   4153: 	    $rhash{$server}=$reply;
                   4154: 	}
1.112     harris41 4155:     }
1.118     harris41 4156:     return \%rhash;
1.240     www      4157: }
                   4158: 
                   4159: # ----------------------------------------- Send log queries and wait for reply
                   4160: 
                   4161: sub log_query {
                   4162:     my ($uname,$udom,$query,%filters)=@_;
                   4163:     my $uhome=&homeserver($uname,$udom);
                   4164:     if ($uhome eq 'no_host') { return 'error: no_host'; }
                   4165:     my $uhost=$hostname{$uhome};
1.800     albertel 4166:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      4167:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   4168:                        $uhome);
1.479     albertel 4169:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      4170:     return get_query_reply($queryid);
                   4171: }
                   4172: 
1.818     raeburn  4173: # -------------------------- Update MySQL table for portfolio file
                   4174: 
                   4175: sub update_portfolio_table {
1.821     raeburn  4176:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.818     raeburn  4177:     my $homeserver = &homeserver($uname,$udom);
                   4178:     my $queryid=
1.821     raeburn  4179:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   4180:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  4181:     my $reply = &get_query_reply($queryid);
                   4182:     return $reply;
                   4183: }
                   4184: 
1.508     raeburn  4185: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  4186: 
                   4187: sub fetch_enrollment_query {
1.511     raeburn  4188:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  4189:     my $homeserver;
1.547     raeburn  4190:     my $maxtries = 1;
1.508     raeburn  4191:     if ($context eq 'automated') {
                   4192:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  4193:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  4194:     } else {
                   4195:         $homeserver = &homeserver($cnum,$dom);
                   4196:     }
1.506     raeburn  4197:     my $host=$hostname{$homeserver};
                   4198:     my $cmd = '';
1.800     albertel 4199:     foreach my $affiliate (keys %{$affiliatesref}) {
                   4200:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  4201:     }
                   4202:     $cmd =~ s/%%$//;
                   4203:     $cmd = &escape($cmd);
                   4204:     my $query = 'fetchenrollment';
1.620     albertel 4205:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  4206:     unless ($queryid=~/^\Q$host\E\_/) { 
                   4207:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   4208:         return 'error: '.$queryid;
                   4209:     }
1.506     raeburn  4210:     my $reply = &get_query_reply($queryid);
1.547     raeburn  4211:     my $tries = 1;
                   4212:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4213:         $reply = &get_query_reply($queryid);
                   4214:         $tries ++;
                   4215:     }
1.526     raeburn  4216:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 4217:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  4218:     } else {
1.515     raeburn  4219:         my @responses = split/:/,$reply;
                   4220:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 4221:             foreach my $line (@responses) {
                   4222:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  4223:                 $$replyref{$key} = $value;
                   4224:             }
                   4225:         } else {
1.506     raeburn  4226:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 4227:             foreach my $line (@responses) {
                   4228:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  4229:                 $$replyref{$key} = $value;
                   4230:                 if ($value > 0) {
1.800     albertel 4231:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   4232:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  4233:                         my $destname = $pathname.'/'.$filename;
                   4234:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  4235:                         if ($xml_classlist =~ /^error/) {
                   4236:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   4237:                         } else {
1.506     raeburn  4238:                             if ( open(FILE,">$destname") ) {
                   4239:                                 print FILE &unescape($xml_classlist);
                   4240:                                 close(FILE);
1.526     raeburn  4241:                             } else {
                   4242:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  4243:                             }
                   4244:                         }
                   4245:                     }
                   4246:                 }
                   4247:             }
                   4248:         }
                   4249:         return 'ok';
                   4250:     }
                   4251:     return 'error';
                   4252: }
                   4253: 
1.242     www      4254: sub get_query_reply {
                   4255:     my $queryid=shift;
1.240     www      4256:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   4257:     my $reply='';
                   4258:     for (1..100) {
                   4259: 	sleep 2;
                   4260:         if (-e $replyfile.'.end') {
1.448     albertel 4261: 	    if (open(my $fh,$replyfile)) {
1.240     www      4262:                $reply.=<$fh>;
1.448     albertel 4263:                close($fh);
1.240     www      4264: 	   } else { return 'error: reply_file_error'; }
1.242     www      4265:            return &unescape($reply);
                   4266: 	}
1.240     www      4267:     }
1.242     www      4268:     return 'timeout:'.$queryid;
1.240     www      4269: }
                   4270: 
                   4271: sub courselog_query {
1.241     www      4272: #
                   4273: # possible filters:
                   4274: # url: url or symb
                   4275: # username
                   4276: # domain
                   4277: # action: view, submit, grade
                   4278: # start: timestamp
                   4279: # end: timestamp
                   4280: #
1.240     www      4281:     my (%filters)=@_;
1.620     albertel 4282:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      4283:     if ($filters{'url'}) {
                   4284: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   4285:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   4286:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   4287:     }
1.620     albertel 4288:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4289:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      4290:     return &log_query($cname,$cdom,'courselog',%filters);
                   4291: }
                   4292: 
                   4293: sub userlog_query {
                   4294:     my ($uname,$udom,%filters)=@_;
                   4295:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      4296: }
                   4297: 
1.506     raeburn  4298: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   4299: 
                   4300: sub auto_run {
1.508     raeburn  4301:     my ($cnum,$cdom) = @_;
                   4302:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4303:     my $response = &reply('autorun:'.$cdom,$homeserver);
1.506     raeburn  4304:     return $response;
                   4305: }
1.776     albertel 4306: 
1.506     raeburn  4307: sub auto_get_sections {
1.508     raeburn  4308:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   4309:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  4310:     my @secs = ();
1.511     raeburn  4311:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  4312:     unless ($response eq 'refused') {
                   4313:         @secs = split/:/,$response;
                   4314:     }
                   4315:     return @secs;
                   4316: }
1.776     albertel 4317: 
1.506     raeburn  4318: sub auto_new_course {
1.508     raeburn  4319:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   4320:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  4321:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  4322:     return $response;
                   4323: }
1.776     albertel 4324: 
1.506     raeburn  4325: sub auto_validate_courseID {
1.508     raeburn  4326:     my ($cnum,$cdom,$inst_course_id) = @_;
                   4327:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4328:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  4329:     return $response;
                   4330: }
1.776     albertel 4331: 
1.506     raeburn  4332: sub auto_create_password {
1.508     raeburn  4333:     my ($cnum,$cdom,$authparam) = @_;
                   4334:     my $homeserver = &homeserver($cnum,$cdom); 
1.506     raeburn  4335:     my $create_passwd = 0;
                   4336:     my $authchk = '';
1.511     raeburn  4337:     my $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
1.506     raeburn  4338:     if ($response eq 'refused') {
                   4339:         $authchk = 'refused';
                   4340:     } else {
                   4341:         ($authparam,$create_passwd,$authchk) = split/:/,$response;
                   4342:     }
                   4343:     return ($authparam,$create_passwd,$authchk);
                   4344: }
                   4345: 
1.706     raeburn  4346: sub auto_photo_permission {
                   4347:     my ($cnum,$cdom,$students) = @_;
                   4348:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 4349:     my ($outcome,$perm_reqd,$conditions) = 
                   4350: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 4351:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4352: 	return (undef,undef);
                   4353:     }
1.706     raeburn  4354:     return ($outcome,$perm_reqd,$conditions);
                   4355: }
                   4356: 
                   4357: sub auto_checkphotos {
                   4358:     my ($uname,$udom,$pid) = @_;
                   4359:     my $homeserver = &homeserver($uname,$udom);
                   4360:     my ($result,$resulttype);
                   4361:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 4362: 				   &escape($uname).':'.&escape($pid),
                   4363: 				   $homeserver));
1.709     albertel 4364:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4365: 	return (undef,undef);
                   4366:     }
1.706     raeburn  4367:     if ($outcome) {
                   4368:         ($result,$resulttype) = split(/:/,$outcome);
                   4369:     } 
                   4370:     return ($result,$resulttype);
                   4371: }
                   4372: 
                   4373: sub auto_photochoice {
                   4374:     my ($cnum,$cdom) = @_;
                   4375:     my $homeserver = &homeserver($cnum,$cdom);
                   4376:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 4377: 						       &escape($cdom),
                   4378: 						       $homeserver)));
1.709     albertel 4379:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4380: 	return (undef,undef);
                   4381:     }
1.706     raeburn  4382:     return ($update,$comment);
                   4383: }
                   4384: 
                   4385: sub auto_photoupdate {
                   4386:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   4387:     my $homeserver = &homeserver($cnum,$dom);
                   4388:     my $host=$hostname{$homeserver};
                   4389:     my $cmd = '';
                   4390:     my $maxtries = 1;
1.800     albertel 4391:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   4392:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  4393:     }
                   4394:     $cmd =~ s/%%$//;
                   4395:     $cmd = &escape($cmd);
                   4396:     my $query = 'institutionalphotos';
                   4397:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   4398:     unless ($queryid=~/^\Q$host\E\_/) {
                   4399:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   4400:         return 'error: '.$queryid;
                   4401:     }
                   4402:     my $reply = &get_query_reply($queryid);
                   4403:     my $tries = 1;
                   4404:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4405:         $reply = &get_query_reply($queryid);
                   4406:         $tries ++;
                   4407:     }
                   4408:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   4409:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   4410:     } else {
                   4411:         my @responses = split(/:/,$reply);
                   4412:         my $outcome = shift(@responses); 
                   4413:         foreach my $item (@responses) {
                   4414:             my ($key,$value) = split(/=/,$item);
                   4415:             $$photo{$key} = $value;
                   4416:         }
                   4417:         return $outcome;
                   4418:     }
                   4419:     return 'error';
                   4420: }
                   4421: 
1.521     raeburn  4422: sub auto_instcode_format {
1.793     albertel 4423:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   4424: 	$cat_order) = @_;
1.521     raeburn  4425:     my $courses = '';
1.772     raeburn  4426:     my @homeservers;
1.521     raeburn  4427:     if ($caller eq 'global') {
1.793     albertel 4428:         foreach my $tryserver (keys(%libserv)) {
1.584     raeburn  4429:             if ($hostdom{$tryserver} eq $codedom) {
1.793     albertel 4430:                 if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
1.772     raeburn  4431:                     push(@homeservers,$tryserver);
                   4432:                 }
1.584     raeburn  4433:             }
                   4434:         }
1.521     raeburn  4435:     } else {
1.772     raeburn  4436:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  4437:     }
1.793     albertel 4438:     foreach my $code (keys(%{$instcodes})) {
                   4439:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  4440:     }
                   4441:     chop($courses);
1.772     raeburn  4442:     my $ok_response = 0;
                   4443:     my $response;
                   4444:     while (@homeservers > 0 && $ok_response == 0) {
                   4445:         my $server = shift(@homeservers); 
                   4446:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   4447:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   4448:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.793     albertel 4449: 		split/:/,$response;
1.772     raeburn  4450:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   4451:             push(@{$codetitles},&str2array($codetitles_str));
                   4452:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   4453:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   4454:             $ok_response = 1;
                   4455:         }
                   4456:     }
                   4457:     if ($ok_response) {
1.521     raeburn  4458:         return 'ok';
1.772     raeburn  4459:     } else {
                   4460:         return $response;
1.521     raeburn  4461:     }
                   4462: }
                   4463: 
1.792     raeburn  4464: sub auto_instcode_defaults {
                   4465:     my ($domain,$returnhash,$code_order) = @_;
                   4466:     my @homeservers;
1.793     albertel 4467:     foreach my $tryserver (keys(%libserv)) {
1.792     raeburn  4468:         if ($hostdom{$tryserver} eq $domain) {
1.793     albertel 4469:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
1.792     raeburn  4470:                 push(@homeservers,$tryserver);
                   4471:             }
                   4472:         }
                   4473:     }
                   4474:     my $ok_response = 0;
                   4475:     my $response;
                   4476:     while (@homeservers > 0 && $ok_response == 0) {
                   4477:         my $server = shift(@homeservers);
                   4478:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
                   4479:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
1.793     albertel 4480:             foreach my $pair (split(/\&/,$response)) {
                   4481:                 my ($name,$value)=split(/\=/,$pair);
1.792     raeburn  4482:                 if ($name eq 'code_order') {
1.796     raeburn  4483:                     @{$code_order} = split(/\&/,&unescape($value));
1.792     raeburn  4484:                 } else {
1.796     raeburn  4485:                     $returnhash->{&unescape($name)}=&unescape($value);
1.792     raeburn  4486:                 }
                   4487:             }
1.804     raeburn  4488:             $ok_response = 1;
1.792     raeburn  4489:         }
                   4490:     }
                   4491:     if ($ok_response) {
                   4492:         return 'ok';
                   4493:     } else {
                   4494:         return $response;
                   4495:     }
                   4496: } 
                   4497: 
1.777     albertel 4498: sub auto_validate_class_sec {
1.773     raeburn  4499:     my ($cdom,$cnum,$owner,$inst_class) = @_;
                   4500:     my $homeserver = &homeserver($cnum,$cdom);
                   4501:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.774     banghart 4502:                         &escape($owner).':'.$cdom,$homeserver);
1.773     raeburn  4503:     return $response;
                   4504: }
                   4505: 
1.679     raeburn  4506: # ------------------------------------------------------- Course Group routines
                   4507: 
                   4508: sub get_coursegroups {
1.809     raeburn  4509:     my ($cdom,$cnum,$group,$namespace) = @_;
                   4510:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  4511: }
                   4512: 
1.679     raeburn  4513: sub modify_coursegroup {
                   4514:     my ($cdom,$cnum,$groupsettings) = @_;
                   4515:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   4516: }
                   4517: 
1.809     raeburn  4518: sub toggle_coursegroup_status {
                   4519:     my ($cdom,$cnum,$group,$action) = @_;
                   4520:     my ($from_namespace,$to_namespace);
                   4521:     if ($action eq 'delete') {
                   4522:         $from_namespace = 'coursegroups';
                   4523:         $to_namespace = 'deleted_groups';
                   4524:     } else {
                   4525:         $from_namespace = 'deleted_groups';
                   4526:         $to_namespace = 'coursegroups';
                   4527:     }
                   4528:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  4529:     if (my $tmp = &error(%curr_group)) {
                   4530:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   4531:         return ('read error',$tmp);
                   4532:     } else {
                   4533:         my %savedsettings = %curr_group; 
1.809     raeburn  4534:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  4535:         my $deloutcome;
                   4536:         if ($result eq 'ok') {
1.809     raeburn  4537:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  4538:         } else {
                   4539:             return ('write error',$result);
                   4540:         }
                   4541:         if ($deloutcome eq 'ok') {
                   4542:             return 'ok';
                   4543:         } else {
                   4544:             return ('delete error',$deloutcome);
                   4545:         }
                   4546:     }
                   4547: }
                   4548: 
1.679     raeburn  4549: sub modify_group_roles {
                   4550:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
                   4551:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   4552:     my $role = 'gr/'.&escape($userprivs);
                   4553:     my ($uname,$udom) = split(/:/,$user);
                   4554:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
1.684     raeburn  4555:     if ($result eq 'ok') {
                   4556:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   4557:     }
1.679     raeburn  4558:     return $result;
                   4559: }
                   4560: 
                   4561: sub modify_coursegroup_membership {
                   4562:     my ($cdom,$cnum,$membership) = @_;
                   4563:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   4564:     return $result;
                   4565: }
                   4566: 
1.682     raeburn  4567: sub get_active_groups {
                   4568:     my ($udom,$uname,$cdom,$cnum) = @_;
                   4569:     my $now = time;
                   4570:     my %groups = ();
                   4571:     foreach my $key (keys(%env)) {
1.811     albertel 4572:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  4573:             my ($start,$end) = split(/\./,$env{$key});
                   4574:             if (($end!=0) && ($end<$now)) { next; }
                   4575:             if (($start!=0) && ($start>$now)) { next; }
                   4576:             if ($1 eq $cdom && $2 eq $cnum) {
                   4577:                 $groups{$3} = $env{$key} ;
                   4578:             }
                   4579:         }
                   4580:     }
                   4581:     return %groups;
                   4582: }
                   4583: 
1.683     raeburn  4584: sub get_group_membership {
                   4585:     my ($cdom,$cnum,$group) = @_;
                   4586:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   4587: }
                   4588: 
                   4589: sub get_users_groups {
                   4590:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  4591:     my @usersgroups;
1.683     raeburn  4592:     my $cachetime=1800;
                   4593: 
                   4594:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  4595:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   4596:     if (defined($cached)) {
1.734     albertel 4597:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  4598:     } else {  
                   4599:         $grouplist = '';
1.816     raeburn  4600:         my $courseurl = &courseid_to_courseurl($courseid);
                   4601:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  4602:         my $access_end = $env{'course.'.$courseid.
                   4603:                               '.default_enrollment_end_date'};
                   4604:         my $now = time;
                   4605:         foreach my $key (keys(%roleshash)) {
                   4606:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   4607:                 my $group = $1;
                   4608:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   4609:                     my $start = $2;
                   4610:                     my $end = $1;
                   4611:                     if ($start == -1) { next; } # deleted from group
                   4612:                     if (($start!=0) && ($start>$now)) { next; }
                   4613:                     if (($end!=0) && ($end<$now)) {
                   4614:                         if ($access_end && $access_end < $now) {
                   4615:                             if ($access_end - $end < 86400) {
                   4616:                                 push(@usersgroups,$group);
1.733     raeburn  4617:                             }
                   4618:                         }
1.817     raeburn  4619:                         next;
1.733     raeburn  4620:                     }
1.817     raeburn  4621:                     push(@usersgroups,$group);
1.683     raeburn  4622:                 }
                   4623:             }
                   4624:         }
1.817     raeburn  4625:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   4626:         $grouplist = join(':',@usersgroups);
                   4627:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  4628:     }
1.733     raeburn  4629:     return @usersgroups;
1.683     raeburn  4630: }
                   4631: 
                   4632: sub devalidate_getgroups_cache {
                   4633:     my ($udom,$uname,$cdom,$cnum)=@_;
                   4634:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 4635: 
1.683     raeburn  4636:     my $hashid="$udom:$uname:$courseid";
                   4637:     &devalidate_cache_new('getgroups',$hashid);
                   4638: }
                   4639: 
1.12      www      4640: # ------------------------------------------------------------------ Plain Text
                   4641: 
                   4642: sub plaintext {
1.742     raeburn  4643:     my ($short,$type,$cid) = @_;
1.758     albertel 4644:     if ($short =~ /^cr/) {
                   4645: 	return (split('/',$short))[-1];
                   4646:     }
1.742     raeburn  4647:     if (!defined($cid)) {
                   4648:         $cid = $env{'request.course.id'};
                   4649:     }
                   4650:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
                   4651:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
                   4652:                                           '.plaintext'});
                   4653:     }
                   4654:     my %rolenames = (
                   4655:                       Course => 'std',
                   4656:                       Group => 'alt1',
                   4657:                     );
                   4658:     if (defined($type) && 
                   4659:          defined($rolenames{$type}) && 
                   4660:          defined($prp{$short}{$rolenames{$type}})) {
                   4661:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   4662:     } else {
                   4663:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   4664:     }
1.12      www      4665: }
                   4666: 
                   4667: # ----------------------------------------------------------------- Assign Role
                   4668: 
                   4669: sub assignrole {
1.357     www      4670:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
1.21      www      4671:     my $mrole;
                   4672:     if ($role =~ /^cr\//) {
1.393     www      4673:         my $cwosec=$url;
1.811     albertel 4674:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      4675: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      4676:            &logthis('Refused custom assignrole: '.
                   4677:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4678: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4679:            return 'refused'; 
                   4680:         }
1.21      www      4681:         $mrole='cr';
1.678     raeburn  4682:     } elsif ($role =~ /^gr\//) {
                   4683:         my $cwogrp=$url;
1.811     albertel 4684:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  4685:         unless (&allowed('mdg',$cwogrp)) {
                   4686:             &logthis('Refused group assignrole: '.
                   4687:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   4688:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   4689:             return 'refused';
                   4690:         }
                   4691:         $mrole='gr';
1.21      www      4692:     } else {
1.82      www      4693:         my $cwosec=$url;
1.811     albertel 4694:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.373     www      4695:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
1.104     www      4696:            &logthis('Refused assignrole: '.
                   4697:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4698: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4699:            return 'refused'; 
                   4700:         }
1.21      www      4701:         $mrole=$role;
                   4702:     }
1.620     albertel 4703:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4704:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      4705:     if ($end) { $command.='_'.$end; }
1.21      www      4706:     if ($start) {
                   4707: 	if ($end) { 
1.81      www      4708:            $command.='_'.$start; 
1.21      www      4709:         } else {
1.81      www      4710:            $command.='_0_'.$start;
1.21      www      4711:         }
                   4712:     }
1.739     raeburn  4713:     my $origstart = $start;
                   4714:     my $origend = $end;
1.357     www      4715: # actually delete
                   4716:     if ($deleteflag) {
1.373     www      4717: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      4718: # modify command to delete the role
1.620     albertel 4719:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      4720:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 4721: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      4722: # set start and finish to negative values for userrolelog
                   4723:            $start=-1;
                   4724:            $end=-1;
                   4725:         }
                   4726:     }
                   4727: # send command
1.349     www      4728:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      4729: # log new user role if status is ok
1.349     www      4730:     if ($answer eq 'ok') {
1.663     raeburn  4731: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  4732: # for course roles, perform group memberships changes triggered by role change.
                   4733:         unless ($role =~ /^gr/) {
                   4734:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   4735:                                              $origstart);
                   4736:         }
1.349     www      4737:     }
                   4738:     return $answer;
1.169     harris41 4739: }
                   4740: 
                   4741: # -------------------------------------------------- Modify user authentication
1.197     www      4742: # Overrides without validation
                   4743: 
1.169     harris41 4744: sub modifyuserauth {
                   4745:     my ($udom,$uname,$umode,$upass)=@_;
                   4746:     my $uhome=&homeserver($uname,$udom);
1.197     www      4747:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   4748:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 4749:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4750:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 4751:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   4752: 		     &escape($upass),$uhome);
1.620     albertel 4753:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      4754:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   4755:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   4756:     &log($udom,,$uname,$uhome,
1.620     albertel 4757:         'Authentication changed by '.$env{'user.domain'}.', '.
                   4758:                                      $env{'user.name'}.', '.$umode.
1.197     www      4759:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 4760:     unless ($reply eq 'ok') {
1.197     www      4761:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 4762: 	return 'error: '.$reply;
                   4763:     }   
1.170     harris41 4764:     return 'ok';
1.80      www      4765: }
                   4766: 
1.81      www      4767: # --------------------------------------------------------------- Modify a user
1.80      www      4768: 
1.81      www      4769: sub modifyuser {
1.206     matthew  4770:     my ($udom,    $uname, $uid,
                   4771:         $umode,   $upass, $first,
                   4772:         $middle,  $last,  $gene,
1.387     www      4773:         $forceid, $desiredhome, $email)=@_;
1.807     albertel 4774:     $udom= &LONCAPA::clean_domain($udom);
                   4775:     $uname=&LONCAPA::clean_username($uname);
1.81      www      4776:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4777:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  4778: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   4779:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   4780:                                      ' desiredhome not specified'). 
1.620     albertel 4781:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4782:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 4783:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      4784: # ----------------------------------------------------------------- Create User
1.406     albertel 4785:     if (($uhome eq 'no_host') && 
                   4786: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      4787:         my $unhome='';
1.209     matthew  4788:         if (defined($desiredhome) && $hostdom{$desiredhome} eq $udom) { 
                   4789:             $unhome = $desiredhome;
1.620     albertel 4790: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   4791: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  4792:         } else { # load balancing routine for determining $unhome
1.80      www      4793:             my $tryserver;
1.81      www      4794:             my $loadm=10000000;
1.80      www      4795:             foreach $tryserver (keys %libserv) {
                   4796: 	       if ($hostdom{$tryserver} eq $udom) {
                   4797:                   my $answer=reply('load',$tryserver);
                   4798:                   if (($answer=~/\d+/) && ($answer<$loadm)) {
                   4799: 		      $loadm=$answer;
                   4800:                       $unhome=$tryserver;
                   4801:                   }
                   4802: 	       }
                   4803: 	    }
                   4804:         }
                   4805:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  4806: 	    return 'error: unable to find a home server for '.$uname.
                   4807:                    ' in domain '.$udom;
1.80      www      4808:         }
                   4809:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   4810:                          &escape($upass),$unhome);
                   4811: 	unless ($reply eq 'ok') {
                   4812:             return 'error: '.$reply;
                   4813:         }   
1.230     stredwic 4814:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      4815:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  4816: 	    return 'error: unable verify users home machine.';
1.80      www      4817:         }
1.209     matthew  4818:     }   # End of creation of new user
1.80      www      4819: # ---------------------------------------------------------------------- Add ID
                   4820:     if ($uid) {
                   4821:        $uid=~tr/A-Z/a-z/;
                   4822:        my %uidhash=&idrget($udom,$uname);
1.196     www      4823:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   4824:          && (!$forceid)) {
1.80      www      4825: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  4826: 	      return 'error: user id "'.$uid.'" does not match '.
                   4827:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      4828:           }
                   4829:        } else {
                   4830: 	  &idput($udom,($uname => $uid));
                   4831:        }
                   4832:     }
                   4833: # -------------------------------------------------------------- Add names, etc
1.313     matthew  4834:     my @tmp=&get('environment',
1.134     albertel 4835: 		   ['firstname','middlename','lastname','generation'],
                   4836: 		   $udom,$uname);
1.313     matthew  4837:     my %names;
                   4838:     if ($tmp[0] =~ m/^error:.*/) { 
                   4839:         %names=(); 
                   4840:     } else {
                   4841:         %names = @tmp;
                   4842:     }
1.388     www      4843: #
                   4844: # Make sure to not trash student environment if instructor does not bother
                   4845: # to supply name and email information
                   4846: #
                   4847:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  4848:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      4849:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  4850:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      4851:     if ($email) {
                   4852:        $email=~s/[^\w\@\.\-\,]//gs;
                   4853:        if ($email=~/\@/) { $names{'notification'} = $email;
                   4854: 			   $names{'critnotification'} = $email;
                   4855: 			   $names{'permanentemail'} = $email; }
                   4856:     }
1.134     albertel 4857:     my $reply = &put('environment', \%names, $udom,$uname);
                   4858:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.680     www      4859:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.81      www      4860:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4861:              $umode.', '.$first.', '.$middle.', '.
                   4862: 	     $last.', '.$gene.' by '.
1.620     albertel 4863:              $env{'user.name'}.' at '.$env{'user.domain'});
1.134     albertel 4864:     return 'ok';
1.80      www      4865: }
                   4866: 
1.81      www      4867: # -------------------------------------------------------------- Modify student
1.80      www      4868: 
1.81      www      4869: sub modifystudent {
                   4870:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.515     raeburn  4871:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
1.455     albertel 4872:     if (!$cid) {
1.620     albertel 4873: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 4874: 	    return 'not_in_class';
                   4875: 	}
1.80      www      4876:     }
                   4877: # --------------------------------------------------------------- Make the user
1.81      www      4878:     my $reply=&modifyuser
1.209     matthew  4879: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      4880:          $desiredhome,$email);
1.80      www      4881:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  4882:     # This will cause &modify_student_enrollment to get the uid from the
                   4883:     # students environment
                   4884:     $uid = undef if (!$forceid);
1.455     albertel 4885:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.515     raeburn  4886: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
1.297     matthew  4887:     return $reply;
                   4888: }
                   4889: 
                   4890: sub modify_student_enrollment {
1.515     raeburn  4891:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
1.455     albertel 4892:     my ($cdom,$cnum,$chome);
                   4893:     if (!$cid) {
1.620     albertel 4894: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 4895: 	    return 'not_in_class';
                   4896: 	}
1.620     albertel 4897: 	$cdom=$env{'course.'.$cid.'.domain'};
                   4898: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 4899:     } else {
                   4900: 	($cdom,$cnum)=split(/_/,$cid);
                   4901:     }
1.620     albertel 4902:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 4903:     if (!$chome) {
1.457     raeburn  4904: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  4905:     }
1.455     albertel 4906:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  4907:     # Make sure the user exists
1.81      www      4908:     my $uhome=&homeserver($uname,$udom);
                   4909:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   4910: 	return 'error: no such user';
                   4911:     }
1.297     matthew  4912:     # Get student data if we were not given enough information
                   4913:     if (!defined($first)  || $first  eq '' || 
                   4914:         !defined($last)   || $last   eq '' || 
                   4915:         !defined($uid)    || $uid    eq '' || 
                   4916:         !defined($middle) || $middle eq '' || 
                   4917:         !defined($gene)   || $gene   eq '') {
1.294     matthew  4918:         # They did not supply us with enough data to enroll the student, so
                   4919:         # we need to pick up more information.
1.297     matthew  4920:         my %tmp = &get('environment',
1.294     matthew  4921:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  4922:                        ,$udom,$uname);
                   4923: 
1.800     albertel 4924:         #foreach my $key (keys(%tmp)) {
                   4925:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 4926:         #}
1.294     matthew  4927:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   4928:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   4929:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  4930:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  4931:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   4932:     }
1.556     albertel 4933:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 4934:     my $reply=cput('classlist',
                   4935: 		   {"$uname:$udom" => 
1.515     raeburn  4936: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 4937: 		   $cdom,$cnum);
1.81      www      4938:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   4939: 	return 'error: '.$reply;
1.652     albertel 4940:     } else {
                   4941: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      4942:     }
1.297     matthew  4943:     # Add student role to user
1.83      www      4944:     my $uurl='/'.$cid;
1.81      www      4945:     $uurl=~s/\_/\//g;
                   4946:     if ($usec) {
                   4947: 	$uurl.='/'.$usec;
                   4948:     }
                   4949:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21      www      4950: }
                   4951: 
1.556     albertel 4952: sub format_name {
                   4953:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   4954:     my $name;
                   4955:     if ($first ne 'lastname') {
                   4956: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   4957:     } else {
                   4958: 	if ($lastname=~/\S/) {
                   4959: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   4960: 	    $name=~s/\s+,/,/;
                   4961: 	} else {
                   4962: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   4963: 	}
                   4964:     }
                   4965:     $name=~s/^\s+//;
                   4966:     $name=~s/\s+$//;
                   4967:     $name=~s/\s+/ /g;
                   4968:     return $name;
                   4969: }
                   4970: 
1.84      www      4971: # ------------------------------------------------- Write to course preferences
                   4972: 
                   4973: sub writecoursepref {
                   4974:     my ($courseid,%prefs)=@_;
                   4975:     $courseid=~s/^\///;
                   4976:     $courseid=~s/\_/\//g;
                   4977:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   4978:     my $chome=homeserver($cnum,$cdomain);
                   4979:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   4980: 	return 'error: no such course';
                   4981:     }
                   4982:     my $cstring='';
1.800     albertel 4983:     foreach my $pref (keys(%prefs)) {
                   4984: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 4985:     }
1.84      www      4986:     $cstring=~s/\&$//;
                   4987:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   4988: }
                   4989: 
                   4990: # ---------------------------------------------------------- Make/modify course
                   4991: 
                   4992: sub createcourse {
1.741     raeburn  4993:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
                   4994:         $course_owner,$crstype)=@_;
1.84      www      4995:     $url=&declutter($url);
                   4996:     my $cid='';
1.264     matthew  4997:     unless (&allowed('ccc',$udom)) {
1.84      www      4998:         return 'refused';
                   4999:     }
                   5000: # ------------------------------------------------------------------- Create ID
1.674     www      5001:    my $uname=int(1+rand(9)).
                   5002:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   5003:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      5004:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   5005: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 5006:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      5007:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5008:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   5009:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 5010:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      5011:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5012:            return 'error: unable to generate unique course-ID';
                   5013:        } 
                   5014:    }
1.264     matthew  5015: # ------------------------------------------------ Check supplied server name
1.620     albertel 5016:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.264     matthew  5017:     if (! exists($libserv{$course_server})) {
                   5018:         return 'error:bad server name '.$course_server;
                   5019:     }
1.84      www      5020: # ------------------------------------------------------------- Make the course
                   5021:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  5022:                       $course_server);
1.84      www      5023:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 5024:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      5025:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5026: 	return 'error: no such course';
                   5027:     }
1.271     www      5028: # ----------------------------------------------------------------- Course made
1.516     raeburn  5029: # log existence
                   5030:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
1.741     raeburn  5031:                  ':'.&escape($inst_code).':'.&escape($course_owner).':'.
                   5032:                   &escape($crstype),$uhome);
1.358     www      5033:     &flushcourselogs();
                   5034: # set toplevel url
1.271     www      5035:     my $topurl=$url;
                   5036:     unless ($nonstandard) {
                   5037: # ------------------------------------------ For standard courses, make top url
                   5038:         my $mapurl=&clutter($url);
1.278     www      5039:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 5040:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      5041: <map>
                   5042: <resource id="1" type="start"></resource>
                   5043: <resource id="2" src="$mapurl"></resource>
                   5044: <resource id="3" type="finish"></resource>
                   5045: <link index="1" from="1" to="2"></link>
                   5046: <link index="2" from="2" to="3"></link>
                   5047: </map>
                   5048: ENDINITMAP
                   5049:         $topurl=&declutter(
1.638     albertel 5050:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      5051:                           );
                   5052:     }
                   5053: # ----------------------------------------------------------- Write preferences
1.84      www      5054:     &writecoursepref($udom.'_'.$uname,
                   5055:                      ('description' => $description,
1.271     www      5056:                       'url'         => $topurl));
1.84      www      5057:     return '/'.$udom.'/'.$uname;
                   5058: }
                   5059: 
1.813     albertel 5060: sub is_course {
                   5061:     my ($cdom,$cnum) = @_;
                   5062:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
                   5063: 				undef,'.');
                   5064:     if (exists($courses{$cdom.'_'.$cnum})) {
                   5065:         return 1;
                   5066:     }
                   5067:     return 0;
                   5068: }
                   5069: 
1.21      www      5070: # ---------------------------------------------------------- Assign Custom Role
                   5071: 
                   5072: sub assigncustomrole {
1.357     www      5073:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21      www      5074:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357     www      5075:                        $end,$start,$deleteflag);
1.21      www      5076: }
                   5077: 
                   5078: # ----------------------------------------------------------------- Revoke Role
                   5079: 
                   5080: sub revokerole {
1.357     www      5081:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21      www      5082:     my $now=time;
1.357     www      5083:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21      www      5084: }
                   5085: 
                   5086: # ---------------------------------------------------------- Revoke Custom Role
                   5087: 
                   5088: sub revokecustomrole {
1.357     www      5089:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21      www      5090:     my $now=time;
1.357     www      5091:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
                   5092:            $deleteflag);
1.17      www      5093: }
                   5094: 
1.533     banghart 5095: # ------------------------------------------------------------ Disk usage
1.535     albertel 5096: sub diskusage {
1.533     banghart 5097:     my ($udom,$uname,$directoryRoot)=@_;
                   5098:     $directoryRoot =~ s/\/$//;
1.535     albertel 5099:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
1.514     albertel 5100:     return $listing;
1.512     banghart 5101: }
                   5102: 
1.566     banghart 5103: sub is_locked {
                   5104:     my ($file_name, $domain, $user) = @_;
                   5105:     my @check;
                   5106:     my $is_locked;
                   5107:     push @check, $file_name;
1.613     albertel 5108:     my %locked = &get('file_permissions',\@check,
1.620     albertel 5109: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 5110:     my ($tmp)=keys(%locked);
                   5111:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  5112:     
1.566     banghart 5113:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  5114:         $is_locked = 'false';
                   5115:         foreach my $entry (@{$locked{$file_name}}) {
                   5116:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  5117:                $is_locked = 'true';
                   5118:                last;
1.745     raeburn  5119:            }
                   5120:        }
1.566     banghart 5121:     } else {
                   5122:         $is_locked = 'false';
                   5123:     }
                   5124: }
                   5125: 
1.759     albertel 5126: sub declutter_portfile {
                   5127:     my ($file) = @_;
                   5128:     &logthis("got $file");
                   5129:     $file =~ s-^(/portfolio/|portfolio/)-/-;
                   5130:     &logthis("ret $file");
                   5131:     return $file;
                   5132: }
                   5133: 
1.559     banghart 5134: # ------------------------------------------------------------- Mark as Read Only
                   5135: 
                   5136: sub mark_as_readonly {
                   5137:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 5138:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5139:     my ($tmp)=keys(%current_permissions);
                   5140:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 5141:     foreach my $file (@{$files}) {
1.759     albertel 5142: 	$file = &declutter_portfile($file);
1.561     banghart 5143:         push(@{$current_permissions{$file}},$what);
1.559     banghart 5144:     }
1.613     albertel 5145:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5146:     return;
                   5147: }
                   5148: 
1.572     banghart 5149: # ------------------------------------------------------------Save Selected Files
                   5150: 
                   5151: sub save_selected_files {
                   5152:     my ($user, $path, @files) = @_;
                   5153:     my $filename = $user."savedfiles";
1.573     banghart 5154:     my @other_files = &files_not_in_path($user, $path);
1.574     banghart 5155:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 5156:     foreach my $file (@files) {
1.620     albertel 5157:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 5158:     }
                   5159:     foreach my $file (@other_files) {
1.574     banghart 5160:         print (OUT $file."\n");
1.572     banghart 5161:     }
1.574     banghart 5162:     close (OUT);
1.572     banghart 5163:     return 'ok';
                   5164: }
                   5165: 
1.574     banghart 5166: sub clear_selected_files {
                   5167:     my ($user) = @_;
                   5168:     my $filename = $user."savedfiles";
                   5169:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5170:     print (OUT undef);
                   5171:     close (OUT);
                   5172:     return ("ok");    
                   5173: }
                   5174: 
1.572     banghart 5175: sub files_in_path {
                   5176:     my ($user, $path) = @_;
                   5177:     my $filename = $user."savedfiles";
                   5178:     my %return_files;
1.574     banghart 5179:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 5180:     while (my $line_in = <IN>) {
1.574     banghart 5181:         chomp ($line_in);
                   5182:         my @paths_and_file = split (m!/!, $line_in);
                   5183:         my $file_part = pop (@paths_and_file);
                   5184:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 5185:         $path_part.='/';
                   5186:         my $path_and_file = $path_part.$file_part;
                   5187:         if ($path_part eq $path) {
                   5188:             $return_files{$file_part}= 'selected';
                   5189:         }
                   5190:     }
1.574     banghart 5191:     close (IN);
                   5192:     return (\%return_files);
1.572     banghart 5193: }
                   5194: 
                   5195: # called in portfolio select mode, to show files selected NOT in current directory
                   5196: sub files_not_in_path {
                   5197:     my ($user, $path) = @_;
                   5198:     my $filename = $user."savedfiles";
                   5199:     my @return_files;
                   5200:     my $path_part;
1.800     albertel 5201:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5202:     while (my $line = <IN>) {
1.572     banghart 5203:         #ok, I know it's clunky, but I want it to work
1.800     albertel 5204:         my @paths_and_file = split(m|/|, $line);
                   5205:         my $file_part = pop(@paths_and_file);
                   5206:         chomp($file_part);
                   5207:         my $path_part = join('/', @paths_and_file);
1.572     banghart 5208:         $path_part .= '/';
                   5209:         my $path_and_file = $path_part.$file_part;
                   5210:         if ($path_part ne $path) {
1.800     albertel 5211:             push(@return_files, ($path_and_file));
1.572     banghart 5212:         }
                   5213:     }
1.800     albertel 5214:     close(OUT);
1.574     banghart 5215:     return (@return_files);
1.572     banghart 5216: }
                   5217: 
1.745     raeburn  5218: #----------------------------------------------Get portfolio file permissions
1.629     banghart 5219: 
1.745     raeburn  5220: sub get_portfile_permissions {
                   5221:     my ($domain,$user) = @_;
1.613     albertel 5222:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5223:     my ($tmp)=keys(%current_permissions);
                   5224:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5225:     return \%current_permissions;
                   5226: }
                   5227: 
                   5228: #---------------------------------------------Get portfolio file access controls
                   5229: 
1.749     raeburn  5230: sub get_access_controls {
1.745     raeburn  5231:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 5232:     my %access;
                   5233:     my $real_file = $file;
                   5234:     $file =~ s/\.meta$//;
1.745     raeburn  5235:     if (defined($file)) {
1.749     raeburn  5236:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   5237:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 5238:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  5239:             }
                   5240:         }
1.745     raeburn  5241:     } else {
1.749     raeburn  5242:         foreach my $key (keys(%{$current_permissions})) {
                   5243:             if ($key =~ /\0accesscontrol$/) {
                   5244:                 if (defined($group)) {
                   5245:                     if ($key !~ m-^\Q$group\E/-) {
                   5246:                         next;
                   5247:                     }
                   5248:                 }
                   5249:                 my ($fullpath) = split(/\0/,$key);
                   5250:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   5251:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   5252:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   5253:                     }
                   5254:                 }
                   5255:             }
                   5256:         }
                   5257:     }
                   5258:     return %access;
                   5259: }
                   5260: 
                   5261: sub modify_access_controls {
                   5262:     my ($file_name,$changes,$domain,$user)=@_;
                   5263:     my ($outcome,$deloutcome);
                   5264:     my %store_permissions;
                   5265:     my %new_values;
                   5266:     my %new_control;
                   5267:     my %translation;
                   5268:     my @deletions = ();
                   5269:     my $now = time;
                   5270:     if (exists($$changes{'activate'})) {
                   5271:         if (ref($$changes{'activate'}) eq 'HASH') {
                   5272:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   5273:             my $numnew = scalar(@newitems);
                   5274:             for (my $i=0; $i<$numnew; $i++) {
                   5275:                 my $newkey = $newitems[$i];
                   5276:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  5277:                 if ($newkey =~ /^\d+:/) { 
                   5278:                     $newkey =~ s/^(\d+)/$newid/;
                   5279:                     $translation{$1} = $newid;
                   5280:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   5281:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   5282:                     $translation{$1} = $newid;
                   5283:                 }
1.749     raeburn  5284:                 $new_values{$file_name."\0".$newkey} = 
                   5285:                                           $$changes{'activate'}{$newitems[$i]};
                   5286:                 $new_control{$newkey} = $now;
                   5287:             }
                   5288:         }
                   5289:     }
                   5290:     my %todelete;
                   5291:     my %changed_items;
                   5292:     foreach my $action ('delete','update') {
                   5293:         if (exists($$changes{$action})) {
                   5294:             if (ref($$changes{$action}) eq 'HASH') {
                   5295:                 foreach my $key (keys(%{$$changes{$action}})) {
                   5296:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   5297:                     if ($action eq 'delete') { 
                   5298:                         $todelete{$itemnum} = 1;
                   5299:                     } else {
                   5300:                         $changed_items{$itemnum} = $key;
                   5301:                     }
                   5302:                 }
1.745     raeburn  5303:             }
                   5304:         }
1.749     raeburn  5305:     }
                   5306:     # get lock on access controls for file.
                   5307:     my $lockhash = {
                   5308:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   5309:                                                        ':'.$env{'user.domain'},
                   5310:                    }; 
                   5311:     my $tries = 0;
                   5312:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5313:    
                   5314:     while (($gotlock ne 'ok') && $tries <3) {
                   5315:         $tries ++;
                   5316:         sleep 1;
                   5317:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5318:     }
                   5319:     if ($gotlock eq 'ok') {
                   5320:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   5321:         my ($tmp)=keys(%curr_permissions);
                   5322:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   5323:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   5324:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   5325:             if (ref($curr_controls) eq 'HASH') {
                   5326:                 foreach my $control_item (keys(%{$curr_controls})) {
                   5327:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   5328:                     if (defined($todelete{$itemnum})) {
                   5329:                         push(@deletions,$file_name."\0".$control_item);
                   5330:                     } else {
                   5331:                         if (defined($changed_items{$itemnum})) {
                   5332:                             $new_control{$changed_items{$itemnum}} = $now;
                   5333:                             push(@deletions,$file_name."\0".$control_item);
                   5334:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   5335:                         } else {
                   5336:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   5337:                         }
                   5338:                     }
1.745     raeburn  5339:                 }
                   5340:             }
                   5341:         }
1.749     raeburn  5342:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   5343:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   5344:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   5345:         #  remove lock
                   5346:         my @del_lock = ($file_name."\0".'locked_access_records');
                   5347:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  5348:         my ($file,$group);
                   5349:         if (&is_course($domain,$user)) {
                   5350:             ($group,$file) = split(/\//,$file_name,2);
                   5351:         } else {
                   5352:             $file = $file_name;
                   5353:         }
                   5354:         my $sqlresult =
                   5355:             &update_portfolio_table($user,$domain,$file,'portfolio_access',
                   5356:                                     $group);
1.749     raeburn  5357:     } else {
                   5358:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  5359:     }
1.749     raeburn  5360:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  5361: }
                   5362: 
                   5363: #------------------------------------------------------Get Marked as Read Only
                   5364: 
                   5365: sub get_marked_as_readonly {
                   5366:     my ($domain,$user,$what,$group) = @_;
                   5367:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 5368:     my @readonly_files;
1.629     banghart 5369:     my $cmp1=$what;
                   5370:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  5371:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5372:         if (defined($group)) {
                   5373:             if ($file_name !~ m-^\Q$group\E/-) {
                   5374:                 next;
                   5375:             }
                   5376:         }
1.561     banghart 5377:         if (ref($value) eq "ARRAY"){
                   5378:             foreach my $stored_what (@{$value}) {
1.629     banghart 5379:                 my $cmp2=$stored_what;
1.759     albertel 5380:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  5381:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  5382:                 }
1.629     banghart 5383:                 if ($cmp1 eq $cmp2) {
1.561     banghart 5384:                     push(@readonly_files, $file_name);
1.745     raeburn  5385:                     last;
1.563     banghart 5386:                 } elsif (!defined($what)) {
                   5387:                     push(@readonly_files, $file_name);
1.745     raeburn  5388:                     last;
1.561     banghart 5389:                 }
                   5390:             }
1.745     raeburn  5391:         }
1.561     banghart 5392:     }
                   5393:     return @readonly_files;
                   5394: }
1.577     banghart 5395: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 5396: 
1.577     banghart 5397: sub get_marked_as_readonly_hash {
1.745     raeburn  5398:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 5399:     my %readonly_files;
1.745     raeburn  5400:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5401:         if (defined($group)) {
                   5402:             if ($file_name !~ m-^\Q$group\E/-) {
                   5403:                 next;
                   5404:             }
                   5405:         }
1.577     banghart 5406:         if (ref($value) eq "ARRAY"){
                   5407:             foreach my $stored_what (@{$value}) {
1.745     raeburn  5408:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 5409:                     foreach my $lock_descriptor(@{$stored_what}) {
                   5410:                         if ($lock_descriptor eq 'graded') {
                   5411:                             $readonly_files{$file_name} = 'graded';
                   5412:                         } elsif ($lock_descriptor eq 'handback') {
                   5413:                             $readonly_files{$file_name} = 'handback';
                   5414:                         } else {
                   5415:                             if (!exists($readonly_files{$file_name})) {
                   5416:                                 $readonly_files{$file_name} = 'locked';
                   5417:                             }
                   5418:                         }
1.745     raeburn  5419:                     }
1.750     banghart 5420:                 } 
1.577     banghart 5421:             }
                   5422:         } 
                   5423:     }
                   5424:     return %readonly_files;
                   5425: }
1.559     banghart 5426: # ------------------------------------------------------------ Unmark as Read Only
                   5427: 
                   5428: sub unmark_as_readonly {
1.629     banghart 5429:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   5430:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  5431:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 5432:     $file_name = &declutter_portfile($file_name);
1.634     albertel 5433:     my $symb_crs = $what;
                   5434:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  5435:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 5436:     my ($tmp)=keys(%current_permissions);
                   5437:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5438:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 5439:     foreach my $file (@readonly_files) {
1.759     albertel 5440: 	my $clean_file = &declutter_portfile($file);
                   5441: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 5442: 	my $current_locks = $current_permissions{$file};
1.563     banghart 5443:         my @new_locks;
                   5444:         my @del_keys;
                   5445:         if (ref($current_locks) eq "ARRAY"){
                   5446:             foreach my $locker (@{$current_locks}) {
1.632     albertel 5447:                 my $compare=$locker;
1.749     raeburn  5448:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  5449:                     $compare=join('',@{$locker});
1.746     raeburn  5450:                     if ($compare ne $symb_crs) {
                   5451:                         push(@new_locks, $locker);
                   5452:                     }
1.563     banghart 5453:                 }
                   5454:             }
1.650     albertel 5455:             if (scalar(@new_locks) > 0) {
1.563     banghart 5456:                 $current_permissions{$file} = \@new_locks;
                   5457:             } else {
                   5458:                 push(@del_keys, $file);
1.613     albertel 5459:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 5460:                 delete($current_permissions{$file});
1.563     banghart 5461:             }
                   5462:         }
1.561     banghart 5463:     }
1.613     albertel 5464:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5465:     return;
                   5466: }
1.512     banghart 5467: 
1.17      www      5468: # ------------------------------------------------------------ Directory lister
                   5469: 
                   5470: sub dirlist {
1.253     stredwic 5471:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
                   5472: 
1.18      www      5473:     $uri=~s/^\///;
                   5474:     $uri=~s/\/$//;
1.253     stredwic 5475:     my ($udom, $uname);
                   5476:     (undef,$udom,$uname)=split(/\//,$uri);
                   5477:     if(defined($userdomain)) {
                   5478:         $udom = $userdomain;
                   5479:     }
                   5480:     if(defined($username)) {
                   5481:         $uname = $username;
                   5482:     }
                   5483: 
                   5484:     my $dirRoot = $perlvar{'lonDocRoot'};
                   5485:     if(defined($alternateDirectoryRoot)) {
                   5486:         $dirRoot = $alternateDirectoryRoot;
                   5487:         $dirRoot =~ s/\/$//;
1.751     banghart 5488:     }
1.253     stredwic 5489: 
                   5490:     if($udom) {
                   5491:         if($uname) {
1.800     albertel 5492:             my $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   5493: 				 &homeserver($uname,$udom));
1.605     matthew  5494:             my @listing_results;
                   5495:             if ($listing eq 'unknown_cmd') {
1.800     albertel 5496:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   5497: 				  &homeserver($uname,$udom));
1.605     matthew  5498:                 @listing_results = split(/:/,$listing);
                   5499:             } else {
                   5500:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   5501:             }
                   5502:             return @listing_results;
1.253     stredwic 5503:         } elsif(!defined($alternateDirectoryRoot)) {
1.800     albertel 5504:             my %allusers;
                   5505:             foreach my $tryserver (keys(%libserv)) {
1.253     stredwic 5506:                 if($hostdom{$tryserver} eq $udom) {
1.800     albertel 5507:                     my $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   5508: 					 $udom, $tryserver);
1.605     matthew  5509:                     my @listing_results;
                   5510:                     if ($listing eq 'unknown_cmd') {
1.800     albertel 5511:                         $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   5512: 					  $udom, $tryserver);
1.605     matthew  5513:                         @listing_results = split(/:/,$listing);
                   5514:                     } else {
                   5515:                         @listing_results =
                   5516:                             map { &unescape($_); } split(/:/,$listing);
                   5517:                     }
                   5518:                     if ($listing_results[0] ne 'no_such_dir' && 
                   5519:                         $listing_results[0] ne 'empty'       &&
                   5520:                         $listing_results[0] ne 'con_lost') {
1.800     albertel 5521:                         foreach my $line (@listing_results) {
                   5522:                             my ($entry) = split(/&/,$line,2);
                   5523:                             $allusers{$entry} = 1;
1.253     stredwic 5524:                         }
                   5525:                     }
1.191     harris41 5526:                 }
1.253     stredwic 5527:             }
                   5528:             my $alluserstr='';
1.800     albertel 5529:             foreach my $user (sort(keys(%allusers))) {
                   5530:                 $alluserstr.=$user.'&user:';
1.253     stredwic 5531:             }
                   5532:             $alluserstr=~s/:$//;
                   5533:             return split(/:/,$alluserstr);
                   5534:         } else {
1.800     albertel 5535:             return ('missing user name');
1.253     stredwic 5536:         }
                   5537:     } elsif(!defined($alternateDirectoryRoot)) {
                   5538:         my $tryserver;
                   5539:         my %alldom=();
1.800     albertel 5540:         foreach $tryserver (keys(%libserv)) {
1.253     stredwic 5541:             $alldom{$hostdom{$tryserver}}=1;
                   5542:         }
                   5543:         my $alldomstr='';
1.800     albertel 5544:         foreach my $domain (sort(keys(%alldom))) {
                   5545:             $alldomstr.=$perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain:';
1.253     stredwic 5546:         }
                   5547:         $alldomstr=~s/:$//;
                   5548:         return split(/:/,$alldomstr);       
                   5549:     } else {
1.800     albertel 5550:         return ('missing domain');
1.275     stredwic 5551:     }
                   5552: }
                   5553: 
                   5554: # --------------------------------------------- GetFileTimestamp
                   5555: # This function utilizes dirlist and returns the date stamp for
                   5556: # when it was last modified.  It will also return an error of -1
                   5557: # if an error occurs
                   5558: 
1.410     matthew  5559: ##
                   5560: ## FIXME: This subroutine assumes its caller knows something about the
                   5561: ## directory structure of the home server for the student ($root).
                   5562: ## Not a good assumption to make.  Since this is for looking up files
                   5563: ## in user directories, the full path should be constructed by lond, not
                   5564: ## whatever machine we request data from.
                   5565: ##
1.275     stredwic 5566: sub GetFileTimestamp {
                   5567:     my ($studentDomain,$studentName,$filename,$root)=@_;
1.807     albertel 5568:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   5569:     $studentName   = &LONCAPA::clean_username($studentName);
1.275     stredwic 5570:     my $subdir=$studentName.'__';
                   5571:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   5572:     my $proname="$studentDomain/$subdir/$studentName";
                   5573:     $proname .= '/'.$filename;
1.375     matthew  5574:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
                   5575:                                               $studentName, $root);
1.275     stredwic 5576:     my @stats = split('&', $fileStat);
                   5577:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  5578:         # @stats contains first the filename, then the stat output
                   5579:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 5580:     } else {
                   5581:         return -1;
1.253     stredwic 5582:     }
1.26      www      5583: }
                   5584: 
1.712     albertel 5585: sub stat_file {
                   5586:     my ($uri) = @_;
1.787     albertel 5587:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 5588: 
1.712     albertel 5589:     my ($udom,$uname,$file,$dir);
                   5590:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   5591: 	($udom,$uname,$file) =
1.811     albertel 5592: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 5593: 	$file = 'userfiles/'.$file;
1.740     www      5594: 	$dir = &propath($udom,$uname);
1.712     albertel 5595:     }
                   5596:     if ($uri =~ m-^/res/-) {
                   5597: 	($udom,$uname) = 
1.807     albertel 5598: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 5599: 	$file = $uri;
                   5600:     }
                   5601: 
                   5602:     if (!$udom || !$uname || !$file) {
                   5603: 	# unable to handle the uri
                   5604: 	return ();
                   5605:     }
                   5606: 
                   5607:     my ($result) = &dirlist($file,$udom,$uname,$dir);
                   5608:     my @stats = split('&', $result);
1.721     banghart 5609:     
1.712     albertel 5610:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   5611: 	shift(@stats); #filename is first
                   5612: 	return @stats;
                   5613:     }
                   5614:     return ();
                   5615: }
                   5616: 
1.26      www      5617: # -------------------------------------------------------- Value of a Condition
                   5618: 
1.713     albertel 5619: # gets the value of a specific preevaluated condition
                   5620: #    stored in the string  $env{user.state.<cid>}
                   5621: # or looks up a condition reference in the bighash and if if hasn't
                   5622: # already been evaluated recurses into docondval to get the value of
                   5623: # the condition, then memoizing it to 
                   5624: #   $env{user.state.<cid>.<condition>}
1.40      www      5625: sub directcondval {
                   5626:     my $number=shift;
1.620     albertel 5627:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 5628: 	&Apache::lonuserstate::evalstate();
                   5629:     }
1.713     albertel 5630:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   5631: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   5632:     } elsif ($number =~ /^_/) {
                   5633: 	my $sub_condition;
                   5634: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   5635: 		&GDBM_READER(),0640)) {
                   5636: 	    $sub_condition=$bighash{'conditions'.$number};
                   5637: 	    untie(%bighash);
                   5638: 	}
                   5639: 	my $value = &docondval($sub_condition);
                   5640: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
                   5641: 	return $value;
                   5642:     }
1.620     albertel 5643:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   5644:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      5645:     } else {
                   5646:        return 2;
                   5647:     }
                   5648: }
                   5649: 
1.713     albertel 5650: # get the collection of conditions for this resource
1.26      www      5651: sub condval {
                   5652:     my $condidx=shift;
1.54      www      5653:     my $allpathcond='';
1.713     albertel 5654:     foreach my $cond (split(/\|/,$condidx)) {
                   5655: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   5656: 	    $allpathcond.=
                   5657: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   5658: 	}
1.191     harris41 5659:     }
1.54      www      5660:     $allpathcond=~s/\|$//;
1.713     albertel 5661:     return &docondval($allpathcond);
                   5662: }
                   5663: 
                   5664: #evaluates an expression of conditions
                   5665: sub docondval {
                   5666:     my ($allpathcond) = @_;
                   5667:     my $result=0;
                   5668:     if ($env{'request.course.id'}
                   5669: 	&& defined($allpathcond)) {
                   5670: 	my $operand='|';
                   5671: 	my @stack;
                   5672: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   5673: 	    if ($chunk eq '(') {
                   5674: 		push @stack,($operand,$result);
                   5675: 	    } elsif ($chunk eq ')') {
                   5676: 		my $before=pop @stack;
                   5677: 		if (pop @stack eq '&') {
                   5678: 		    $result=$result>$before?$before:$result;
                   5679: 		} else {
                   5680: 		    $result=$result>$before?$result:$before;
                   5681: 		}
                   5682: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   5683: 		$operand=$chunk;
                   5684: 	    } else {
                   5685: 		my $new=directcondval($chunk);
                   5686: 		if ($operand eq '&') {
                   5687: 		    $result=$result>$new?$new:$result;
                   5688: 		} else {
                   5689: 		    $result=$result>$new?$result:$new;
                   5690: 		}
                   5691: 	    }
                   5692: 	}
1.26      www      5693:     }
                   5694:     return $result;
1.421     albertel 5695: }
                   5696: 
                   5697: # ---------------------------------------------------- Devalidate courseresdata
                   5698: 
                   5699: sub devalidatecourseresdata {
                   5700:     my ($coursenum,$coursedomain)=@_;
                   5701:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 5702:     &devalidate_cache_new('courseres',$hashid);
1.28      www      5703: }
                   5704: 
1.763     www      5705: 
1.200     www      5706: # --------------------------------------------------- Course Resourcedata Query
                   5707: 
1.624     albertel 5708: sub get_courseresdata {
                   5709:     my ($coursenum,$coursedomain)=@_;
1.200     www      5710:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   5711:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 5712:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 5713:     my %dumpreply;
1.417     albertel 5714:     unless (defined($cached)) {
1.624     albertel 5715: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 5716: 	$result=\%dumpreply;
1.251     albertel 5717: 	my ($tmp) = keys(%dumpreply);
                   5718: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 5719: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 5720: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   5721: 	    return $tmp;
1.416     albertel 5722: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 5723: 	    $result=undef;
1.599     albertel 5724: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 5725: 	}
                   5726:     }
1.624     albertel 5727:     return $result;
                   5728: }
                   5729: 
1.633     albertel 5730: sub devalidateuserresdata {
                   5731:     my ($uname,$udom)=@_;
                   5732:     my $hashid="$udom:$uname";
                   5733:     &devalidate_cache_new('userres',$hashid);
                   5734: }
                   5735: 
1.624     albertel 5736: sub get_userresdata {
                   5737:     my ($uname,$udom)=@_;
                   5738:     #most student don\'t have any data set, check if there is some data
                   5739:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   5740: 
                   5741:     my $hashid="$udom:$uname";
                   5742:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   5743:     if (!defined($cached)) {
                   5744: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   5745: 	$result=\%resourcedata;
                   5746: 	&do_cache_new('userres',$hashid,$result,600);
                   5747:     }
                   5748:     my ($tmp)=keys(%$result);
                   5749:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   5750: 	return $result;
                   5751:     }
                   5752:     #error 2 occurs when the .db doesn't exist
                   5753:     if ($tmp!~/error: 2 /) {
1.672     albertel 5754: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 5755: 		 " Trying to get resource data for ".
                   5756: 		 $uname." at ".$udom.": ".
                   5757: 		 $tmp."</font>");
                   5758:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 5759: 	#&EXT_cache_set($udom,$uname);
                   5760: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 5761: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 5762:     }
                   5763:     return $tmp;
                   5764: }
                   5765: 
                   5766: sub resdata {
                   5767:     my ($name,$domain,$type,@which)=@_;
                   5768:     my $result;
                   5769:     if ($type eq 'course') {
                   5770: 	$result=&get_courseresdata($name,$domain);
                   5771:     } elsif ($type eq 'user') {
                   5772: 	$result=&get_userresdata($name,$domain);
                   5773:     }
                   5774:     if (!ref($result)) { return $result; }    
1.251     albertel 5775:     foreach my $item (@which) {
1.417     albertel 5776: 	if (defined($result->{$item})) {
                   5777: 	    return $result->{$item};
1.251     albertel 5778: 	}
1.250     albertel 5779:     }
1.291     albertel 5780:     return undef;
1.200     www      5781: }
                   5782: 
1.379     matthew  5783: #
                   5784: # EXT resource caching routines
                   5785: #
                   5786: 
                   5787: sub clear_EXT_cache_status {
1.383     albertel 5788:     &delenv('cache.EXT.');
1.379     matthew  5789: }
                   5790: 
                   5791: sub EXT_cache_status {
                   5792:     my ($target_domain,$target_user) = @_;
1.383     albertel 5793:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 5794:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  5795:         # We know already the user has no data
                   5796:         return 1;
                   5797:     } else {
                   5798:         return 0;
                   5799:     }
                   5800: }
                   5801: 
                   5802: sub EXT_cache_set {
                   5803:     my ($target_domain,$target_user) = @_;
1.383     albertel 5804:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.633     albertel 5805:     #&appenv($cachename => time);
1.379     matthew  5806: }
                   5807: 
1.28      www      5808: # --------------------------------------------------------- Value of a Variable
1.58      www      5809: sub EXT {
1.715     albertel 5810: 
1.395     albertel 5811:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      5812:     unless ($varname) { return ''; }
1.218     albertel 5813:     #get real user name/domain, courseid and symb
                   5814:     my $courseid;
1.359     albertel 5815:     my $publicuser;
1.427     www      5816:     if ($symbparm) {
                   5817: 	$symbparm=&get_symb_from_alias($symbparm);
                   5818:     }
1.218     albertel 5819:     if (!($uname && $udom)) {
1.790     albertel 5820:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 5821:       if (!$symbparm) {	$symbparm=$cursymb; }
                   5822:     } else {
1.620     albertel 5823: 	$courseid=$env{'request.course.id'};
1.218     albertel 5824:     }
1.48      www      5825:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   5826:     my $rest;
1.320     albertel 5827:     if (defined($therest[0])) {
1.48      www      5828:        $rest=join('.',@therest);
                   5829:     } else {
                   5830:        $rest='';
                   5831:     }
1.320     albertel 5832: 
1.57      www      5833:     my $qualifierrest=$qualifier;
                   5834:     if ($rest) { $qualifierrest.='.'.$rest; }
                   5835:     my $spacequalifierrest=$space;
                   5836:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      5837:     if ($realm eq 'user') {
1.48      www      5838: # --------------------------------------------------------------- user.resource
                   5839: 	if ($space eq 'resource') {
1.651     albertel 5840: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   5841: 		  || defined($Apache::lonhomework::parsing_a_task))
                   5842: 		 &&
1.744     albertel 5843: 		 ($symbparm eq &symbread()) ) {	
                   5844: 		# if we are in the middle of processing the resource the
                   5845: 		# get the value we are planning on committing
                   5846:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   5847:                     return $Apache::lonhomework::results{$qualifierrest};
                   5848:                 } else {
                   5849:                     return $Apache::lonhomework::history{$qualifierrest};
                   5850:                 }
1.335     albertel 5851: 	    } else {
1.359     albertel 5852: 		my %restored;
1.620     albertel 5853: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 5854: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   5855: 		} else {
                   5856: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   5857: 		}
1.335     albertel 5858: 		return $restored{$qualifierrest};
                   5859: 	    }
1.48      www      5860: # ----------------------------------------------------------------- user.access
                   5861:         } elsif ($space eq 'access') {
1.218     albertel 5862: 	    # FIXME - not supporting calls for a specific user
1.48      www      5863:             return &allowed($qualifier,$rest);
                   5864: # ------------------------------------------ user.preferences, user.environment
                   5865:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 5866: 	    if (($uname eq $env{'user.name'}) &&
                   5867: 		($udom eq $env{'user.domain'})) {
                   5868: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 5869: 	    } else {
1.359     albertel 5870: 		my %returnhash;
                   5871: 		if (!$publicuser) {
                   5872: 		    %returnhash=&userenvironment($udom,$uname,
                   5873: 						 $qualifierrest);
                   5874: 		}
1.218     albertel 5875: 		return $returnhash{$qualifierrest};
                   5876: 	    }
1.48      www      5877: # ----------------------------------------------------------------- user.course
                   5878:         } elsif ($space eq 'course') {
1.218     albertel 5879: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 5880:             return $env{join('.',('request.course',$qualifier))};
1.48      www      5881: # ------------------------------------------------------------------- user.role
                   5882:         } elsif ($space eq 'role') {
1.218     albertel 5883: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 5884:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      5885:             if ($qualifier eq 'value') {
                   5886: 		return $role;
                   5887:             } elsif ($qualifier eq 'extent') {
                   5888:                 return $where;
                   5889:             }
                   5890: # ----------------------------------------------------------------- user.domain
                   5891:         } elsif ($space eq 'domain') {
1.218     albertel 5892:             return $udom;
1.48      www      5893: # ------------------------------------------------------------------- user.name
                   5894:         } elsif ($space eq 'name') {
1.218     albertel 5895:             return $uname;
1.48      www      5896: # ---------------------------------------------------- Any other user namespace
1.29      www      5897:         } else {
1.359     albertel 5898: 	    my %reply;
                   5899: 	    if (!$publicuser) {
                   5900: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   5901: 	    }
                   5902: 	    return $reply{$qualifierrest};
1.48      www      5903:         }
1.236     www      5904:     } elsif ($realm eq 'query') {
                   5905: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 5906:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   5907: 						[$spacequalifierrest]);
1.620     albertel 5908: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      5909:    } elsif ($realm eq 'request') {
1.48      www      5910: # ------------------------------------------------------------- request.browser
                   5911:         if ($space eq 'browser') {
1.430     www      5912: 	    if ($qualifier eq 'textremote') {
1.676     albertel 5913: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      5914: 		    return 1;
                   5915: 		} else {
                   5916: 		    return 0;
                   5917: 		}
                   5918: 	    } else {
1.620     albertel 5919: 		return $env{'browser.'.$qualifier};
1.430     www      5920: 	    }
1.57      www      5921: # ------------------------------------------------------------ request.filename
                   5922:         } else {
1.620     albertel 5923:             return $env{'request.'.$spacequalifierrest};
1.29      www      5924:         }
1.28      www      5925:     } elsif ($realm eq 'course') {
1.48      www      5926: # ---------------------------------------------------------- course.description
1.620     albertel 5927:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      5928:     } elsif ($realm eq 'resource') {
1.165     www      5929: 
1.620     albertel 5930: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 5931: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   5932: 	}
1.693     albertel 5933: 
                   5934: 	if ($space eq 'title') {
                   5935: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   5936: 	    return &gettitle($symbparm);
                   5937: 	}
                   5938: 	
                   5939: 	if ($space eq 'map') {
                   5940: 	    my ($map) = &decode_symb($symbparm);
                   5941: 	    return &symbread($map);
                   5942: 	}
                   5943: 
                   5944: 	my ($section, $group, @groups);
1.593     albertel 5945: 	my ($courselevelm,$courselevel);
1.539     albertel 5946: 	if ($symbparm && defined($courseid) && 
1.620     albertel 5947: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      5948: 
1.218     albertel 5949: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      5950: 
1.60      www      5951: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 5952: 	    my $symbp=$symbparm;
1.735     albertel 5953: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 5954: 
                   5955: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   5956: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   5957: 
1.620     albertel 5958: 	    if (($env{'user.name'} eq $uname) &&
                   5959: 		($env{'user.domain'} eq $udom)) {
                   5960: 		$section=$env{'request.course.sec'};
1.733     raeburn  5961:                 @groups = split(/:/,$env{'request.course.groups'});  
                   5962:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 5963: 	    } else {
1.539     albertel 5964: 		if (! defined($usection)) {
1.551     albertel 5965: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 5966: 		} else {
                   5967: 		    $section = $usection;
                   5968: 		}
1.733     raeburn  5969:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 5970: 	    }
                   5971: 
                   5972: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   5973: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   5974: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   5975: 
1.593     albertel 5976: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 5977: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 5978: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      5979: 
1.60      www      5980: # ----------------------------------------------------------- first, check user
1.624     albertel 5981: 
                   5982: 	    my $userreply=&resdata($uname,$udom,'user',
                   5983: 				       ($courselevelr,$courselevelm,
                   5984: 					$courselevel));
                   5985: 	    if (defined($userreply)) { return $userreply; }
1.95      www      5986: 
1.594     albertel 5987: # ------------------------------------------------ second, check some of course
1.684     raeburn  5988:             my $coursereply;
1.691     raeburn  5989:             if (@groups > 0) {
                   5990:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   5991:                                        $mapparm,$spacequalifierrest);
1.684     raeburn  5992:                 if (defined($coursereply)) { return $coursereply; }
                   5993:             }
1.96      www      5994: 
1.684     raeburn  5995: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.624     albertel 5996: 				     $env{'course.'.$courseid.'.domain'},
                   5997: 				     'course',
                   5998: 				     ($seclevelr,$seclevelm,$seclevel,
                   5999: 				      $courselevelr));
1.287     albertel 6000: 	    if (defined($coursereply)) { return $coursereply; }
1.200     www      6001: 
1.60      www      6002: # ------------------------------------------------------ third, check map parms
1.218     albertel 6003: 	    my %parmhash=();
                   6004: 	    my $thisparm='';
                   6005: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 6006: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 6007: 		    &GDBM_READER(),0640)) {
1.218     albertel 6008: 		$thisparm=$parmhash{$symbparm};
                   6009: 		untie(%parmhash);
                   6010: 	    }
                   6011: 	    if ($thisparm) { return $thisparm; }
                   6012: 	}
1.594     albertel 6013: # ------------------------------------------ fourth, look in resource metadata
1.71      www      6014: 
1.218     albertel 6015: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 6016: 	my $filename;
                   6017: 	if (!$symbparm) { $symbparm=&symbread(); }
                   6018: 	if ($symbparm) {
1.409     www      6019: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 6020: 	} else {
1.620     albertel 6021: 	    $filename=$env{'request.filename'};
1.282     albertel 6022: 	}
                   6023: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.288     albertel 6024: 	if (defined($metadata)) { return $metadata; }
1.282     albertel 6025: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.288     albertel 6026: 	if (defined($metadata)) { return $metadata; }
1.142     www      6027: 
1.594     albertel 6028: # ---------------------------------------------- fourth, look in rest pf course
1.593     albertel 6029: 	if ($symbparm && defined($courseid) && 
1.620     albertel 6030: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 6031: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   6032: 				     $env{'course.'.$courseid.'.domain'},
                   6033: 				     'course',
                   6034: 				     ($courselevelm,$courselevel));
1.593     albertel 6035: 	    if (defined($coursereply)) { return $coursereply; }
                   6036: 	}
1.145     www      6037: # ------------------------------------------------------------------ Cascade up
1.218     albertel 6038: 	unless ($space eq '0') {
1.336     albertel 6039: 	    my @parts=split(/_/,$space);
                   6040: 	    my $id=pop(@parts);
                   6041: 	    my $part=join('_',@parts);
                   6042: 	    if ($part eq '') { $part='0'; }
                   6043: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 6044: 				 $symbparm,$udom,$uname,$section,1);
1.337     albertel 6045: 	    if (defined($partgeneral)) { return $partgeneral; }
1.218     albertel 6046: 	}
1.395     albertel 6047: 	if ($recurse) { return undef; }
                   6048: 	my $pack_def=&packages_tab_default($filename,$varname);
                   6049: 	if (defined($pack_def)) { return $pack_def; }
1.71      www      6050: 
1.48      www      6051: # ---------------------------------------------------- Any other user namespace
                   6052:     } elsif ($realm eq 'environment') {
                   6053: # ----------------------------------------------------------------- environment
1.620     albertel 6054: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   6055: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 6056: 	} else {
1.770     albertel 6057: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   6058: 		return '';
                   6059: 	    }
1.219     albertel 6060: 	    my %returnhash=&userenvironment($udom,$uname,
                   6061: 					    $spacequalifierrest);
                   6062: 	    return $returnhash{$spacequalifierrest};
                   6063: 	}
1.28      www      6064:     } elsif ($realm eq 'system') {
1.48      www      6065: # ----------------------------------------------------------------- system.time
                   6066: 	if ($space eq 'time') {
                   6067: 	    return time;
                   6068:         }
1.696     albertel 6069:     } elsif ($realm eq 'server') {
                   6070: # ----------------------------------------------------------------- system.time
                   6071: 	if ($space eq 'name') {
                   6072: 	    return $ENV{'SERVER_NAME'};
                   6073:         }
1.28      www      6074:     }
1.48      www      6075:     return '';
1.61      www      6076: }
                   6077: 
1.691     raeburn  6078: sub check_group_parms {
                   6079:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   6080:     my @groupitems = ();
                   6081:     my $resultitem;
                   6082:     my @levels = ($symbparm,$mapparm,$what);
                   6083:     foreach my $group (@{$groups}) {
                   6084:         foreach my $level (@levels) {
                   6085:              my $item = $courseid.'.['.$group.'].'.$level;
                   6086:              push(@groupitems,$item);
                   6087:         }
                   6088:     }
                   6089:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   6090:                             $env{'course.'.$courseid.'.domain'},
                   6091:                                      'course',@groupitems);
                   6092:     return $coursereply;
                   6093: }
                   6094: 
                   6095: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  6096:     my ($courseid,@groups) = @_;
                   6097:     @groups = sort(@groups);
1.691     raeburn  6098:     return @groups;
                   6099: }
                   6100: 
1.395     albertel 6101: sub packages_tab_default {
                   6102:     my ($uri,$varname)=@_;
                   6103:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 6104: 
                   6105:     my (@extension,@specifics,$do_default);
                   6106:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 6107: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 6108: 	if ($pack_type eq 'default') {
                   6109: 	    $do_default=1;
                   6110: 	} elsif ($pack_type eq 'extension') {
                   6111: 	    push(@extension,[$package,$pack_type,$pack_part]);
                   6112: 	} else {
                   6113: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   6114: 	}
                   6115:     }
                   6116:     # first look for a package that matches the requested part id
                   6117:     foreach my $package (@specifics) {
                   6118: 	my (undef,$pack_type,$pack_part)=@{$package};
                   6119: 	next if ($pack_part ne $part);
                   6120: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6121: 	    return $packagetab{"$pack_type&$name&default"};
                   6122: 	}
                   6123:     }
                   6124:     # look for any possible matching non extension_ package
                   6125:     foreach my $package (@specifics) {
                   6126: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 6127: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6128: 	    return $packagetab{"$pack_type&$name&default"};
                   6129: 	}
1.585     albertel 6130: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 6131: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   6132: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 6133: 	}
                   6134:     }
1.738     albertel 6135:     # look for any posible extension_ match
                   6136:     foreach my $package (@extension) {
                   6137: 	my ($package,$pack_type)=@{$package};
                   6138: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6139: 	    return $packagetab{"$pack_type&$name&default"};
                   6140: 	}
                   6141: 	if (defined($packagetab{$package."&$name&default"})) {
                   6142: 	    return $packagetab{$package."&$name&default"};
                   6143: 	}
                   6144:     }
                   6145:     # look for a global default setting
                   6146:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   6147: 	return $packagetab{"default&$name&default"};
                   6148:     }
1.395     albertel 6149:     return undef;
                   6150: }
                   6151: 
1.334     albertel 6152: sub add_prefix_and_part {
                   6153:     my ($prefix,$part)=@_;
                   6154:     my $keyroot;
                   6155:     if (defined($prefix) && $prefix !~ /^__/) {
                   6156: 	# prefix that has a part already
                   6157: 	$keyroot=$prefix;
                   6158:     } elsif (defined($prefix)) {
                   6159: 	# prefix that is missing a part
                   6160: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   6161:     } else {
                   6162: 	# no prefix at all
                   6163: 	if (defined($part)) { $keyroot='_'.$part; }
                   6164:     }
                   6165:     return $keyroot;
                   6166: }
                   6167: 
1.71      www      6168: # ---------------------------------------------------------------- Get metadata
                   6169: 
1.599     albertel 6170: my %metaentry;
1.71      www      6171: sub metadata {
1.176     www      6172:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      6173:     $uri=&declutter($uri);
1.288     albertel 6174:     # if it is a non metadata possible uri return quickly
1.529     albertel 6175:     if (($uri eq '') || 
                   6176: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 6177: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.423     albertel 6178:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
1.807     albertel 6179: 	($uri =~ m|home/$match_username/public_html/|)) {
1.468     albertel 6180: 	return undef;
1.288     albertel 6181:     }
1.73      www      6182:     my $filename=$uri;
                   6183:     $uri=~s/\.meta$//;
1.172     www      6184: #
                   6185: # Is the metadata already cached?
1.177     www      6186: # Look at timestamp of caching
1.172     www      6187: # Everything is cached by the main uri, libraries are never directly cached
                   6188: #
1.428     albertel 6189:     if (!defined($liburi)) {
1.599     albertel 6190: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 6191: 	if (defined($cached)) { return $result->{':'.$what}; }
                   6192:     }
                   6193:     {
1.172     www      6194: #
                   6195: # Is this a recursive call for a library?
                   6196: #
1.599     albertel 6197: #	if (! exists($metacache{$uri})) {
                   6198: #	    $metacache{$uri}={};
                   6199: #	}
1.171     www      6200:         if ($liburi) {
                   6201: 	    $liburi=&declutter($liburi);
                   6202:             $filename=$liburi;
1.401     bowersj2 6203:         } else {
1.599     albertel 6204: 	    &devalidate_cache_new('meta',$uri);
                   6205: 	    undef(%metaentry);
1.401     bowersj2 6206: 	}
1.140     www      6207:         my %metathesekeys=();
1.73      www      6208:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 6209: 	my $metastring;
1.768     albertel 6210: 	if ($uri !~ m -^(editupload)/-) {
1.543     albertel 6211: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 6212: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 6213: 	    $metastring=&getfile($file);
1.489     albertel 6214: 	}
1.208     albertel 6215:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      6216:         my $token;
1.140     www      6217:         undef %metathesekeys;
1.71      www      6218:         while ($token=$parser->get_token) {
1.339     albertel 6219: 	    if ($token->[0] eq 'S') {
                   6220: 		if (defined($token->[2]->{'package'})) {
1.172     www      6221: #
                   6222: # This is a package - get package info
                   6223: #
1.339     albertel 6224: 		    my $package=$token->[2]->{'package'};
                   6225: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6226: 		    if (defined($token->[2]->{'id'})) { 
                   6227: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   6228: 		    }
1.599     albertel 6229: 		    if ($metaentry{':packages'}) {
                   6230: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 6231: 		    } else {
1.599     albertel 6232: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 6233: 		    }
1.736     albertel 6234: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 6235: 			my $part=$keyroot;
                   6236: 			$part=~s/^\_//;
1.736     albertel 6237: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   6238: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   6239: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 6240: 			    # ignore package.tab specified default values
                   6241:                             # here &package_tab_default() will fetch those
                   6242: 			    if ($subp eq 'default') { next; }
1.736     albertel 6243: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 6244: 			    my $unikey;
                   6245: 			    if ($pack =~ /_0$/) {
                   6246: 				$unikey='parameter_0_'.$name;
                   6247: 				$part=0;
                   6248: 			    } else {
                   6249: 				$unikey='parameter'.$keyroot.'_'.$name;
                   6250: 			    }
1.339     albertel 6251: 			    if ($subp eq 'display') {
                   6252: 				$value.=' [Part: '.$part.']';
                   6253: 			    }
1.599     albertel 6254: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 6255: 			    $metathesekeys{$unikey}=1;
1.599     albertel 6256: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6257: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 6258: 			    }
1.599     albertel 6259: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   6260: 				$metaentry{':'.$unikey}=
                   6261: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 6262: 			    }
1.339     albertel 6263: 			}
                   6264: 		    }
                   6265: 		} else {
1.172     www      6266: #
                   6267: # This is not a package - some other kind of start tag
1.339     albertel 6268: #
                   6269: 		    my $entry=$token->[1];
                   6270: 		    my $unikey;
                   6271: 		    if ($entry eq 'import') {
                   6272: 			$unikey='';
                   6273: 		    } else {
                   6274: 			$unikey=$entry;
                   6275: 		    }
                   6276: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6277: 
                   6278: 		    if (defined($token->[2]->{'id'})) { 
                   6279: 			$unikey.='_'.$token->[2]->{'id'}; 
                   6280: 		    }
1.175     www      6281: 
1.339     albertel 6282: 		    if ($entry eq 'import') {
1.175     www      6283: #
                   6284: # Importing a library here
1.339     albertel 6285: #
                   6286: 			if ($depthcount<20) {
                   6287: 			    my $location=$parser->get_text('/import');
                   6288: 			    my $dir=$filename;
                   6289: 			    $dir=~s|[^/]*$||;
                   6290: 			    $location=&filelocation($dir,$location);
1.736     albertel 6291: 			    my $metadata = 
                   6292: 				&metadata($uri,'keys', $location,$unikey,
                   6293: 					  $depthcount+1);
                   6294: 			    foreach my $meta (split(',',$metadata)) {
                   6295: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   6296: 				$metathesekeys{$meta}=1;
1.339     albertel 6297: 			    }
                   6298: 			}
                   6299: 		    } else { 
                   6300: 			
                   6301: 			if (defined($token->[2]->{'name'})) { 
                   6302: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   6303: 			}
                   6304: 			$metathesekeys{$unikey}=1;
1.736     albertel 6305: 			foreach my $param (@{$token->[3]}) {
                   6306: 			    $metaentry{':'.$unikey.'.'.$param} =
                   6307: 				$token->[2]->{$param};
1.339     albertel 6308: 			}
                   6309: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 6310: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 6311: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   6312: 		 # only ws inside the tag, and not in default, so use default
                   6313: 		 # as value
1.599     albertel 6314: 			    $metaentry{':'.$unikey}=$default;
1.339     albertel 6315: 			} else {
1.321     albertel 6316: 		  # either something interesting inside the tag or default
                   6317:                   # uninteresting
1.599     albertel 6318: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 6319: 			}
1.172     www      6320: # end of not-a-package not-a-library import
1.339     albertel 6321: 		    }
1.172     www      6322: # end of not-a-package start tag
1.339     albertel 6323: 		}
1.172     www      6324: # the next is the end of "start tag"
1.339     albertel 6325: 	    }
                   6326: 	}
1.483     albertel 6327: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.737     albertel 6328: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 6329: 	    #no specific packages #how's our extension
                   6330: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 6331: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 6332: 					 \%metathesekeys);
                   6333: 	}
1.599     albertel 6334: 	if (!exists($metaentry{':packages'})) {
1.737     albertel 6335: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 6336: 		#no specific packages well let's get default then
                   6337: 		if ($key!~/^default&/) { next; }
1.488     albertel 6338: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 6339: 					     \%metathesekeys);
                   6340: 	    }
                   6341: 	}
1.338     www      6342: # are there custom rights to evaluate
1.599     albertel 6343: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 6344: 
1.338     www      6345:     #
                   6346:     # Importing a rights file here
1.339     albertel 6347:     #
                   6348: 	    unless ($depthcount) {
1.599     albertel 6349: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 6350: 		my $dir=$filename;
                   6351: 		$dir=~s|[^/]*$||;
                   6352: 		$location=&filelocation($dir,$location);
1.736     albertel 6353: 		my $rights_metadata =
                   6354: 		    &metadata($uri,'keys',$location,'_rights',
                   6355: 			      $depthcount+1);
                   6356: 		foreach my $rights (split(',',$rights_metadata)) {
                   6357: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   6358: 		    $metathesekeys{$rights}=1;
1.339     albertel 6359: 		}
                   6360: 	    }
                   6361: 	}
1.737     albertel 6362: 	# uniqifiy package listing
                   6363: 	my %seen;
                   6364: 	my @uniq_packages =
                   6365: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   6366: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   6367: 
                   6368: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 6369: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   6370: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.699     albertel 6371: 	&do_cache_new('meta',$uri,\%metaentry,60*60);
1.177     www      6372: # this is the end of "was not already recently cached
1.71      www      6373:     }
1.599     albertel 6374:     return $metaentry{':'.$what};
1.261     albertel 6375: }
                   6376: 
1.488     albertel 6377: sub metadata_create_package_def {
1.483     albertel 6378:     my ($uri,$key,$package,$metathesekeys)=@_;
                   6379:     my ($pack,$name,$subp)=split(/\&/,$key);
                   6380:     if ($subp eq 'default') { next; }
                   6381:     
1.599     albertel 6382:     if (defined($metaentry{':packages'})) {
                   6383: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 6384:     } else {
1.599     albertel 6385: 	$metaentry{':packages'}=$package;
1.483     albertel 6386:     }
                   6387:     my $value=$packagetab{$key};
                   6388:     my $unikey;
                   6389:     $unikey='parameter_0_'.$name;
1.599     albertel 6390:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 6391:     $$metathesekeys{$unikey}=1;
1.599     albertel 6392:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6393: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 6394:     }
1.599     albertel 6395:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   6396: 	$metaentry{':'.$unikey}=
                   6397: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 6398:     }
                   6399: }
                   6400: 
1.261     albertel 6401: sub metadata_generate_part0 {
                   6402:     my ($metadata,$metacache,$uri) = @_;
                   6403:     my %allnames;
1.737     albertel 6404:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 6405: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 6406: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   6407: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 6408: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 6409: 	    $allnames{$name}=$part;
                   6410: 	  }
                   6411: 	}
                   6412:     }
                   6413:     foreach my $name (keys(%allnames)) {
                   6414:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 6415:       my $key=":parameter_0_$name";
1.261     albertel 6416:       $$metacache{"$key.part"}='0';
                   6417:       $$metacache{"$key.name"}=$name;
1.428     albertel 6418:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 6419: 					   $allnames{$name}.'_'.$name.
                   6420: 					   '.type'};
1.428     albertel 6421:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 6422: 			     '.display'};
1.644     www      6423:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 6424:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 6425:       $$metacache{"$key.display"}=$olddis;
                   6426:     }
1.71      www      6427: }
                   6428: 
1.764     albertel 6429: # ------------------------------------------------------ Devalidate title cache
                   6430: 
                   6431: sub devalidate_title_cache {
                   6432:     my ($url)=@_;
                   6433:     if (!$env{'request.course.id'}) { return; }
                   6434:     my $symb=&symbread($url);
                   6435:     if (!$symb) { return; }
                   6436:     my $key=$env{'request.course.id'}."\0".$symb;
                   6437:     &devalidate_cache_new('title',$key);
                   6438: }
                   6439: 
1.301     www      6440: # ------------------------------------------------- Get the title of a resource
                   6441: 
                   6442: sub gettitle {
                   6443:     my $urlsymb=shift;
                   6444:     my $symb=&symbread($urlsymb);
1.534     albertel 6445:     if ($symb) {
1.620     albertel 6446: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 6447: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 6448: 	if (defined($cached)) { 
                   6449: 	    return $result;
                   6450: 	}
1.534     albertel 6451: 	my ($map,$resid,$url)=&decode_symb($symb);
                   6452: 	my $title='';
                   6453: 	my %bighash;
1.620     albertel 6454: 	if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.534     albertel 6455: 		&GDBM_READER(),0640)) {
                   6456: 	    my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   6457: 	    $title=$bighash{'title_'.$mapid.'.'.$resid};
                   6458: 	    untie %bighash;
                   6459: 	}
                   6460: 	$title=~s/\&colon\;/\:/gs;
                   6461: 	if ($title) {
1.599     albertel 6462: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 6463: 	}
                   6464: 	$urlsymb=$url;
                   6465:     }
                   6466:     my $title=&metadata($urlsymb,'title');
                   6467:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   6468:     return $title;
1.301     www      6469: }
1.613     albertel 6470: 
1.614     albertel 6471: sub get_slot {
                   6472:     my ($which,$cnum,$cdom)=@_;
                   6473:     if (!$cnum || !$cdom) {
1.790     albertel 6474: 	(undef,my $courseid)=&whichuser();
1.620     albertel 6475: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   6476: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 6477:     }
1.703     albertel 6478:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   6479:     my %slotinfo;
                   6480:     if (exists($remembered{$key})) {
                   6481: 	$slotinfo{$which} = $remembered{$key};
                   6482:     } else {
                   6483: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   6484: 	&Apache::lonhomework::showhash(%slotinfo);
                   6485: 	my ($tmp)=keys(%slotinfo);
                   6486: 	if ($tmp=~/^error:/) { return (); }
                   6487: 	$remembered{$key} = $slotinfo{$which};
                   6488:     }
1.616     albertel 6489:     if (ref($slotinfo{$which}) eq 'HASH') {
                   6490: 	return %{$slotinfo{$which}};
                   6491:     }
                   6492:     return $slotinfo{$which};
1.614     albertel 6493: }
1.31      www      6494: # ------------------------------------------------- Update symbolic store links
                   6495: 
                   6496: sub symblist {
                   6497:     my ($mapname,%newhash)=@_;
1.438     www      6498:     $mapname=&deversion(&declutter($mapname));
1.31      www      6499:     my %hash;
1.620     albertel 6500:     if (($env{'request.course.fn'}) && (%newhash)) {
                   6501:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6502:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 6503: 	    foreach my $url (keys %newhash) {
                   6504: 		next if ($url eq 'last_known'
                   6505: 			 && $env{'form.no_update_last_known'});
                   6506: 		$hash{declutter($url)}=&encode_symb($mapname,
                   6507: 						    $newhash{$url}->[1],
                   6508: 						    $newhash{$url}->[0]);
1.191     harris41 6509:             }
1.31      www      6510:             if (untie(%hash)) {
                   6511: 		return 'ok';
                   6512:             }
                   6513:         }
                   6514:     }
                   6515:     return 'error';
1.212     www      6516: }
                   6517: 
                   6518: # --------------------------------------------------------------- Verify a symb
                   6519: 
                   6520: sub symbverify {
1.510     www      6521:     my ($symb,$thisurl)=@_;
                   6522:     my $thisfn=$thisurl;
1.439     www      6523:     $thisfn=&declutter($thisfn);
1.215     www      6524: # direct jump to resource in page or to a sequence - will construct own symbs
                   6525:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   6526: # check URL part
1.409     www      6527:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      6528: 
1.431     www      6529:     unless ($url eq $thisfn) { return 0; }
1.213     www      6530: 
1.216     www      6531:     $symb=&symbclean($symb);
1.510     www      6532:     $thisurl=&deversion($thisurl);
1.439     www      6533:     $thisfn=&deversion($thisfn);
1.213     www      6534: 
                   6535:     my %bighash;
                   6536:     my $okay=0;
1.431     www      6537: 
1.620     albertel 6538:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6539:                             &GDBM_READER(),0640)) {
1.510     www      6540:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      6541:         unless ($ids) { 
1.510     www      6542:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      6543:         }
                   6544:         if ($ids) {
                   6545: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 6546: 	    foreach my $id (split(/\,/,$ids)) {
                   6547: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      6548:                if (
                   6549:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   6550:    eq $symb) { 
1.620     albertel 6551: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 6552: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 6553: 		       $okay=1; 
                   6554: 		   }
                   6555: 	       }
1.216     www      6556: 	   }
                   6557:         }
1.213     www      6558: 	untie(%bighash);
                   6559:     }
                   6560:     return $okay;
1.31      www      6561: }
                   6562: 
1.210     www      6563: # --------------------------------------------------------------- Clean-up symb
                   6564: 
                   6565: sub symbclean {
                   6566:     my $symb=shift;
1.568     albertel 6567:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      6568: # remove version from map
                   6569:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      6570: 
1.210     www      6571: # remove version from URL
                   6572:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      6573: 
1.507     www      6574: # remove wrapper
                   6575: 
1.510     www      6576:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 6577:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      6578:     return $symb;
1.409     www      6579: }
                   6580: 
                   6581: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 6582: 
                   6583: sub encode_symb {
                   6584:     my ($map,$resid,$url)=@_;
                   6585:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   6586: }
1.409     www      6587: 
                   6588: sub decode_symb {
1.568     albertel 6589:     my $symb=shift;
                   6590:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   6591:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      6592:     return (&fixversion($map),$resid,&fixversion($url));
                   6593: }
                   6594: 
                   6595: sub fixversion {
                   6596:     my $fn=shift;
1.609     banghart 6597:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      6598:     my %bighash;
                   6599:     my $uri=&clutter($fn);
1.620     albertel 6600:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      6601: # is this cached?
1.599     albertel 6602:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      6603:     if (defined($cached)) { return $result; }
                   6604: # unfortunately not cached, or expired
1.620     albertel 6605:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      6606: 	    &GDBM_READER(),0640)) {
                   6607:  	if ($bighash{'version_'.$uri}) {
                   6608:  	    my $version=$bighash{'version_'.$uri};
1.444     www      6609:  	    unless (($version eq 'mostrecent') || 
                   6610: 		    ($version==&getversion($uri))) {
1.440     www      6611:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   6612:  	    }
                   6613:  	}
                   6614:  	untie %bighash;
1.413     www      6615:     }
1.599     albertel 6616:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      6617: }
                   6618: 
                   6619: sub deversion {
                   6620:     my $url=shift;
                   6621:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   6622:     return $url;
1.210     www      6623: }
                   6624: 
1.31      www      6625: # ------------------------------------------------------ Return symb list entry
                   6626: 
                   6627: sub symbread {
1.249     www      6628:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 6629:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 6630:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      6631: # no filename provided? try from environment
1.44      www      6632:     unless ($thisfn) {
1.620     albertel 6633:         if ($env{'request.symb'}) {
                   6634: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 6635: 	}
1.620     albertel 6636: 	$thisfn=$env{'request.filename'};
1.44      www      6637:     }
1.569     albertel 6638:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      6639: # is that filename actually a symb? Verify, clean, and return
                   6640:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 6641: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 6642: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 6643: 	}
1.242     www      6644:     }
1.44      www      6645:     $thisfn=declutter($thisfn);
1.31      www      6646:     my %hash;
1.37      www      6647:     my %bighash;
                   6648:     my $syval='';
1.620     albertel 6649:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  6650:         my $targetfn = $thisfn;
1.609     banghart 6651:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  6652:             $targetfn = 'adm/wrapper/'.$thisfn;
                   6653:         }
1.687     albertel 6654: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   6655: 	    $targetfn=$1;
                   6656: 	}
1.620     albertel 6657:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6658:                       &GDBM_READER(),0640)) {
1.481     raeburn  6659: 	    $syval=$hash{$targetfn};
1.37      www      6660:             untie(%hash);
                   6661:         }
                   6662: # ---------------------------------------------------------- There was an entry
                   6663:         if ($syval) {
1.601     albertel 6664: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 6665: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.601     albertel 6666: 		    #&appenv('request.ambiguous' => $thisfn);
1.620     albertel 6667: 		    #return $env{$cache_str}='';
1.601     albertel 6668: 		#}    
                   6669: 		#$syval.=$1;
                   6670: 	    #}
1.37      www      6671:         } else {
                   6672: # ------------------------------------------------------- Was not in symb table
1.620     albertel 6673:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6674:                             &GDBM_READER(),0640)) {
1.37      www      6675: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      6676:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      6677:               unless ($ids) { 
                   6678:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      6679:               }
                   6680:               unless ($ids) {
                   6681: # alias?
                   6682: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      6683:               }
1.37      www      6684:               if ($ids) {
                   6685: # ------------------------------------------------------------------- Has ID(s)
                   6686:                  my @possibilities=split(/\,/,$ids);
1.39      www      6687:                  if ($#possibilities==0) {
                   6688: # ----------------------------------------------- There is only one possibility
1.37      www      6689: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 6690: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6691: 						    $resid,$thisfn);
1.249     www      6692:                  } elsif (!$donotrecurse) {
1.39      www      6693: # ------------------------------------------ There is more than one possibility
                   6694:                      my $realpossible=0;
1.800     albertel 6695:                      foreach my $id (@possibilities) {
                   6696: 			 my $file=$bighash{'src_'.$id};
1.39      www      6697:                          if (&allowed('bre',$file)) {
1.800     albertel 6698:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      6699:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   6700: 				$realpossible++;
1.626     albertel 6701:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6702: 						    $resid,$thisfn);
1.39      www      6703:                             }
                   6704: 			 }
1.191     harris41 6705:                      }
1.39      www      6706: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      6707:                  } else {
                   6708:                      $syval='';
1.37      www      6709:                  }
                   6710: 	      }
                   6711:               untie(%bighash)
1.481     raeburn  6712:            }
1.31      www      6713:         }
1.62      www      6714:         if ($syval) {
1.620     albertel 6715: 	    return $env{$cache_str}=$syval;
1.62      www      6716:         }
1.31      www      6717:     }
1.44      www      6718:     &appenv('request.ambiguous' => $thisfn);
1.620     albertel 6719:     return $env{$cache_str}='';
1.31      www      6720: }
                   6721: 
                   6722: # ---------------------------------------------------------- Return random seed
                   6723: 
1.32      www      6724: sub numval {
                   6725:     my $txt=shift;
                   6726:     $txt=~tr/A-J/0-9/;
                   6727:     $txt=~tr/a-j/0-9/;
                   6728:     $txt=~tr/K-T/0-9/;
                   6729:     $txt=~tr/k-t/0-9/;
                   6730:     $txt=~tr/U-Z/0-5/;
                   6731:     $txt=~tr/u-z/0-5/;
                   6732:     $txt=~s/\D//g;
1.564     albertel 6733:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      6734:     return int($txt);
1.368     albertel 6735: }
                   6736: 
1.484     albertel 6737: sub numval2 {
                   6738:     my $txt=shift;
                   6739:     $txt=~tr/A-J/0-9/;
                   6740:     $txt=~tr/a-j/0-9/;
                   6741:     $txt=~tr/K-T/0-9/;
                   6742:     $txt=~tr/k-t/0-9/;
                   6743:     $txt=~tr/U-Z/0-5/;
                   6744:     $txt=~tr/u-z/0-5/;
                   6745:     $txt=~s/\D//g;
                   6746:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   6747:     my $total;
                   6748:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 6749:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 6750:     return int($total);
                   6751: }
                   6752: 
1.575     albertel 6753: sub numval3 {
                   6754:     use integer;
                   6755:     my $txt=shift;
                   6756:     $txt=~tr/A-J/0-9/;
                   6757:     $txt=~tr/a-j/0-9/;
                   6758:     $txt=~tr/K-T/0-9/;
                   6759:     $txt=~tr/k-t/0-9/;
                   6760:     $txt=~tr/U-Z/0-5/;
                   6761:     $txt=~tr/u-z/0-5/;
                   6762:     $txt=~s/\D//g;
                   6763:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   6764:     my $total;
                   6765:     foreach my $val (@txts) { $total+=$val; }
                   6766:     if ($_64bit) { $total=(($total<<32)>>32); }
                   6767:     return $total;
                   6768: }
                   6769: 
1.675     albertel 6770: sub digest {
                   6771:     my ($data)=@_;
                   6772:     my $digest=&Digest::MD5::md5($data);
                   6773:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   6774:     my ($e,$f);
                   6775:     {
                   6776:         use integer;
                   6777:         $e=($a+$b);
                   6778:         $f=($c+$d);
                   6779:         if ($_64bit) {
                   6780:             $e=(($e<<32)>>32);
                   6781:             $f=(($f<<32)>>32);
                   6782:         }
                   6783:     }
                   6784:     if (wantarray) {
                   6785: 	return ($e,$f);
                   6786:     } else {
                   6787: 	my $g;
                   6788: 	{
                   6789: 	    use integer;
                   6790: 	    $g=($e+$f);
                   6791: 	    if ($_64bit) {
                   6792: 		$g=(($g<<32)>>32);
                   6793: 	    }
                   6794: 	}
                   6795: 	return $g;
                   6796:     }
                   6797: }
                   6798: 
1.368     albertel 6799: sub latest_rnd_algorithm_id {
1.675     albertel 6800:     return '64bit5';
1.366     albertel 6801: }
1.32      www      6802: 
1.503     albertel 6803: sub get_rand_alg {
                   6804:     my ($courseid)=@_;
1.790     albertel 6805:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 6806:     if ($courseid) {
1.620     albertel 6807: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 6808:     }
                   6809:     return &latest_rnd_algorithm_id();
                   6810: }
                   6811: 
1.562     albertel 6812: sub validCODE {
                   6813:     my ($CODE)=@_;
                   6814:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   6815:     return 0;
                   6816: }
                   6817: 
1.491     albertel 6818: sub getCODE {
1.620     albertel 6819:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 6820:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   6821: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   6822: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 6823: 	return $Apache::lonhomework::history{'resource.CODE'};
                   6824:     }
                   6825:     return undef;
                   6826: }
                   6827: 
1.31      www      6828: sub rndseed {
1.155     albertel 6829:     my ($symb,$courseid,$domain,$username)=@_;
1.366     albertel 6830: 
1.790     albertel 6831:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.155     albertel 6832:     if (!$symb) {
1.366     albertel 6833: 	unless ($symb=$wsymb) { return time; }
                   6834:     }
                   6835:     if (!$courseid) { $courseid=$wcourseid; }
                   6836:     if (!$domain) { $domain=$wdomain; }
                   6837:     if (!$username) { $username=$wusername }
1.503     albertel 6838:     my $which=&get_rand_alg();
1.803     albertel 6839: 
1.491     albertel 6840:     if (defined(&getCODE())) {
1.675     albertel 6841: 	if ($which eq '64bit5') {
                   6842: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   6843: 	} elsif ($which eq '64bit4') {
1.575     albertel 6844: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   6845: 	} else {
                   6846: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   6847: 	}
1.675     albertel 6848:     } elsif ($which eq '64bit5') {
                   6849: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 6850:     } elsif ($which eq '64bit4') {
                   6851: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 6852:     } elsif ($which eq '64bit3') {
                   6853: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 6854:     } elsif ($which eq '64bit2') {
                   6855: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 6856:     } elsif ($which eq '64bit') {
                   6857: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   6858:     }
                   6859:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   6860: }
                   6861: 
                   6862: sub rndseed_32bit {
                   6863:     my ($symb,$courseid,$domain,$username)=@_;
                   6864:     {
                   6865: 	use integer;
                   6866: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   6867: 	my $symbseed=numval($symb) << 22;
                   6868: 	my $namechck=unpack("%32C*",$username) << 17;
                   6869: 	my $nameseed=numval($username) << 12;
                   6870: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   6871: 	my $courseseed=unpack("%32C*",$courseid);
                   6872: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 6873: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6874: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 6875: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 6876: 	return $num;
                   6877:     }
                   6878: }
                   6879: 
                   6880: sub rndseed_64bit {
                   6881:     my ($symb,$courseid,$domain,$username)=@_;
                   6882:     {
                   6883: 	use integer;
                   6884: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   6885: 	my $symbseed=numval($symb) << 10;
                   6886: 	my $namechck=unpack("%32S*",$username);
                   6887: 	
                   6888: 	my $nameseed=numval($username) << 21;
                   6889: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   6890: 	my $courseseed=unpack("%32S*",$courseid);
                   6891: 	
                   6892: 	my $num1=$symbchck+$symbseed+$namechck;
                   6893: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6894: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6895: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 6896: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 6897: 	return "$num1,$num2";
1.155     albertel 6898:     }
1.366     albertel 6899: }
                   6900: 
1.443     albertel 6901: sub rndseed_64bit2 {
                   6902:     my ($symb,$courseid,$domain,$username)=@_;
                   6903:     {
                   6904: 	use integer;
                   6905: 	# strings need to be an even # of cahracters long, it it is odd the
                   6906:         # last characters gets thrown away
                   6907: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6908: 	my $symbseed=numval($symb) << 10;
                   6909: 	my $namechck=unpack("%32S*",$username.' ');
                   6910: 	
                   6911: 	my $nameseed=numval($username) << 21;
1.501     albertel 6912: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6913: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6914: 	
                   6915: 	my $num1=$symbchck+$symbseed+$namechck;
                   6916: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6917: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6918: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 6919: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 6920: 	return "$num1,$num2";
                   6921:     }
                   6922: }
                   6923: 
                   6924: sub rndseed_64bit3 {
                   6925:     my ($symb,$courseid,$domain,$username)=@_;
                   6926:     {
                   6927: 	use integer;
                   6928: 	# strings need to be an even # of cahracters long, it it is odd the
                   6929:         # last characters gets thrown away
                   6930: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6931: 	my $symbseed=numval2($symb) << 10;
                   6932: 	my $namechck=unpack("%32S*",$username.' ');
                   6933: 	
                   6934: 	my $nameseed=numval2($username) << 21;
1.443     albertel 6935: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6936: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6937: 	
                   6938: 	my $num1=$symbchck+$symbseed+$namechck;
                   6939: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6940: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6941: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 6942: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6943: 	
1.503     albertel 6944: 	return "$num1:$num2";
1.443     albertel 6945:     }
                   6946: }
                   6947: 
1.575     albertel 6948: sub rndseed_64bit4 {
                   6949:     my ($symb,$courseid,$domain,$username)=@_;
                   6950:     {
                   6951: 	use integer;
                   6952: 	# strings need to be an even # of cahracters long, it it is odd the
                   6953:         # last characters gets thrown away
                   6954: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6955: 	my $symbseed=numval3($symb) << 10;
                   6956: 	my $namechck=unpack("%32S*",$username.' ');
                   6957: 	
                   6958: 	my $nameseed=numval3($username) << 21;
                   6959: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6960: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6961: 	
                   6962: 	my $num1=$symbchck+$symbseed+$namechck;
                   6963: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6964: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6965: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 6966: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6967: 	
                   6968: 	return "$num1:$num2";
                   6969:     }
                   6970: }
                   6971: 
1.675     albertel 6972: sub rndseed_64bit5 {
                   6973:     my ($symb,$courseid,$domain,$username)=@_;
                   6974:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   6975:     return "$num1:$num2";
                   6976: }
                   6977: 
1.366     albertel 6978: sub rndseed_CODE_64bit {
                   6979:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 6980:     {
1.366     albertel 6981: 	use integer;
1.443     albertel 6982: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 6983: 	my $symbseed=numval2($symb);
1.491     albertel 6984: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   6985: 	my $CODEseed=numval(&getCODE());
1.443     albertel 6986: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 6987: 	my $num1=$symbseed+$CODEchck;
                   6988: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 6989: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   6990: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 6991: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   6992: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 6993: 	return "$num1:$num2";
1.366     albertel 6994:     }
                   6995: }
                   6996: 
1.575     albertel 6997: sub rndseed_CODE_64bit4 {
                   6998:     my ($symb,$courseid,$domain,$username)=@_;
                   6999:     {
                   7000: 	use integer;
                   7001: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   7002: 	my $symbseed=numval3($symb);
                   7003: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   7004: 	my $CODEseed=numval3(&getCODE());
                   7005: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7006: 	my $num1=$symbseed+$CODEchck;
                   7007: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 7008: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   7009: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 7010: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   7011: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   7012: 	return "$num1:$num2";
                   7013:     }
                   7014: }
                   7015: 
1.675     albertel 7016: sub rndseed_CODE_64bit5 {
                   7017:     my ($symb,$courseid,$domain,$username)=@_;
                   7018:     my $code = &getCODE();
                   7019:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   7020:     return "$num1:$num2";
                   7021: }
                   7022: 
1.366     albertel 7023: sub setup_random_from_rndseed {
                   7024:     my ($rndseed)=@_;
1.503     albertel 7025:     if ($rndseed =~/([,:])/) {
                   7026: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 7027: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   7028:     } else {
                   7029: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 7030:     }
1.36      albertel 7031: }
                   7032: 
1.474     albertel 7033: sub latest_receipt_algorithm_id {
                   7034:     return 'receipt2';
                   7035: }
                   7036: 
1.480     www      7037: sub recunique {
                   7038:     my $fucourseid=shift;
                   7039:     my $unique;
1.620     albertel 7040:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   7041: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      7042:     } else {
                   7043: 	$unique=$perlvar{'lonReceipt'};
                   7044:     }
                   7045:     return unpack("%32C*",$unique);
                   7046: }
                   7047: 
                   7048: sub recprefix {
                   7049:     my $fucourseid=shift;
                   7050:     my $prefix;
1.620     albertel 7051:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   7052: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      7053:     } else {
                   7054: 	$prefix=$perlvar{'lonHostID'};
                   7055:     }
                   7056:     return unpack("%32C*",$prefix);
                   7057: }
                   7058: 
1.76      www      7059: sub ireceipt {
1.474     albertel 7060:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.76      www      7061:     my $cuname=unpack("%32C*",$funame);
                   7062:     my $cudom=unpack("%32C*",$fudom);
                   7063:     my $cucourseid=unpack("%32C*",$fucourseid);
                   7064:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      7065:     my $cunique=&recunique($fucourseid);
1.474     albertel 7066:     my $cpart=unpack("%32S*",$part);
1.480     www      7067:     my $return =&recprefix($fucourseid).'-';
1.620     albertel 7068:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   7069: 	$env{'request.state'} eq 'construct') {
1.790     albertel 7070: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 7071: 			       
                   7072: 	$return.= ($cunique%$cuname+
                   7073: 		   $cunique%$cudom+
                   7074: 		   $cusymb%$cuname+
                   7075: 		   $cusymb%$cudom+
                   7076: 		   $cucourseid%$cuname+
                   7077: 		   $cucourseid%$cudom+
                   7078: 		   $cpart%$cuname+
                   7079: 		   $cpart%$cudom);
                   7080:     } else {
                   7081: 	$return.= ($cunique%$cuname+
                   7082: 		   $cunique%$cudom+
                   7083: 		   $cusymb%$cuname+
                   7084: 		   $cusymb%$cudom+
                   7085: 		   $cucourseid%$cuname+
                   7086: 		   $cucourseid%$cudom);
                   7087:     }
                   7088:     return $return;
1.76      www      7089: }
                   7090: 
                   7091: sub receipt {
1.474     albertel 7092:     my ($part)=@_;
1.790     albertel 7093:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 7094:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      7095: }
1.260     ng       7096: 
1.790     albertel 7097: sub whichuser {
                   7098:     my ($passedsymb)=@_;
                   7099:     my ($symb,$courseid,$domain,$name,$publicuser);
                   7100:     if (defined($env{'form.grade_symb'})) {
                   7101: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   7102: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   7103: 	if (!$allowed &&
                   7104: 	    exists($env{'request.course.sec'}) &&
                   7105: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   7106: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   7107: 			      '/'.$env{'request.course.sec'});
                   7108: 	}
                   7109: 	if ($allowed) {
                   7110: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   7111: 	    $courseid=$tmp_courseid;
                   7112: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   7113: 	    ($name)=&get_env_multiple('form.grade_username');
                   7114: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   7115: 	}
                   7116:     }
                   7117:     if (!$passedsymb) {
                   7118: 	$symb=&symbread();
                   7119:     } else {
                   7120: 	$symb=$passedsymb;
                   7121:     }
                   7122:     $courseid=$env{'request.course.id'};
                   7123:     $domain=$env{'user.domain'};
                   7124:     $name=$env{'user.name'};
                   7125:     if ($name eq 'public' && $domain eq 'public') {
                   7126: 	if (!defined($env{'form.username'})) {
                   7127: 	    $env{'form.username'}.=time.rand(10000000);
                   7128: 	}
                   7129: 	$name.=$env{'form.username'};
                   7130:     }
                   7131:     return ($symb,$courseid,$domain,$name,$publicuser);
                   7132: 
                   7133: }
                   7134: 
1.36      albertel 7135: # ------------------------------------------------------------ Serves up a file
1.472     albertel 7136: # returns either the contents of the file or 
                   7137: # -1 if the file doesn't exist
1.481     raeburn  7138: #
                   7139: # if the target is a file that was uploaded via DOCS, 
                   7140: # a check will be made to see if a current copy exists on the local server,
                   7141: # if it does this will be served, otherwise a copy will be retrieved from
                   7142: # the home server for the course and stored in /home/httpd/html/userfiles on
                   7143: # the local server.   
1.472     albertel 7144: 
1.36      albertel 7145: sub getfile {
1.538     albertel 7146:     my ($file) = @_;
1.609     banghart 7147:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 7148:     &repcopy($file);
                   7149:     return &readfile($file);
                   7150: }
                   7151: 
                   7152: sub repcopy_userfile {
                   7153:     my ($file)=@_;
1.609     banghart 7154:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 7155:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 7156:     my ($cdom,$cnum,$filename) = 
1.811     albertel 7157: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 7158:     my ($info,$rtncode);
                   7159:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   7160:     if (-e "$file") {
                   7161: 	my @fileinfo = stat($file);
                   7162: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 7163: 	if ($lwpresp ne 'ok') {
                   7164: 	    if ($rtncode eq '404') {
1.538     albertel 7165: 		unlink($file);
1.482     albertel 7166: 	    }
1.517     albertel 7167: 	    #my $ua=new LWP::UserAgent;
1.538     albertel 7168: 	    #my $request=new HTTP::Request('GET',&tokenwrapper($uri));
1.517     albertel 7169: 	    #my $response=$ua->request($request);
                   7170: 	    #if ($response->is_success()) {
                   7171: 	#	return $response->content;
                   7172: 	#    } else {
                   7173: 	#	return -1;
                   7174: 	#    }
1.482     albertel 7175: 	    return -1;
                   7176: 	}
                   7177: 	if ($info < $fileinfo[9]) {
1.607     raeburn  7178: 	    return 'ok';
1.482     albertel 7179: 	}
                   7180: 	$info = '';
1.538     albertel 7181: 	$lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 7182: 	if ($lwpresp ne 'ok') {
                   7183: 	    return -1;
                   7184: 	}
                   7185:     } else {
1.538     albertel 7186: 	my $lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 7187: 	if ($lwpresp ne 'ok') {
1.824.2.2  albertel 7188: 	    return -1;
1.482     albertel 7189: 	}
                   7190: 	my @parts = ($cdom,$cnum); 
                   7191: 	if ($filename =~ m|^(.+)/[^/]+$|) {
                   7192: 	    push @parts, split(/\//,$1);
1.518     albertel 7193: 	}
1.538     albertel 7194: 	my $path = $perlvar{'lonDocRoot'}.'/userfiles';
1.482     albertel 7195: 	foreach my $part (@parts) {
                   7196: 	    $path .= '/'.$part;
                   7197: 	    if (!-e $path) {
                   7198: 		mkdir($path,0770);
                   7199: 	    }
                   7200: 	}
                   7201:     }
1.538     albertel 7202:     open(FILE,">$file");
1.482     albertel 7203:     print FILE $info;
                   7204:     close(FILE);
1.607     raeburn  7205:     return 'ok';
1.481     raeburn  7206: }
                   7207: 
1.517     albertel 7208: sub tokenwrapper {
                   7209:     my $uri=shift;
1.552     albertel 7210:     $uri=~s|^http\://([^/]+)||;
                   7211:     $uri=~s|^/||;
1.620     albertel 7212:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 7213:     my $token=$1;
1.552     albertel 7214:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   7215:     if ($udom && $uname && $file) {
                   7216: 	$file=~s|(\?\.*)*$||;
1.620     albertel 7217:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
1.552     albertel 7218:         return 'http://'.$hostname{ &homeserver($uname,$udom)}.'/'.$uri.
1.517     albertel 7219:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   7220:                                '&tokenissued='.$perlvar{'lonHostID'};
                   7221:     } else {
                   7222:         return '/adm/notfound.html';
                   7223:     }
                   7224: }
                   7225: 
1.481     raeburn  7226: sub getuploaded {
                   7227:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   7228:     $uri=~s/^\///;
                   7229:     $uri = 'http://'.$hostname{ &homeserver($cnum,$cdom)}.'/raw/'.$uri;
                   7230:     my $ua=new LWP::UserAgent;
                   7231:     my $request=new HTTP::Request($reqtype,$uri);
                   7232:     my $response=$ua->request($request);
                   7233:     $$rtncode = $response->code;
1.482     albertel 7234:     if (! $response->is_success()) {
                   7235: 	return 'failed';
                   7236:     }      
                   7237:     if ($reqtype eq 'HEAD') {
1.486     www      7238: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 7239:     } elsif ($reqtype eq 'GET') {
                   7240: 	$$info = $response->content;
1.472     albertel 7241:     }
1.482     albertel 7242:     return 'ok';
1.36      albertel 7243: }
                   7244: 
1.481     raeburn  7245: sub readfile {
                   7246:     my $file = shift;
                   7247:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   7248:     my $fh;
                   7249:     open($fh,"<$file");
                   7250:     my $a='';
1.800     albertel 7251:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  7252:     return $a;
                   7253: }
                   7254: 
1.36      albertel 7255: sub filelocation {
1.590     banghart 7256:     my ($dir,$file) = @_;
                   7257:     my $location;
                   7258:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 7259: 
                   7260:     if ($file =~ m-^/adm/-) {
                   7261: 	$file=~s-^/adm/wrapper/-/-;
                   7262: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   7263:     }
1.590     banghart 7264:     if ($file=~m:^/~:) { # is a contruction space reference
                   7265:         $location = $file;
                   7266:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 7267:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 7268: 	# is a correct contruction space reference
                   7269:         $location = $file;
1.609     banghart 7270:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 7271:         my ($udom,$uname,$filename)=
1.811     albertel 7272:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 7273:         my $home=&homeserver($uname,$udom);
                   7274:         my $is_me=0;
                   7275:         my @ids=&current_machine_ids();
                   7276:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   7277:         if ($is_me) {
1.740     www      7278:   	    $location=&propath($udom,$uname).
1.590     banghart 7279:   	      '/userfiles/'.$filename;
                   7280:         } else {
                   7281:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   7282:   	      $udom.'/'.$uname.'/'.$filename;
                   7283:         }
                   7284:     } else {
                   7285:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   7286:         $file=~s:^/res/:/:;
                   7287:         if ( !( $file =~ m:^/:) ) {
                   7288:             $location = $dir. '/'.$file;
                   7289:         } else {
                   7290:             $location = '/home/httpd/html/res'.$file;
                   7291:         }
1.59      albertel 7292:     }
1.590     banghart 7293:     $location=~s://+:/:g; # remove duplicate /
                   7294:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
                   7295:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   7296:     return $location;
1.46      www      7297: }
1.36      albertel 7298: 
1.46      www      7299: sub hreflocation {
                   7300:     my ($dir,$file)=@_;
1.460     albertel 7301:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666     albertel 7302: 	$file=filelocation($dir,$file);
1.700     albertel 7303:     } elsif ($file=~m-^/adm/-) {
                   7304: 	$file=~s-^/adm/wrapper/-/-;
                   7305: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 7306:     }
                   7307:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   7308: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 7309:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   7310: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 7311:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 7312: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 7313: 	    -/uploaded/$1/$2/-x;
1.46      www      7314:     }
1.462     albertel 7315:     return $file;
1.465     albertel 7316: }
                   7317: 
                   7318: sub current_machine_domains {
                   7319:     my $hostname=$hostname{$perlvar{'lonHostID'}};
                   7320:     my @domains;
                   7321:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  7322: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 7323: 	if ($hostname eq $name) {
                   7324: 	    push(@domains,$hostdom{$id});
                   7325: 	}
                   7326:     }
                   7327:     return @domains;
                   7328: }
                   7329: 
                   7330: sub current_machine_ids {
                   7331:     my $hostname=$hostname{$perlvar{'lonHostID'}};
                   7332:     my @ids;
                   7333:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  7334: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 7335: 	if ($hostname eq $name) {
                   7336: 	    push(@ids,$id);
                   7337: 	}
                   7338:     }
                   7339:     return @ids;
1.31      www      7340: }
                   7341: 
1.824     raeburn  7342: sub additional_machine_domains {
                   7343:     my @domains;
                   7344:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   7345:     while( my $line = <$fh>) {
                   7346:         $line =~ s/\s//g;
                   7347:         push(@domains,$line);
                   7348:     }
                   7349:     return @domains;
                   7350: }
                   7351: 
                   7352: sub default_login_domain {
                   7353:     my $domain = $perlvar{'lonDefDomain'};
                   7354:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   7355:     foreach my $posdom (&current_machine_domains(),
                   7356:                         &additional_machine_domains()) {
                   7357:         if (lc($posdom) eq lc($testdomain)) {
                   7358:             $domain=$posdom;
                   7359:             last;
                   7360:         }
                   7361:     }
                   7362:     return $domain;
                   7363: }
                   7364: 
1.31      www      7365: # ------------------------------------------------------------- Declutters URLs
                   7366: 
                   7367: sub declutter {
                   7368:     my $thisfn=shift;
1.569     albertel 7369:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 7370:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      7371:     $thisfn=~s/^\///;
1.697     albertel 7372:     $thisfn=~s|^adm/wrapper/||;
                   7373:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      7374:     $thisfn=~s/^res\///;
1.235     www      7375:     $thisfn=~s/\?.+$//;
1.268     www      7376:     return $thisfn;
                   7377: }
                   7378: 
                   7379: # ------------------------------------------------------------- Clutter up URLs
                   7380: 
                   7381: sub clutter {
                   7382:     my $thisfn='/'.&declutter(shift);
1.609     banghart 7383:     unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) { 
1.270     www      7384:        $thisfn='/res'.$thisfn; 
                   7385:     }
1.694     albertel 7386:     if ($thisfn !~m|/adm|) {
1.695     albertel 7387: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 7388: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 7389: 	} else {
                   7390: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   7391: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 7392: 	    if ($embstyle eq 'ssi'
                   7393: 		|| ($embstyle eq 'hdn')
                   7394: 		|| ($embstyle eq 'rat')
                   7395: 		|| ($embstyle eq 'prv')
                   7396: 		|| ($embstyle eq 'ign')) {
                   7397: 		#do nothing with these
                   7398: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 7399: 		|| ($embstyle eq 'emb')
                   7400: 		|| ($embstyle eq 'wrp')) {
                   7401: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 7402: 	    } elsif ($embstyle eq 'unk'
                   7403: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 7404: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 7405: 	    } else {
1.718     www      7406: #		&logthis("Got a blank emb style");
1.695     albertel 7407: 	    }
1.694     albertel 7408: 	}
                   7409:     }
1.31      www      7410:     return $thisfn;
1.12      www      7411: }
                   7412: 
1.787     albertel 7413: sub clutter_with_no_wrapper {
                   7414:     my $uri = &clutter(shift);
                   7415:     if ($uri =~ m-^/adm/-) {
                   7416: 	$uri =~ s-^/adm/wrapper/-/-;
                   7417: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   7418:     }
                   7419:     return $uri;
                   7420: }
                   7421: 
1.557     albertel 7422: sub freeze_escape {
                   7423:     my ($value)=@_;
                   7424:     if (ref($value)) {
                   7425: 	$value=&nfreeze($value);
                   7426: 	return '__FROZEN__'.&escape($value);
                   7427:     }
                   7428:     return &escape($value);
                   7429: }
                   7430: 
1.11      www      7431: 
1.557     albertel 7432: sub thaw_unescape {
                   7433:     my ($value)=@_;
                   7434:     if ($value =~ /^__FROZEN__/) {
                   7435: 	substr($value,0,10,undef);
                   7436: 	$value=&unescape($value);
                   7437: 	return &thaw($value);
                   7438:     }
                   7439:     return &unescape($value);
                   7440: }
                   7441: 
1.436     albertel 7442: sub correct_line_ends {
                   7443:     my ($result)=@_;
                   7444:     $$result =~s/\r\n/\n/mg;
                   7445:     $$result =~s/\r/\n/mg;
1.415     albertel 7446: }
1.1       albertel 7447: # ================================================================ Main Program
                   7448: 
1.184     www      7449: sub goodbye {
1.204     albertel 7450:    &logthis("Starting Shut down");
1.443     albertel 7451: #not converted to using infrastruture and probably shouldn't be
1.599     albertel 7452:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&freeze(\%badServerCache))));
1.443     albertel 7453: #converted
1.599     albertel 7454: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
                   7455:    &logthis(sprintf("%-20s is %s",'%homecache',length(&freeze(\%homecache))));
                   7456: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&freeze(\%titlecache))));
                   7457: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&freeze(\%courseresdatacache))));
1.425     albertel 7458: #1.1 only
1.599     albertel 7459: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&freeze(\%userresdatacache))));
                   7460: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&freeze(\%getsectioncache))));
                   7461: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&freeze(\%courseresversioncache))));
                   7462: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&freeze(\%resversioncache))));
                   7463:    &logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
                   7464:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   7465:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      7466:    &flushcourselogs();
                   7467:    &logthis("Shutting down");
                   7468: }
                   7469: 
1.179     www      7470: BEGIN {
1.228     harris41 7471: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
1.195     www      7472:     unless ($readit) {
1.217     harris41 7473: {
1.781     raeburn  7474:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   7475:     %perlvar = (%perlvar,%{$configvars});
1.227     harris41 7476: }
1.1       albertel 7477: 
1.327     albertel 7478: # ------------------------------------------------------------ Read domain file
                   7479: {
                   7480:     %domaindescription = ();
                   7481:     %domain_auth_def = ();
                   7482:     %domain_auth_arg_def = ();
1.448     albertel 7483:     my $fh;
                   7484:     if (open($fh,"<".$Apache::lonnet::perlvar{'lonTabDir'}.'/domain.tab')) {
1.800     albertel 7485: 	while (my $line = <$fh>) {
                   7486:            next if ($line =~ /^(\#|\s*$)/);
1.390     matthew  7487: #           next if /^\#/;
1.801     foxr     7488:            chomp $line;
1.403     www      7489:            my ($domain, $domain_description, $def_auth, $def_auth_arg,
1.800     albertel 7490: 	       $def_lang, $city, $longi, $lati, $primary) = split(/:/,$line,9);
1.403     www      7491: 	   $domain_auth_def{$domain}=$def_auth;
1.327     albertel 7492:            $domain_auth_arg_def{$domain}=$def_auth_arg;
1.403     www      7493: 	   $domaindescription{$domain}=$domain_description;
                   7494: 	   $domain_lang_def{$domain}=$def_lang;
                   7495: 	   $domain_city{$domain}=$city;
                   7496: 	   $domain_longi{$domain}=$longi;
                   7497: 	   $domain_lati{$domain}=$lati;
1.685     raeburn  7498:            $domain_primary{$domain}=$primary;
1.403     www      7499: 
1.448     albertel 7500:  #         &logthis("Domain.tab: $domain, $domain_auth_def{$domain}, $domain_auth_arg_def{$domain},$domaindescription{$domain}");
1.327     albertel 7501: #          &logthis("Domain.tab: $domain ".$domaindescription{$domain} );
1.448     albertel 7502: 	}
1.327     albertel 7503:     }
1.448     albertel 7504:     close ($fh);
1.327     albertel 7505: }
                   7506: 
                   7507: 
1.1       albertel 7508: # ------------------------------------------------------------- Read hosts file
                   7509: {
1.448     albertel 7510:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
1.1       albertel 7511: 
                   7512:     while (my $configline=<$config>) {
1.303     matthew  7513:        next if ($configline =~ /^(\#|\s*$)/);
1.154     www      7514:        chomp($configline);
1.595     albertel 7515:        my ($id,$domain,$role,$name)=split(/:/,$configline);
1.597     albertel 7516:        $name=~s/\s//g;
1.595     albertel 7517:        if ($id && $domain && $role && $name) {
1.252     albertel 7518: 	 $hostname{$id}=$name;
                   7519: 	 $hostdom{$id}=$domain;
                   7520: 	 if ($role eq 'library') { $libserv{$id}=$name; }
1.245     www      7521:        }
1.1       albertel 7522:     }
1.448     albertel 7523:     close($config);
1.619     albertel 7524:     # FIXME: dev server don't want this, production servers _do_ want this
1.654     albertel 7525:     #&get_iphost();
1.1       albertel 7526: }
                   7527: 
1.598     albertel 7528: sub get_iphost {
                   7529:     if (%iphost) { return %iphost; }
1.653     albertel 7530:     my %name_to_ip;
1.598     albertel 7531:     foreach my $id (keys(%hostname)) {
                   7532: 	my $name=$hostname{$id};
1.653     albertel 7533: 	my $ip;
                   7534: 	if (!exists($name_to_ip{$name})) {
                   7535: 	    $ip = gethostbyname($name);
                   7536: 	    if (!$ip || length($ip) ne 4) {
                   7537: 		&logthis("Skipping host $id name $name no IP found\n");
                   7538: 		next;
                   7539: 	    }
                   7540: 	    $ip=inet_ntoa($ip);
                   7541: 	    $name_to_ip{$name} = $ip;
                   7542: 	} else {
                   7543: 	    $ip = $name_to_ip{$name};
1.598     albertel 7544: 	}
                   7545: 	push(@{$iphost{$ip}},$id);
                   7546:     }
                   7547:     return %iphost;
                   7548: }
                   7549: 
1.1       albertel 7550: # ------------------------------------------------------ Read spare server file
                   7551: {
1.448     albertel 7552:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 7553: 
                   7554:     while (my $configline=<$config>) {
                   7555:        chomp($configline);
1.284     matthew  7556:        if ($configline) {
1.784     albertel 7557: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 7558: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 7559: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 7560:        }
                   7561:     }
1.448     albertel 7562:     close($config);
1.1       albertel 7563: }
1.11      www      7564: # ------------------------------------------------------------ Read permissions
                   7565: {
1.448     albertel 7566:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      7567: 
                   7568:     while (my $configline=<$config>) {
1.448     albertel 7569: 	chomp($configline);
                   7570: 	if ($configline) {
                   7571: 	    my ($role,$perm)=split(/ /,$configline);
                   7572: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   7573: 	}
1.11      www      7574:     }
1.448     albertel 7575:     close($config);
1.11      www      7576: }
                   7577: 
                   7578: # -------------------------------------------- Read plain texts for permissions
                   7579: {
1.448     albertel 7580:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      7581: 
                   7582:     while (my $configline=<$config>) {
1.448     albertel 7583: 	chomp($configline);
                   7584: 	if ($configline) {
1.742     raeburn  7585: 	    my ($short,@plain)=split(/:/,$configline);
                   7586:             %{$prp{$short}} = ();
                   7587: 	    if (@plain > 0) {
                   7588:                 $prp{$short}{'std'} = $plain[0];
                   7589:                 for (my $i=1; $i<@plain; $i++) {
                   7590:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   7591:                 }
                   7592:             }
1.448     albertel 7593: 	}
1.135     www      7594:     }
1.448     albertel 7595:     close($config);
1.135     www      7596: }
                   7597: 
                   7598: # ---------------------------------------------------------- Read package table
                   7599: {
1.448     albertel 7600:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      7601: 
                   7602:     while (my $configline=<$config>) {
1.483     albertel 7603: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 7604: 	chomp($configline);
                   7605: 	my ($short,$plain)=split(/:/,$configline);
                   7606: 	my ($pack,$name)=split(/\&/,$short);
                   7607: 	if ($plain ne '') {
                   7608: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   7609: 	    $packagetab{$short}=$plain; 
                   7610: 	}
1.11      www      7611:     }
1.448     albertel 7612:     close($config);
1.329     matthew  7613: }
                   7614: 
                   7615: # ------------- set up temporary directory
                   7616: {
                   7617:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   7618: 
1.11      www      7619: }
                   7620: 
1.794     albertel 7621: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   7622: 				'compress_threshold'=> 20_000,
                   7623:  			        });
1.185     www      7624: 
1.281     www      7625: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      7626: $dumpcount=0;
1.22      www      7627: 
1.163     harris41 7628: &logtouch();
1.672     albertel 7629: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      7630: $readit=1;
1.564     albertel 7631:     {
                   7632: 	use integer;
                   7633: 	my $test=(2**32)+1;
1.568     albertel 7634: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 7635: 	&logthis(" Detected 64bit platform ($_64bit)");
                   7636:     }
1.195     www      7637: }
1.1       albertel 7638: }
1.179     www      7639: 
1.1       albertel 7640: 1;
1.191     harris41 7641: __END__
                   7642: 
1.243     albertel 7643: =pod
                   7644: 
1.191     harris41 7645: =head1 NAME
                   7646: 
1.243     albertel 7647: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 7648: 
                   7649: =head1 SYNOPSIS
                   7650: 
1.243     albertel 7651: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 7652: 
                   7653:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   7654: 
1.243     albertel 7655: Common parameters:
                   7656: 
                   7657: =over 4
                   7658: 
                   7659: =item *
                   7660: 
                   7661: $uname : an internal username (if $cname expecting a course Id specifically)
                   7662: 
                   7663: =item *
                   7664: 
                   7665: $udom : a domain (if $cdom expecting a course's domain specifically)
                   7666: 
                   7667: =item *
                   7668: 
                   7669: $symb : a resource instance identifier
                   7670: 
                   7671: =item *
                   7672: 
                   7673: $namespace : the name of a .db file that contains the data needed or
                   7674: being set.
                   7675: 
                   7676: =back
                   7677: 
1.394     bowersj2 7678: =head1 OVERVIEW
1.191     harris41 7679: 
1.394     bowersj2 7680: lonnet provides subroutines which interact with the
                   7681: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   7682: about classes, users, and resources.
1.243     albertel 7683: 
                   7684: For many of these objects you can also use this to store data about
                   7685: them or modify them in various ways.
1.191     harris41 7686: 
1.394     bowersj2 7687: =head2 Symbs
1.191     harris41 7688: 
1.394     bowersj2 7689: To identify a specific instance of a resource, LON-CAPA uses symbols
                   7690: or "symbs"X<symb>. These identifiers are built from the URL of the
                   7691: map, the resource number of the resource in the map, and the URL of
                   7692: the resource itself. The latter is somewhat redundant, but might help
                   7693: if maps change.
                   7694: 
                   7695: An example is
                   7696: 
                   7697:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   7698: 
                   7699: The respective map entry is
                   7700: 
                   7701:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   7702:   title="Problem 2">
                   7703:  </resource>
                   7704: 
                   7705: Symbs are used by the random number generator, as well as to store and
                   7706: restore data specific to a certain instance of for example a problem.
                   7707: 
                   7708: =head2 Storing And Retrieving Data
                   7709: 
                   7710: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   7711: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   7712: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   7713: is is the non-critical message twin of cstore. These functions are for
                   7714: handlers to store a perl hash to a user's permanent data space in an
                   7715: easy manner, and to retrieve it again on another call. It is expected
                   7716: that a handler would use this once at the beginning to retrieve data,
                   7717: and then again once at the end to send only the new data back.
                   7718: 
                   7719: The data is stored in the user's data directory on the user's
                   7720: homeserver under the ID of the course.
                   7721: 
                   7722: The hash that is returned by restore will have all of the previous
                   7723: value for all of the elements of the hash.
                   7724: 
                   7725: Example:
                   7726: 
                   7727:  #creating a hash
                   7728:  my %hash;
                   7729:  $hash{'foo'}='bar';
                   7730: 
                   7731:  #storing it
                   7732:  &Apache::lonnet::cstore(\%hash);
                   7733: 
                   7734:  #changing a value
                   7735:  $hash{'foo'}='notbar';
                   7736: 
                   7737:  #adding a new value
                   7738:  $hash{'bar'}='foo';
                   7739:  &Apache::lonnet::cstore(\%hash);
                   7740: 
                   7741:  #retrieving the hash
                   7742:  my %history=&Apache::lonnet::restore();
                   7743: 
                   7744:  #print the hash
                   7745:  foreach my $key (sort(keys(%history))) {
                   7746:    print("\%history{$key} = $history{$key}");
                   7747:  }
                   7748: 
                   7749: Will print out:
1.191     harris41 7750: 
1.394     bowersj2 7751:  %history{1:foo} = bar
                   7752:  %history{1:keys} = foo:timestamp
                   7753:  %history{1:timestamp} = 990455579
                   7754:  %history{2:bar} = foo
                   7755:  %history{2:foo} = notbar
                   7756:  %history{2:keys} = foo:bar:timestamp
                   7757:  %history{2:timestamp} = 990455580
                   7758:  %history{bar} = foo
                   7759:  %history{foo} = notbar
                   7760:  %history{timestamp} = 990455580
                   7761:  %history{version} = 2
                   7762: 
                   7763: Note that the special hash entries C<keys>, C<version> and
                   7764: C<timestamp> were added to the hash. C<version> will be equal to the
                   7765: total number of versions of the data that have been stored. The
                   7766: C<timestamp> attribute will be the UNIX time the hash was
                   7767: stored. C<keys> is available in every historical section to list which
                   7768: keys were added or changed at a specific historical revision of a
                   7769: hash.
                   7770: 
                   7771: B<Warning>: do not store the hash that restore returns directly. This
                   7772: will cause a mess since it will restore the historical keys as if the
                   7773: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 7774: 
1.394     bowersj2 7775: Calling convention:
1.191     harris41 7776: 
1.394     bowersj2 7777:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   7778:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 7779: 
1.394     bowersj2 7780: For more detailed information, see lonnet specific documentation.
1.191     harris41 7781: 
1.394     bowersj2 7782: =head1 RETURN MESSAGES
1.191     harris41 7783: 
1.394     bowersj2 7784: =over 4
1.191     harris41 7785: 
1.394     bowersj2 7786: =item * B<con_lost>: unable to contact remote host
1.191     harris41 7787: 
1.394     bowersj2 7788: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   7789: when the connection is brought back up
1.191     harris41 7790: 
1.394     bowersj2 7791: =item * B<con_failed>: unable to contact remote host and unable to save message
                   7792: for later delivery
1.191     harris41 7793: 
1.394     bowersj2 7794: =item * B<error:>: an error a occured, a description of the error follows the :
1.191     harris41 7795: 
1.394     bowersj2 7796: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 7797: that was requested
1.191     harris41 7798: 
1.243     albertel 7799: =back
1.191     harris41 7800: 
1.243     albertel 7801: =head1 PUBLIC SUBROUTINES
1.191     harris41 7802: 
1.243     albertel 7803: =head2 Session Environment Functions
1.191     harris41 7804: 
1.243     albertel 7805: =over 4
1.191     harris41 7806: 
1.394     bowersj2 7807: =item * 
                   7808: X<appenv()>
                   7809: B<appenv(%hash)>: the value of %hash is written to
                   7810: the user envirnoment file, and will be restored for each access this
1.620     albertel 7811: user makes during this session, also modifies the %env for the current
1.394     bowersj2 7812: process
1.191     harris41 7813: 
                   7814: =item *
1.394     bowersj2 7815: X<delenv()>
                   7816: B<delenv($regexp)>: removes all items from the session
                   7817: environment file that matches the regular expression in $regexp. The
1.620     albertel 7818: values are also delted from the current processes %env.
1.191     harris41 7819: 
1.795     albertel 7820: =item * get_env_multiple($name) 
                   7821: 
                   7822: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   7823: values may be defined and end up as an array ref.
                   7824: 
                   7825: returns an array of values
                   7826: 
1.243     albertel 7827: =back
                   7828: 
                   7829: =head2 User Information
1.191     harris41 7830: 
1.243     albertel 7831: =over 4
1.191     harris41 7832: 
                   7833: =item *
1.394     bowersj2 7834: X<queryauthenticate()>
                   7835: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 7836: authentication scheme
                   7837: 
                   7838: =item *
1.394     bowersj2 7839: X<authenticate()>
                   7840: B<authenticate($uname,$upass,$udom)>: try to
                   7841: authenticate user from domain's lib servers (first use the current
                   7842: one). C<$upass> should be the users password.
1.191     harris41 7843: 
                   7844: =item *
1.394     bowersj2 7845: X<homeserver()>
                   7846: B<homeserver($uname,$udom)>: find the server which has
                   7847: the user's directory and files (there must be only one), this caches
                   7848: the answer, and also caches if there is a borken connection.
1.191     harris41 7849: 
                   7850: =item *
1.394     bowersj2 7851: X<idget()>
                   7852: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   7853: (IDs are a unique resource in a domain, there must be only 1 ID per
                   7854: username, and only 1 username per ID in a specific domain) (returns
                   7855: hash: id=>name,id=>name)
1.191     harris41 7856: 
                   7857: =item *
1.394     bowersj2 7858: X<idrget()>
                   7859: B<idrget($udom,@unames)>: find the IDs behind a list of
                   7860: usernames (returns hash: name=>id,name=>id)
1.191     harris41 7861: 
                   7862: =item *
1.394     bowersj2 7863: X<idput()>
                   7864: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 7865: 
                   7866: =item *
1.394     bowersj2 7867: X<rolesinit()>
                   7868: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 7869: 
                   7870: =item *
1.551     albertel 7871: X<getsection()>
                   7872: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 7873: course $cname, return section name/number or '' for "not in course"
                   7874: and '-1' for "no section"
                   7875: 
                   7876: =item *
1.394     bowersj2 7877: X<userenvironment()>
                   7878: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 7879: passed in @what from the requested user's environment, returns a hash
                   7880: 
                   7881: =back
                   7882: 
                   7883: =head2 User Roles
                   7884: 
                   7885: =over 4
                   7886: 
                   7887: =item *
                   7888: 
1.810     raeburn  7889: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 7890:  F: full access
                   7891:  U,I,K: authentication modes (cxx only)
                   7892:  '': forbidden
                   7893:  1: user needs to choose course
                   7894:  2: browse allowed
1.766     albertel 7895:  A: passphrase authentication needed
1.243     albertel 7896: 
                   7897: =item *
                   7898: 
                   7899: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   7900: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   7901: and course level
                   7902: 
                   7903: =item *
                   7904: 
                   7905: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   7906: explanation of a user role term
                   7907: 
                   7908: =back
                   7909: 
                   7910: =head2 User Modification
                   7911: 
                   7912: =over 4
                   7913: 
                   7914: =item *
                   7915: 
                   7916: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
                   7917: user for the level given by URL.  Optional start and end dates (leave empty
                   7918: string or zero for "no date")
1.191     harris41 7919: 
                   7920: =item *
                   7921: 
1.243     albertel 7922: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   7923: change a users, password, possible return values are: ok,
                   7924: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   7925: refused
1.191     harris41 7926: 
                   7927: =item *
                   7928: 
1.243     albertel 7929: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 7930: 
                   7931: =item *
                   7932: 
1.243     albertel 7933: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
                   7934: modify user
1.191     harris41 7935: 
                   7936: =item *
                   7937: 
1.286     matthew  7938: modifystudent
                   7939: 
                   7940: modify a students enrollment and identification information.
                   7941: The course id is resolved based on the current users environment.  
                   7942: This means the envoking user must be a course coordinator or otherwise
                   7943: associated with a course.
                   7944: 
1.297     matthew  7945: This call is essentially a wrapper for lonnet::modifyuser and
                   7946: lonnet::modify_student_enrollment
1.286     matthew  7947: 
                   7948: Inputs: 
                   7949: 
                   7950: =over 4
                   7951: 
                   7952: =item B<$udom> Students loncapa domain
                   7953: 
                   7954: =item B<$uname> Students loncapa login name
                   7955: 
                   7956: =item B<$uid> Students id/student number
                   7957: 
                   7958: =item B<$umode> Students authentication mode
                   7959: 
                   7960: =item B<$upass> Students password
                   7961: 
                   7962: =item B<$first> Students first name
                   7963: 
                   7964: =item B<$middle> Students middle name
                   7965: 
                   7966: =item B<$last> Students last name
                   7967: 
                   7968: =item B<$gene> Students generation
                   7969: 
                   7970: =item B<$usec> Students section in course
                   7971: 
                   7972: =item B<$end> Unix time of the roles expiration
                   7973: 
                   7974: =item B<$start> Unix time of the roles start date
                   7975: 
                   7976: =item B<$forceid> If defined, allow $uid to be changed
                   7977: 
                   7978: =item B<$desiredhome> server to use as home server for student
                   7979: 
                   7980: =back
1.297     matthew  7981: 
                   7982: =item *
                   7983: 
                   7984: modify_student_enrollment
                   7985: 
                   7986: Change a students enrollment status in a class.  The environment variable
                   7987: 'role.request.course' must be defined for this function to proceed.
                   7988: 
                   7989: Inputs:
                   7990: 
                   7991: =over 4
                   7992: 
                   7993: =item $udom, students domain
                   7994: 
                   7995: =item $uname, students name
                   7996: 
                   7997: =item $uid, students user id
                   7998: 
                   7999: =item $first, students first name
                   8000: 
                   8001: =item $middle
                   8002: 
                   8003: =item $last
                   8004: 
                   8005: =item $gene
                   8006: 
                   8007: =item $usec
                   8008: 
                   8009: =item $end
                   8010: 
                   8011: =item $start
                   8012: 
                   8013: =back
                   8014: 
1.191     harris41 8015: 
                   8016: =item *
                   8017: 
1.243     albertel 8018: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   8019: custom role; give a custom role to a user for the level given by URL.  Specify
                   8020: name and domain of role author, and role name
1.191     harris41 8021: 
                   8022: =item *
                   8023: 
1.243     albertel 8024: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 8025: 
                   8026: =item *
                   8027: 
1.243     albertel 8028: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   8029: 
                   8030: =back
                   8031: 
                   8032: =head2 Course Infomation
                   8033: 
                   8034: =over 4
1.191     harris41 8035: 
                   8036: =item *
                   8037: 
1.631     albertel 8038: coursedescription($courseid) : returns a hash of information about the
                   8039: specified course id, including all environment settings for the
                   8040: course, the description of the course will be in the hash under the
                   8041: key 'description'
1.191     harris41 8042: 
                   8043: =item *
                   8044: 
1.624     albertel 8045: resdata($name,$domain,$type,@which) : request for current parameter
                   8046: setting for a specific $type, where $type is either 'course' or 'user',
                   8047: @what should be a list of parameters to ask about. This routine caches
                   8048: answers for 5 minutes.
1.243     albertel 8049: 
                   8050: =back
                   8051: 
                   8052: =head2 Course Modification
                   8053: 
                   8054: =over 4
1.191     harris41 8055: 
                   8056: =item *
                   8057: 
1.243     albertel 8058: writecoursepref($courseid,%prefs) : write preferences (environment
                   8059: database) for a course
1.191     harris41 8060: 
                   8061: =item *
                   8062: 
1.243     albertel 8063: createcourse($udom,$description,$url) : make/modify course
                   8064: 
                   8065: =back
                   8066: 
                   8067: =head2 Resource Subroutines
                   8068: 
                   8069: =over 4
1.191     harris41 8070: 
                   8071: =item *
                   8072: 
1.243     albertel 8073: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 8074: 
                   8075: =item *
                   8076: 
1.243     albertel 8077: repcopy($filename) : subscribes to the requested file, and attempts to
                   8078: replicate from the owning library server, Might return
1.607     raeburn  8079: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   8080: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 8081: resource. Expects the local filesystem pathname
                   8082: (/home/httpd/html/res/....)
                   8083: 
                   8084: =back
                   8085: 
                   8086: =head2 Resource Information
                   8087: 
                   8088: =over 4
1.191     harris41 8089: 
                   8090: =item *
                   8091: 
1.243     albertel 8092: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   8093: a vairety of different possible values, $varname should be a request
                   8094: string, and the other parameters can be used to specify who and what
                   8095: one is asking about.
                   8096: 
                   8097: Possible values for $varname are environment.lastname (or other item
                   8098: from the envirnment hash), user.name (or someother aspect about the
                   8099: user), resource.0.maxtries (or some other part and parameter of a
                   8100: resource)
1.204     albertel 8101: 
                   8102: =item *
                   8103: 
1.243     albertel 8104: directcondval($number) : get current value of a condition; reads from a state
                   8105: string
1.204     albertel 8106: 
                   8107: =item *
                   8108: 
1.243     albertel 8109: condval($condidx) : value of condition index based on state
1.204     albertel 8110: 
                   8111: =item *
                   8112: 
1.243     albertel 8113: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   8114: resource's metadata, $what should be either a specific key, or either
                   8115: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   8116: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   8117: 
                   8118: this function automatically caches all requests
1.191     harris41 8119: 
                   8120: =item *
                   8121: 
1.243     albertel 8122: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   8123: network of library servers; returns file handle of where SQL and regex results
                   8124: will be stored for query
1.191     harris41 8125: 
                   8126: =item *
                   8127: 
1.243     albertel 8128: symbread($filename) : return symbolic list entry (filename argument optional);
                   8129: returns the data handle
1.191     harris41 8130: 
                   8131: =item *
                   8132: 
1.243     albertel 8133: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 8134: a possible symb for the URL in $thisfn, and if is an encryypted
                   8135: resource that the user accessed using /enc/ returns a 1 on success, 0
                   8136: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 8137: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 8138: 
1.191     harris41 8139: 
                   8140: =item *
                   8141: 
1.243     albertel 8142: symbclean($symb) : removes versions numbers from a symb, returns the
                   8143: cleaned symb
1.191     harris41 8144: 
                   8145: =item *
                   8146: 
1.243     albertel 8147: is_on_map($uri) : checks if the $uri is somewhere on the current
                   8148: course map, user must be in a course for it to work.
1.191     harris41 8149: 
                   8150: =item *
                   8151: 
1.243     albertel 8152: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 8153: 
                   8154: =item *
                   8155: 
1.243     albertel 8156: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   8157: a random seed, all arguments are optional, if they aren't sent it uses the
                   8158: environment to derive them. Note: if symb isn't sent and it can't get one
                   8159: from &symbread it will use the current time as its return value
1.191     harris41 8160: 
                   8161: =item *
                   8162: 
1.243     albertel 8163: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   8164: unfakeable, receipt
1.191     harris41 8165: 
                   8166: =item *
                   8167: 
1.620     albertel 8168: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 8169: 
                   8170: =item *
                   8171: 
1.243     albertel 8172: countacc($url) : count the number of accesses to a given URL
1.191     harris41 8173: 
                   8174: =item *
                   8175: 
1.243     albertel 8176: 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 8177: 
                   8178: =item *
                   8179: 
1.243     albertel 8180: 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 8181: 
                   8182: =item *
                   8183: 
1.243     albertel 8184: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 8185: 
                   8186: =item *
                   8187: 
1.243     albertel 8188: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   8189: forcing spreadsheet to reevaluate the resource scores next time.
                   8190: 
                   8191: =back
                   8192: 
                   8193: =head2 Storing/Retreiving Data
                   8194: 
                   8195: =over 4
1.191     harris41 8196: 
                   8197: =item *
                   8198: 
1.243     albertel 8199: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   8200: for this url; hashref needs to be given and should be a \%hashname; the
                   8201: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 8202: be derived from the env
1.191     harris41 8203: 
                   8204: =item *
                   8205: 
1.243     albertel 8206: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   8207: uses critical subroutine
1.191     harris41 8208: 
                   8209: =item *
                   8210: 
1.243     albertel 8211: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   8212: all args are optional
1.191     harris41 8213: 
                   8214: =item *
                   8215: 
1.717     albertel 8216: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   8217: dumps the complete (or key matching regexp) namespace into a hash
                   8218: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   8219: normally &store()ed into
                   8220: 
                   8221: $range should be either an integer '100' (give me the first 100
                   8222:                                            matching records)
                   8223:               or be  two integers sperated by a - with no spaces
                   8224:                  '30-50' (give me the 30th through the 50th matching
                   8225:                           records)
                   8226: 
                   8227: 
                   8228: =item *
                   8229: 
                   8230: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   8231: replaces a &store() version of data with a replacement set of data
                   8232: for a particular resource in a namespace passed in the $storehash hash 
                   8233: reference
                   8234: 
                   8235: =item *
                   8236: 
1.243     albertel 8237: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   8238: works very similar to store/cstore, but all data is stored in a
                   8239: temporary location and can be reset using tmpreset, $storehash should
                   8240: be a hash reference, returns nothing on success
1.191     harris41 8241: 
                   8242: =item *
                   8243: 
1.243     albertel 8244: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   8245: similar to restore, but all data is stored in a temporary location and
                   8246: can be reset using tmpreset. Returns a hash of values on success,
                   8247: error string otherwise.
1.191     harris41 8248: 
                   8249: =item *
                   8250: 
1.243     albertel 8251: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   8252: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 8253: 
                   8254: =item *
                   8255: 
1.243     albertel 8256: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   8257: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 8258: 
                   8259: =item *
                   8260: 
1.243     albertel 8261: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   8262: namesp ($udom and $uname are optional)
1.191     harris41 8263: 
                   8264: =item *
                   8265: 
1.702     albertel 8266: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 8267: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 8268: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  8269: 
1.702     albertel 8270: $range should be either an integer '100' (give me the first 100
                   8271:                                            matching records)
                   8272:               or be  two integers sperated by a - with no spaces
                   8273:                  '30-50' (give me the 30th through the 50th matching
                   8274:                           records)
1.449     matthew  8275: =item *
                   8276: 
                   8277: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   8278: $store can be a scalar, an array reference, or if the amount to be 
                   8279: incremented is > 1, a hash reference.
                   8280: 
                   8281: ($udom and $uname are optional)
1.191     harris41 8282: 
                   8283: =item *
                   8284: 
1.243     albertel 8285: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   8286: ($udom and $uname are optional)
1.191     harris41 8287: 
                   8288: =item *
                   8289: 
1.243     albertel 8290: cput($namespace,$storehash,$udom,$uname) : critical put
                   8291: ($udom and $uname are optional)
1.191     harris41 8292: 
                   8293: =item *
                   8294: 
1.748     albertel 8295: newput($namespace,$storehash,$udom,$uname) :
                   8296: 
                   8297: Attempts to store the items in the $storehash, but only if they don't
                   8298: currently exist, if this succeeds you can be certain that you have 
                   8299: successfully created a new key value pair in the $namespace db.
                   8300: 
                   8301: 
                   8302: Args:
                   8303:  $namespace: name of database to store values to
                   8304:  $storehash: hashref to store to the db
                   8305:  $udom: (optional) domain of user containing the db
                   8306:  $uname: (optional) name of user caontaining the db
                   8307: 
                   8308: Returns:
                   8309:  'ok' -> succeeded in storing all keys of $storehash
                   8310:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   8311:                         least <key> already existed in the db (other
                   8312:                         requested keys may also already exist)
                   8313:  'error: <msg>' -> unable to tie the DB or other erorr occured
                   8314:  'con_lost' -> unable to contact request server
                   8315:  'refused' -> action was not allowed by remote machine
                   8316: 
                   8317: 
                   8318: =item *
                   8319: 
1.243     albertel 8320: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   8321: reference filled in from namesp (encrypts the return communication)
                   8322: ($udom and $uname are optional)
1.191     harris41 8323: 
                   8324: =item *
                   8325: 
1.243     albertel 8326: log($udom,$name,$home,$message) : write to permanent log for user; use
                   8327: critical subroutine
                   8328: 
1.806     raeburn  8329: =item *
                   8330: 
                   8331: get_dom($namespace,$storearr,$udomain) : returns hash with keys from array
                   8332: reference filled in from namespace found in domain level on primary domain server ($udomain is optional)
                   8333: 
                   8334: =item *
                   8335: 
                   8336: put_dom($namespace,$storehash,$udomain) :  stores hash in namespace at domain level on primary domain server ($udomain is optional)
                   8337: 
1.243     albertel 8338: =back
                   8339: 
                   8340: =head2 Network Status Functions
                   8341: 
                   8342: =over 4
1.191     harris41 8343: 
                   8344: =item *
                   8345: 
                   8346: dirlist($uri) : return directory list based on URI
                   8347: 
                   8348: =item *
                   8349: 
1.243     albertel 8350: spareserver() : find server with least workload from spare.tab
                   8351: 
                   8352: =back
                   8353: 
                   8354: =head2 Apache Request
                   8355: 
                   8356: =over 4
1.191     harris41 8357: 
                   8358: =item *
                   8359: 
1.243     albertel 8360: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   8361: localhost, posts hash
                   8362: 
                   8363: =back
                   8364: 
                   8365: =head2 Data to String to Data
                   8366: 
                   8367: =over 4
1.191     harris41 8368: 
                   8369: =item *
                   8370: 
1.243     albertel 8371: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   8372: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 8373: 
                   8374: =item *
                   8375: 
1.243     albertel 8376: hashref2str($hashref) : convert a hashref into a string complete with
                   8377: escaping and '=' and '&' separators, supports elements that are
                   8378: arrayrefs and hashrefs
1.191     harris41 8379: 
                   8380: =item *
                   8381: 
1.243     albertel 8382: arrayref2str($arrayref) : convert an arrayref into a string complete
                   8383: with escaping and '&' separators, supports elements that are arrayrefs
                   8384: and hashrefs
1.191     harris41 8385: 
                   8386: =item *
                   8387: 
1.243     albertel 8388: str2hash($string) : convert string to hash using unescaping and
                   8389: splitting on '=' and '&', supports elements that are arrayrefs and
                   8390: hashrefs
1.191     harris41 8391: 
                   8392: =item *
                   8393: 
1.243     albertel 8394: str2array($string) : convert string to hash using unescaping and
                   8395: splitting on '&', supports elements that are arrayrefs and hashrefs
                   8396: 
                   8397: =back
                   8398: 
                   8399: =head2 Logging Routines
                   8400: 
                   8401: =over 4
                   8402: 
                   8403: These routines allow one to make log messages in the lonnet.log and
                   8404: lonnet.perm logfiles.
1.191     harris41 8405: 
                   8406: =item *
                   8407: 
1.243     albertel 8408: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 8409: 
                   8410: =item *
                   8411: 
1.243     albertel 8412: logthis() : append message to the normal lonnet.log file, it gets
                   8413: preiodically rolled over and deleted.
1.191     harris41 8414: 
                   8415: =item *
                   8416: 
1.243     albertel 8417: logperm() : append a permanent message to lonnet.perm.log, this log
                   8418: file never gets deleted by any automated portion of the system, only
                   8419: messages of critical importance should go in here.
                   8420: 
                   8421: =back
                   8422: 
                   8423: =head2 General File Helper Routines
                   8424: 
                   8425: =over 4
1.191     harris41 8426: 
                   8427: =item *
                   8428: 
1.481     raeburn  8429: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   8430: (a) files in /uploaded
                   8431:   (i) If a local copy of the file exists - 
                   8432:       compares modification date of local copy with last-modified date for 
                   8433:       definitive version stored on home server for course. If local copy is 
                   8434:       stale, requests a new version from the home server and stores it. 
                   8435:       If the original has been removed from the home server, then local copy 
                   8436:       is unlinked.
                   8437:   (ii) If local copy does not exist -
                   8438:       requests the file from the home server and stores it. 
                   8439:   
                   8440:   If $caller is 'uploadrep':  
                   8441:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   8442:     for request for files originally uploaded via DOCS. 
                   8443:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   8444:   
                   8445:   Otherwise:
                   8446:      This indicates a call from the content generation phase of the request.
                   8447:      -  returns the entire contents of the file or -1.
                   8448:      
                   8449: (b) files in /res
                   8450:    - returns the entire contents of a file or -1; 
                   8451:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 8452: 
1.712     albertel 8453: 
                   8454: =item *
                   8455: 
                   8456: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   8457:                   reference
                   8458: 
                   8459: returns either a stat() list of data about the file or an empty list
                   8460: if the file doesn't exist or couldn't find out about it (connection
                   8461: problems or user unknown)
                   8462: 
1.191     harris41 8463: =item *
                   8464: 
1.243     albertel 8465: filelocation($dir,$file) : returns file system location of a file
                   8466: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   8467: directory that relative $file lookups are to looked in ($dir of /a/dir
                   8468: and a file of ../bob will become /a/bob)
1.191     harris41 8469: 
                   8470: =item *
                   8471: 
                   8472: hreflocation($dir,$file) : returns file system location or a URL; same as
                   8473: filelocation except for hrefs
                   8474: 
                   8475: =item *
                   8476: 
                   8477: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   8478: 
1.243     albertel 8479: =back
                   8480: 
1.608     albertel 8481: =head2 Usererfile file routines (/uploaded*)
                   8482: 
                   8483: =over 4
                   8484: 
                   8485: =item *
                   8486: 
                   8487: userfileupload(): main rotine for putting a file in a user or course's
                   8488:                   filespace, arguments are,
                   8489: 
1.620     albertel 8490:  formname - required - this is the name of the element in $env where the
1.608     albertel 8491:            filename, and the contents of the file to create/modifed exist
1.620     albertel 8492:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   8493:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 8494:  coursedoc - if true, store the file in the course of the active role
                   8495:              of the current user
                   8496:  subdir - required - subdirectory to put the file in under ../userfiles/
                   8497:          if undefined, it will be placed in "unknown"
                   8498: 
                   8499:  (This routine calls clean_filename() to remove any dangerous
                   8500:  characters from the filename, and then calls finuserfileupload() to
                   8501:  complete the transaction)
                   8502: 
                   8503:  returns either the url of the uploaded file (/uploaded/....) if successful
                   8504:  and /adm/notfound.html if unsuccessful
                   8505: 
                   8506: =item *
                   8507: 
                   8508: clean_filename(): routine for cleaing a filename up for storage in
                   8509:                  userfile space, argument is:
                   8510: 
                   8511:  filename - proposed filename
                   8512: 
                   8513: returns: the new clean filename
                   8514: 
                   8515: =item *
                   8516: 
                   8517: finishuserfileupload(): routine that creaes and sends the file to
                   8518: userspace, probably shouldn't be called directly
                   8519: 
                   8520:   docuname: username or courseid of destination for the file
                   8521:   docudom: domain of user/course of destination for the file
                   8522:   formname: same as for userfileupload()
                   8523:   fname: filename (inculding subdirectories) for the file
                   8524: 
                   8525:  returns either the url of the uploaded file (/uploaded/....) if successful
                   8526:  and /adm/notfound.html if unsuccessful
                   8527: 
                   8528: =item *
                   8529: 
                   8530: renameuserfile(): renames an existing userfile to a new name
                   8531: 
                   8532:   Args:
                   8533:    docuname: username or courseid of destination for the file
                   8534:    docudom: domain of user/course of destination for the file
                   8535:    old: current file name (including any subdirs under userfiles)
                   8536:    new: desired file name (including any subdirs under userfiles)
                   8537: 
                   8538: =item *
                   8539: 
                   8540: mkdiruserfile(): creates a directory is a userfiles dir
                   8541: 
                   8542:   Args:
                   8543:    docuname: username or courseid of destination for the file
                   8544:    docudom: domain of user/course of destination for the file
                   8545:    dir: dir to create (including any subdirs under userfiles)
                   8546: 
                   8547: =item *
                   8548: 
                   8549: removeuserfile(): removes a file that exists in userfiles
                   8550: 
                   8551:   Args:
                   8552:    docuname: username or courseid of destination for the file
                   8553:    docudom: domain of user/course of destination for the file
                   8554:    fname: filname to delete (including any subdirs under userfiles)
                   8555: 
                   8556: =item *
                   8557: 
                   8558: removeuploadedurl(): convience function for removeuserfile()
                   8559: 
                   8560:   Args:
                   8561:    url:  a full /uploaded/... url to delete
                   8562: 
1.747     albertel 8563: =item * 
                   8564: 
                   8565: get_portfile_permissions():
                   8566:   Args:
                   8567:     domain: domain of user or course contain the portfolio files
                   8568:     user: name of user or num of course contain the portfolio files
                   8569:   Returns:
                   8570:     hashref of a dump of the proper file_permissions.db
                   8571:    
                   8572: 
                   8573: =item * 
                   8574: 
                   8575: get_access_controls():
                   8576: 
                   8577: Args:
                   8578:   current_permissions: the hash ref returned from get_portfile_permissions()
                   8579:   group: (optional) the group you want the files associated with
                   8580:   file: (optional) the file you want access info on
                   8581: 
                   8582: Returns:
1.749     raeburn  8583:     a hash (keys are file names) of hashes containing
                   8584:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   8585:         values are XML containing access control settings (see below) 
1.747     albertel 8586: 
                   8587: Internal notes:
                   8588: 
1.749     raeburn  8589:  access controls are stored in file_permissions.db as key=value pairs.
                   8590:     key -> path to file/file_name\0uniqueID:scope_end_start
                   8591:         where scope -> public,guest,course,group,domains or users.
                   8592:               end -> UNIX time for end of access (0 -> no end date)
                   8593:               start -> UNIX time for start of access
                   8594: 
                   8595:     value -> XML description of access control
                   8596:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   8597:             <start></start>
                   8598:             <end></end>
                   8599: 
                   8600:             <password></password>  for scope type = guest
                   8601: 
                   8602:             <domain></domain>     for scope type = course or group
                   8603:             <number></number>
                   8604:             <roles id="">
                   8605:              <role></role>
                   8606:              <access></access>
                   8607:              <section></section>
                   8608:              <group></group>
                   8609:             </roles>
                   8610: 
                   8611:             <dom></dom>         for scope type = domains
                   8612: 
                   8613:             <users>             for scope type = users
                   8614:              <user>
                   8615:               <uname></uname>
                   8616:               <udom></udom>
                   8617:              </user>
                   8618:             </users>
                   8619:            </scope> 
                   8620:               
                   8621:  Access data is also aggregated for each file in an additional key=value pair:
                   8622:  key -> path to file/file_name\0accesscontrol 
                   8623:  value -> reference to hash
                   8624:           hash contains key = value pairs
                   8625:           where key = uniqueID:scope_end_start
                   8626:                 value = UNIX time record was last updated
                   8627: 
                   8628:           Used to improve speed of look-ups of access controls for each file.  
                   8629:  
                   8630:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   8631: 
                   8632: modify_access_controls():
                   8633: 
                   8634: Modifies access controls for a portfolio file
                   8635: Args
                   8636: 1. file name
                   8637: 2. reference to hash of required changes,
                   8638: 3. domain
                   8639: 4. username
                   8640:   where domain,username are the domain of the portfolio owner 
                   8641:   (either a user or a course) 
                   8642: 
                   8643: Returns:
                   8644: 1. result of additions or updates ('ok' or 'error', with error message). 
                   8645: 2. result of deletions ('ok' or 'error', with error message).
                   8646: 3. reference to hash of any new or updated access controls.
                   8647: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   8648:    key = integer (inbound ID)
                   8649:    value = uniqueID  
1.747     albertel 8650: 
1.608     albertel 8651: =back
                   8652: 
1.243     albertel 8653: =head2 HTTP Helper Routines
                   8654: 
                   8655: =over 4
                   8656: 
1.191     harris41 8657: =item *
                   8658: 
                   8659: escape() : unpack non-word characters into CGI-compatible hex codes
                   8660: 
                   8661: =item *
                   8662: 
                   8663: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   8664: 
1.243     albertel 8665: =back
                   8666: 
                   8667: =head1 PRIVATE SUBROUTINES
                   8668: 
                   8669: =head2 Underlying communication routines (Shouldn't call)
                   8670: 
                   8671: =over 4
                   8672: 
                   8673: =item *
                   8674: 
                   8675: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   8676: 
                   8677: =item *
                   8678: 
                   8679: reply() : uses subreply to send a message to remote machine, logs all failures
                   8680: 
                   8681: =item *
                   8682: 
                   8683: critical() : passes a critical message to another server; if cannot
                   8684: get through then place message in connection buffer directory and
                   8685: returns con_delayed, if incapable of saving message, returns
                   8686: con_failed
                   8687: 
                   8688: =item *
                   8689: 
                   8690: reconlonc() : tries to reconnect lonc client processes.
                   8691: 
                   8692: =back
                   8693: 
                   8694: =head2 Resource Access Logging
                   8695: 
                   8696: =over 4
                   8697: 
                   8698: =item *
                   8699: 
                   8700: flushcourselogs() : flush (save) buffer logs and access logs
                   8701: 
                   8702: =item *
                   8703: 
                   8704: courselog($what) : save message for course in hash
                   8705: 
                   8706: =item *
                   8707: 
                   8708: courseacclog($what) : save message for course using &courselog().  Perform
                   8709: special processing for specific resource types (problems, exams, quizzes, etc).
                   8710: 
1.191     harris41 8711: =item *
                   8712: 
                   8713: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   8714: as a PerlChildExitHandler
1.243     albertel 8715: 
                   8716: =back
                   8717: 
                   8718: =head2 Other
                   8719: 
                   8720: =over 4
                   8721: 
                   8722: =item *
                   8723: 
                   8724: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 8725: 
                   8726: =back
                   8727: 
                   8728: =cut

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