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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.830   ! albertel    4: # $Id: lonnet.pm,v 1.829 2007/01/18 21:31:40 www 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.830   ! 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.830   ! 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.830   ! albertel  425:     open(my $env_file,$env{'user.environment'});
        !           426:     if (&timed_flock($env_file,LOCK_EX)
        !           427: 	&&
        !           428: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
        !           429: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  430: 	foreach my $key (keys(%disk_env)) {
                    431: 	    if ($key=~/^$delthis/) { 
1.619     albertel  432:                 delete($env{$key});
1.783     albertel  433:                 delete($disk_env{$key});
1.473     matthew   434:             }
1.448     albertel  435: 	}
1.783     albertel  436: 	untie(%disk_env);
1.5       www       437:     }
                    438:     return 'ok';
1.369     albertel  439: }
                    440: 
1.790     albertel  441: sub get_env_multiple {
                    442:     my ($name) = @_;
                    443:     my @values;
                    444:     if (defined($env{$name})) {
                    445:         # exists is it an array
                    446:         if (ref($env{$name})) {
                    447:             @values=@{ $env{$name} };
                    448:         } else {
                    449:             $values[0]=$env{$name};
                    450:         }
                    451:     }
                    452:     return(@values);
                    453: }
                    454: 
1.369     albertel  455: # ------------------------------------------ Find out current server userload
                    456: # there is a copy in lond
                    457: sub userload {
                    458:     my $numusers=0;
                    459:     {
                    460: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    461: 	my $filename;
                    462: 	my $curtime=time;
                    463: 	while ($filename=readdir(LONIDS)) {
                    464: 	    if ($filename eq '.' || $filename eq '..') {next;}
1.404     albertel  465: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  466: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  467: 	}
                    468: 	closedir(LONIDS);
                    469:     }
                    470:     my $userloadpercent=0;
                    471:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    472:     if ($maxuserload) {
1.371     albertel  473: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  474:     }
1.372     albertel  475:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  476:     return $userloadpercent;
1.283     www       477: }
                    478: 
                    479: # ------------------------------------------ Fight off request when overloaded
                    480: 
                    481: sub overloaderror {
                    482:     my ($r,$checkserver)=@_;
                    483:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
                    484:     my $loadavg;
                    485:     if ($checkserver eq $perlvar{'lonHostID'}) {
1.448     albertel  486:        open(my $loadfile,'/proc/loadavg');
1.283     www       487:        $loadavg=<$loadfile>;
                    488:        $loadavg =~ s/\s.*//g;
1.285     matthew   489:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448     albertel  490:        close($loadfile);
1.283     www       491:     } else {
                    492:        $loadavg=&reply('load',$checkserver);
                    493:     }
1.285     matthew   494:     my $overload=$loadavg-100;
1.283     www       495:     if ($overload>0) {
1.285     matthew   496: 	$r->err_headers_out->{'Retry-After'}=$overload;
1.283     www       497:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554     www       498:         return 413;
1.283     www       499:     }    
                    500:     return '';
1.5       www       501: }
1.1       albertel  502: 
                    503: # ------------------------------ Find server with least workload from spare.tab
1.11      www       504: 
1.1       albertel  505: sub spareserver {
1.670     albertel  506:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.784     albertel  507:     my $spare_server;
1.370     albertel  508:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  509:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    510:                                                      :  $userloadpercent;
                    511:     
                    512:     foreach my $try_server (@{ $spareid{'primary'} }) {
                    513: 	($spare_server, $lowest_load) =
                    514: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
                    515:     }
                    516: 
                    517:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    518: 
                    519:     if (!$found_server) {
                    520: 	foreach my $try_server (@{ $spareid{'default'} }) {
                    521: 	    ($spare_server, $lowest_load) =
                    522: 		&compare_server_load($try_server, $spare_server, $lowest_load);
                    523: 	}
                    524:     }
                    525: 
                    526:     if (!$want_server_name) {
                    527: 	$spare_server="http://$hostname{$spare_server}";
                    528:     }
                    529:     return $spare_server;
                    530: }
                    531: 
                    532: sub compare_server_load {
                    533:     my ($try_server, $spare_server, $lowest_load) = @_;
                    534: 
                    535:     my $loadans     = &reply('load',    $try_server);
                    536:     my $userloadans = &reply('userload',$try_server);
                    537: 
                    538:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
                    539: 	next; #didn't get a number from the server
                    540:     }
                    541: 
                    542:     my $load;
                    543:     if ($loadans =~ /\d/) {
                    544: 	if ($userloadans =~ /\d/) {
                    545: 	    #both are numbers, pick the bigger one
                    546: 	    $load = ($loadans > $userloadans) ? $loadans 
                    547: 		                              : $userloadans;
1.411     albertel  548: 	} else {
1.784     albertel  549: 	    $load = $loadans;
1.411     albertel  550: 	}
1.784     albertel  551:     } else {
                    552: 	$load = $userloadans;
                    553:     }
                    554: 
                    555:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    556: 	$spare_server = $try_server;
                    557: 	$lowest_load  = $load;
1.370     albertel  558:     }
1.784     albertel  559:     return ($spare_server,$lowest_load);
1.202     matthew   560: }
                    561: # --------------------------------------------- Try to change a user's password
                    562: 
                    563: sub changepass {
1.799     raeburn   564:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   565:     $currentpass = &escape($currentpass);
                    566:     $newpass     = &escape($newpass);
1.799     raeburn   567:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
1.202     matthew   568: 		       $server);
                    569:     if (! $answer) {
                    570: 	&logthis("No reply on password change request to $server ".
                    571: 		 "by $uname in domain $udom.");
                    572:     } elsif ($answer =~ "^ok") {
                    573:         &logthis("$uname in $udom successfully changed their password ".
                    574: 		 "on $server.");
                    575:     } elsif ($answer =~ "^pwchange_failure") {
                    576: 	&logthis("$uname in $udom was unable to change their password ".
                    577: 		 "on $server.  The action was blocked by either lcpasswd ".
                    578: 		 "or pwchange");
                    579:     } elsif ($answer =~ "^non_authorized") {
                    580:         &logthis("$uname in $udom did not get their password correct when ".
                    581: 		 "attempting to change it on $server.");
                    582:     } elsif ($answer =~ "^auth_mode_error") {
                    583:         &logthis("$uname in $udom attempted to change their password despite ".
                    584: 		 "not being locally or internally authenticated on $server.");
                    585:     } elsif ($answer =~ "^unknown_user") {
                    586:         &logthis("$uname in $udom attempted to change their password ".
                    587: 		 "on $server but were unable to because $server is not ".
                    588: 		 "their home server.");
                    589:     } elsif ($answer =~ "^refused") {
                    590: 	&logthis("$server refused to change $uname in $udom password because ".
                    591: 		 "it was sent an unencrypted request to change the password.");
                    592:     }
                    593:     return $answer;
1.1       albertel  594: }
                    595: 
1.169     harris41  596: # ----------------------- Try to determine user's current authentication scheme
                    597: 
                    598: sub queryauthenticate {
                    599:     my ($uname,$udom)=@_;
1.456     albertel  600:     my $uhome=&homeserver($uname,$udom);
                    601:     if (!$uhome) {
                    602: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                    603: 	return 'no_host';
                    604:     }
                    605:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                    606:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                    607: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41  608:     }
1.456     albertel  609:     return $answer;
1.169     harris41  610: }
                    611: 
1.1       albertel  612: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       613: 
1.1       albertel  614: sub authenticate {
                    615:     my ($uname,$upass,$udom)=@_;
1.807     albertel  616:     $upass=&escape($upass);
                    617:     $uname= &LONCAPA::clean_username($uname);
1.471     albertel  618:     my $uhome=&homeserver($uname,$udom);
                    619:     if (!$uhome) {
                    620: 	&logthis("User $uname at $udom is unknown in authenticate");
                    621: 	return 'no_host';
1.1       albertel  622:     }
1.471     albertel  623:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
                    624:     if ($answer eq 'authorized') {
                    625: 	&logthis("User $uname at $udom authorized by $uhome"); 
                    626: 	return $uhome; 
                    627:     }
                    628:     if ($answer eq 'non_authorized') {
                    629: 	&logthis("User $uname at $udom rejected by $uhome");
                    630: 	return 'no_host'; 
1.9       www       631:     }
1.471     albertel  632:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel  633:     return 'no_host';
                    634: }
                    635: 
                    636: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www       637: 
1.599     albertel  638: my %homecache;
1.1       albertel  639: sub homeserver {
1.230     stredwic  640:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel  641:     my $index="$uname:$udom";
1.426     albertel  642: 
1.599     albertel  643:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.1       albertel  644:     my $tryserver;
                    645:     foreach $tryserver (keys %libserv) {
1.230     stredwic  646:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic  647: 		 exists($badServerCache{$tryserver}));
1.1       albertel  648: 	if ($hostdom{$tryserver} eq $udom) {
                    649:            my $answer=reply("home:$udom:$uname",$tryserver);
                    650:            if ($answer eq 'found') { 
1.599     albertel  651: 	       return $homecache{$index}=$tryserver;
1.231     stredwic  652:            } elsif ($answer eq 'no_host') {
                    653: 	       $badServerCache{$tryserver}=1;
1.221     matthew   654:            }
1.1       albertel  655:        }
                    656:     }    
                    657:     return 'no_host';
1.70      www       658: }
                    659: 
                    660: # ------------------------------------- Find the usernames behind a list of IDs
                    661: 
                    662: sub idget {
                    663:     my ($udom,@ids)=@_;
                    664:     my %returnhash=();
                    665:     
                    666:     my $tryserver;
                    667:     foreach $tryserver (keys %libserv) {
                    668:        if ($hostdom{$tryserver} eq $udom) {
                    669: 	  my $idlist=join('&',@ids);
                    670:           $idlist=~tr/A-Z/a-z/; 
                    671: 	  my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                    672:           my @answer=();
1.76      www       673:           if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1.70      www       674: 	      @answer=split(/\&/,$reply);
                    675:           }                    ;
                    676:           my $i;
                    677:           for ($i=0;$i<=$#ids;$i++) {
                    678:               if ($answer[$i]) {
                    679: 		  $returnhash{$ids[$i]}=$answer[$i];
                    680:               } 
                    681:           }
                    682:        }
                    683:     }    
                    684:     return %returnhash;
                    685: }
                    686: 
                    687: # ------------------------------------- Find the IDs behind a list of usernames
                    688: 
                    689: sub idrget {
                    690:     my ($udom,@unames)=@_;
                    691:     my %returnhash=();
1.800     albertel  692:     foreach my $uname (@unames) {
                    693:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41  694:     }
1.70      www       695:     return %returnhash;
                    696: }
                    697: 
                    698: # ------------------------------- Store away a list of names and associated IDs
                    699: 
                    700: sub idput {
                    701:     my ($udom,%ids)=@_;
                    702:     my %servers=();
1.800     albertel  703:     foreach my $uname (keys(%ids)) {
                    704: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                    705:         my $uhom=&homeserver($uname,$udom);
1.70      www       706:         if ($uhom ne 'no_host') {
1.800     albertel  707:             my $id=&escape($ids{$uname});
1.70      www       708:             $id=~tr/A-Z/a-z/;
1.800     albertel  709:             my $esc_unam=&escape($uname);
1.70      www       710: 	    if ($servers{$uhom}) {
1.800     albertel  711: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www       712:             } else {
1.800     albertel  713:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www       714:             }
                    715:         }
1.191     harris41  716:     }
1.800     albertel  717:     foreach my $server (keys(%servers)) {
                    718:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41  719:     }
1.344     www       720: }
                    721: 
1.806     raeburn   722: # ------------------------------------------- get items from domain db files   
                    723: 
                    724: sub get_dom {
                    725:     my ($namespace,$storearr,$udom)=@_;
                    726:     my $items='';
                    727:     foreach my $item (@$storearr) {
                    728:         $items.=&escape($item).'&';
                    729:     }
                    730:     $items=~s/\&$//;
                    731:     if (!$udom) { $udom=$env{'user.domain'}; }
                    732:     if (exists($domain_primary{$udom})) {
                    733:         my $uhome=$domain_primary{$udom};
                    734:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
                    735:         my @pairs=split(/\&/,$rep);
                    736:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                    737:             return @pairs;
                    738:         }
                    739:         my %returnhash=();
                    740:         my $i=0;
                    741:         foreach my $item (@$storearr) {
                    742:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                    743:             $i++;
                    744:         }
                    745:         return %returnhash;
                    746:     } else {
                    747:         &logthis("get_dom failed - no primary domain server for $udom");
                    748:     }
                    749: }
                    750: 
                    751: # -------------------------------------------- put items in domain db files 
                    752: 
                    753: sub put_dom {
                    754:     my ($namespace,$storehash,$udom)=@_;
                    755:     if (!$udom) { $udom=$env{'user.domain'}; }
                    756:     if (exists($domain_primary{$udom})) {
                    757:         my $uhome=$domain_primary{$udom};
                    758:         my $items='';
                    759:         foreach my $item (keys(%$storehash)) {
                    760:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                    761:         }
                    762:         $items=~s/\&$//;
                    763:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                    764:     } else {
                    765:         &logthis("put_dom failed - no primary domain server for $udom");
                    766:     }
                    767: }
                    768: 
1.344     www       769: # --------------------------------------------------- Assign a key to a student
                    770: 
                    771: sub assign_access_key {
1.364     www       772: #
                    773: # a valid key looks like uname:udom#comments
                    774: # comments are being appended
                    775: #
1.498     www       776:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                    777:     $kdom=
1.620     albertel  778:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www       779:     $knum=
1.620     albertel  780:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www       781:     $cdom=
1.620     albertel  782:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       783:     $cnum=
1.620     albertel  784:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    785:     $udom=$env{'user.name'} unless (defined($udom));
                    786:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www       787:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www       788:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel  789:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www       790:                                                   # assigned to this person
                    791:                                                   # - this should not happen,
1.345     www       792:                                                   # unless something went wrong
                    793:                                                   # the first time around
                    794: # ready to assign
1.364     www       795:         $logentry=$1.'; '.$logentry;
1.496     www       796:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www       797:                                                  $kdom,$knum) eq 'ok') {
1.345     www       798: # key now belongs to user
1.346     www       799: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www       800:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
                    801:                 &appenv('environment.'.$envkey => $ckey);
                    802:                 return 'ok';
                    803:             } else {
                    804:                 return 
                    805:   'error: Count not permanently assign key, will need to be re-entered later.';
                    806: 	    }
                    807:         } else {
                    808:             return 'error: Could not assign key, try again later.';
                    809:         }
1.364     www       810:     } elsif (!$existing{$ckey}) {
1.345     www       811: # the key does not exist
                    812: 	return 'error: The key does not exist';
                    813:     } else {
                    814: # the key is somebody else's
                    815: 	return 'error: The key is already in use';
                    816:     }
1.344     www       817: }
                    818: 
1.364     www       819: # ------------------------------------------ put an additional comment on a key
                    820: 
                    821: sub comment_access_key {
                    822: #
                    823: # a valid key looks like uname:udom#comments
                    824: # comments are being appended
                    825: #
                    826:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                    827:     $cdom=
1.620     albertel  828:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www       829:     $cnum=
1.620     albertel  830:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www       831:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                    832:     if ($existing{$ckey}) {
                    833:         $existing{$ckey}.='; '.$logentry;
                    834: # ready to assign
1.367     www       835:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www       836:                                                  $cdom,$cnum) eq 'ok') {
                    837: 	    return 'ok';
                    838:         } else {
                    839: 	    return 'error: Count not store comment.';
                    840:         }
                    841:     } else {
                    842: # the key does not exist
                    843: 	return 'error: The key does not exist';
                    844:     }
                    845: }
                    846: 
1.344     www       847: # ------------------------------------------------------ Generate a set of keys
                    848: 
                    849: sub generate_access_keys {
1.364     www       850:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www       851:     $cdom=
1.620     albertel  852:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       853:     $cnum=
1.620     albertel  854:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www       855:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www       856:     unless (($cdom) && ($cnum)) { return 0; }
                    857:     if ($number>10000) { return 0; }
                    858:     sleep(2); # make sure don't get same seed twice
                    859:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                    860:     my $total=0;
                    861:     for (my $i=1;$i<=$number;$i++) {
                    862:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                    863:                   sprintf("%lx",int(100000*rand)).'-'.
                    864:                   sprintf("%lx",int(100000*rand));
                    865:        $newkey=~s/1/g/g; # folks mix up 1 and l
                    866:        $newkey=~s/0/h/g; # and also 0 and O
                    867:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                    868:        if ($existing{$newkey}) {
                    869:            $i--;
                    870:        } else {
1.364     www       871: 	  if (&put('accesskeys',
                    872:               { $newkey => '# generated '.localtime().
1.620     albertel  873:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www       874:                            '; '.$logentry },
                    875: 		   $cdom,$cnum) eq 'ok') {
1.344     www       876:               $total++;
                    877: 	  }
                    878:        }
                    879:     }
1.620     albertel  880:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www       881:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                    882:     return $total;
                    883: }
                    884: 
                    885: # ------------------------------------------------------- Validate an accesskey
                    886: 
                    887: sub validate_access_key {
                    888:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                    889:     $cdom=
1.620     albertel  890:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       891:     $cnum=
1.620     albertel  892:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    893:     $udom=$env{'user.domain'} unless (defined($udom));
                    894:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www       895:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel  896:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www       897: }
                    898: 
                    899: # ------------------------------------- Find the section of student in a course
1.652     albertel  900: sub devalidate_getsection_cache {
                    901:     my ($udom,$unam,$courseid)=@_;
                    902:     my $hashid="$udom:$unam:$courseid";
                    903:     &devalidate_cache_new('getsection',$hashid);
                    904: }
1.298     matthew   905: 
1.815     albertel  906: sub courseid_to_courseurl {
                    907:     my ($courseid) = @_;
                    908:     #already url style courseid
                    909:     return $courseid if ($courseid =~ m{^/});
                    910: 
                    911:     if (exists($env{'course.'.$courseid.'.num'})) {
                    912: 	my $cnum = $env{'course.'.$courseid.'.num'};
                    913: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                    914: 	return "/$cdom/$cnum";
                    915:     }
                    916: 
                    917:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                    918:     if (exists($courseinfo{'num'})) {
                    919: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                    920:     }
                    921: 
                    922:     return undef;
                    923: }
                    924: 
1.298     matthew   925: sub getsection {
                    926:     my ($udom,$unam,$courseid)=@_;
1.599     albertel  927:     my $cachetime=1800;
1.551     albertel  928: 
                    929:     my $hashid="$udom:$unam:$courseid";
1.599     albertel  930:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel  931:     if (defined($cached)) { return $result; }
                    932: 
1.298     matthew   933:     my %Pending; 
                    934:     my %Expired;
                    935:     #
                    936:     # Each role can either have not started yet (pending), be active, 
                    937:     #    or have expired.
                    938:     #
                    939:     # If there is an active role, we are done.
                    940:     #
                    941:     # If there is more than one role which has not started yet, 
                    942:     #     choose the one which will start sooner
                    943:     # If there is one role which has not started yet, return it.
                    944:     #
                    945:     # If there is more than one expired role, choose the one which ended last.
                    946:     # If there is a role which has expired, return it.
                    947:     #
1.815     albertel  948:     $courseid = &courseid_to_courseurl($courseid);
1.817     raeburn   949:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
                    950:     foreach my $key (keys(%roleshash)) {
1.479     albertel  951:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew   952:         my $section=$1;
                    953:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn   954:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew   955:         my $now=time;
1.548     albertel  956:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew   957:             $Expired{$end}=$section;
                    958:             next;
                    959:         }
1.548     albertel  960:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew   961:             $Pending{$start}=$section;
                    962:             next;
                    963:         }
1.599     albertel  964:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew   965:     }
                    966:     #
                    967:     # Presumedly there will be few matching roles from the above
                    968:     # loop and the sorting time will be negligible.
                    969:     if (scalar(keys(%Pending))) {
                    970:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel  971:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew   972:     } 
                    973:     if (scalar(keys(%Expired))) {
                    974:         my @sorted = sort {$a <=> $b} keys(%Expired);
                    975:         my $time = pop(@sorted);
1.599     albertel  976:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew   977:     }
1.599     albertel  978:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew   979: }
1.70      www       980: 
1.599     albertel  981: sub save_cache {
                    982:     &purge_remembered();
1.722     albertel  983:     #&Apache::loncommon::validate_page();
1.620     albertel  984:     undef(%env);
1.780     albertel  985:     undef($env_loaded);
1.599     albertel  986: }
1.452     albertel  987: 
1.599     albertel  988: my $to_remember=-1;
                    989: my %remembered;
                    990: my %accessed;
                    991: my $kicks=0;
                    992: my $hits=0;
                    993: sub devalidate_cache_new {
                    994:     my ($name,$id,$debug) = @_;
                    995:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
                    996:     $id=&escape($name.':'.$id);
                    997:     $memcache->delete($id);
                    998:     delete($remembered{$id});
                    999:     delete($accessed{$id});
                   1000: }
                   1001: 
                   1002: sub is_cached_new {
                   1003:     my ($name,$id,$debug) = @_;
                   1004:     $id=&escape($name.':'.$id);
                   1005:     if (exists($remembered{$id})) {
                   1006: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                   1007: 	$accessed{$id}=[&gettimeofday()];
                   1008: 	$hits++;
                   1009: 	return ($remembered{$id},1);
                   1010:     }
                   1011:     my $value = $memcache->get($id);
                   1012:     if (!(defined($value))) {
                   1013: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 1014: 	return (undef,undef);
1.416     albertel 1015:     }
1.599     albertel 1016:     if ($value eq '__undef__') {
                   1017: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   1018: 	$value=undef;
                   1019:     }
                   1020:     &make_room($id,$value,$debug);
                   1021:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   1022:     return ($value,1);
                   1023: }
                   1024: 
                   1025: sub do_cache_new {
                   1026:     my ($name,$id,$value,$time,$debug) = @_;
                   1027:     $id=&escape($name.':'.$id);
                   1028:     my $setvalue=$value;
                   1029:     if (!defined($setvalue)) {
                   1030: 	$setvalue='__undef__';
                   1031:     }
1.623     albertel 1032:     if (!defined($time) ) {
                   1033: 	$time=600;
                   1034:     }
1.599     albertel 1035:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.600     albertel 1036:     $memcache->set($id,$setvalue,$time);
                   1037:     # need to make a copy of $value
                   1038:     #&make_room($id,$value,$debug);
1.599     albertel 1039:     return $value;
                   1040: }
                   1041: 
                   1042: sub make_room {
                   1043:     my ($id,$value,$debug)=@_;
                   1044:     $remembered{$id}=$value;
                   1045:     if ($to_remember<0) { return; }
                   1046:     $accessed{$id}=[&gettimeofday()];
                   1047:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   1048:     my $to_kick;
                   1049:     my $max_time=0;
                   1050:     foreach my $other (keys(%accessed)) {
                   1051: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   1052: 	    $to_kick=$other;
                   1053: 	    $max_time=&tv_interval($accessed{$other});
                   1054: 	}
                   1055:     }
                   1056:     delete($remembered{$to_kick});
                   1057:     delete($accessed{$to_kick});
                   1058:     $kicks++;
                   1059:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 1060:     return;
                   1061: }
                   1062: 
1.599     albertel 1063: sub purge_remembered {
1.604     albertel 1064:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   1065:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 1066:     undef(%remembered);
                   1067:     undef(%accessed);
1.428     albertel 1068: }
1.70      www      1069: # ------------------------------------- Read an entry from a user's environment
                   1070: 
                   1071: sub userenvironment {
                   1072:     my ($udom,$unam,@what)=@_;
                   1073:     my %returnhash=();
                   1074:     my @answer=split(/\&/,
                   1075:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
                   1076:                       &homeserver($unam,$udom)));
                   1077:     my $i;
                   1078:     for ($i=0;$i<=$#what;$i++) {
                   1079: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                   1080:     }
                   1081:     return %returnhash;
1.1       albertel 1082: }
                   1083: 
1.617     albertel 1084: # ---------------------------------------------------------- Get a studentphoto
                   1085: sub studentphoto {
                   1086:     my ($udom,$unam,$ext) = @_;
                   1087:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1088:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1089:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1090:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1091:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1092:             } else {
                   1093:                 my ($result,$perm_reqd)=
1.707     albertel 1094: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1095:                 if ($result eq 'ok') {
                   1096:                     if (!($perm_reqd eq 'yes')) {
                   1097:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1098:                     }
                   1099:                 }
                   1100:             }
                   1101:         }
                   1102:     } else {
                   1103:         my ($result,$perm_reqd) = 
1.707     albertel 1104: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1105:         if ($result eq 'ok') {
                   1106:             if (!($perm_reqd eq 'yes')) {
                   1107:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1108:             }
                   1109:         }
                   1110:     }
                   1111:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1112: }
                   1113: 
                   1114: sub retrievestudentphoto {
                   1115:     my ($udom,$unam,$ext,$type) = @_;
                   1116:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1117:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1118:     if ($ret eq 'ok') {
                   1119:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1120:         if ($type eq 'thumbnail') {
                   1121:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1122:         }
                   1123:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1124:         return $tokenurl;
                   1125:     } else {
                   1126:         if ($type eq 'thumbnail') {
                   1127:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1128:         } else { 
                   1129:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1130:         }
1.617     albertel 1131:     }
                   1132: }
                   1133: 
1.263     www      1134: # -------------------------------------------------------------------- New chat
                   1135: 
                   1136: sub chatsend {
1.724     raeburn  1137:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1138:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1139:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1140:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1141:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1142: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1143: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1144: }
                   1145: 
                   1146: # ------------------------------------------ Find current version of a resource
                   1147: 
                   1148: sub getversion {
                   1149:     my $fname=&clutter(shift);
                   1150:     unless ($fname=~/^\/res\//) { return -1; }
                   1151:     return &currentversion(&filelocation('',$fname));
                   1152: }
                   1153: 
                   1154: sub currentversion {
                   1155:     my $fname=shift;
1.599     albertel 1156:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1157:     if (defined($cached)) { return $result; }
1.292     www      1158:     my $author=$fname;
                   1159:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1160:     my ($udom,$uname)=split(/\//,$author);
                   1161:     my $home=homeserver($uname,$udom);
                   1162:     if ($home eq 'no_host') { 
                   1163:         return -1; 
                   1164:     }
                   1165:     my $answer=reply("currentversion:$fname",$home);
                   1166:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1167: 	return -1;
                   1168:     }
1.599     albertel 1169:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1170: }
                   1171: 
1.1       albertel 1172: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1173: 
1.1       albertel 1174: sub subscribe {
                   1175:     my $fname=shift;
1.761     raeburn  1176:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1177:     $fname=~s/[\n\r]//g;
1.1       albertel 1178:     my $author=$fname;
                   1179:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1180:     my ($udom,$uname)=split(/\//,$author);
                   1181:     my $home=homeserver($uname,$udom);
1.335     albertel 1182:     if ($home eq 'no_host') {
                   1183:         return 'not_found';
1.1       albertel 1184:     }
                   1185:     my $answer=reply("sub:$fname",$home);
1.64      www      1186:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1187: 	$answer.=' by '.$home;
                   1188:     }
1.1       albertel 1189:     return $answer;
                   1190: }
                   1191:     
1.8       www      1192: # -------------------------------------------------------------- Replicate file
                   1193: 
                   1194: sub repcopy {
                   1195:     my $filename=shift;
1.23      www      1196:     $filename=~s/\/+/\//g;
1.607     raeburn  1197:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1198:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1199:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1200: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1201: 	return &repcopy_userfile($filename);
                   1202:     }
1.532     albertel 1203:     $filename=~s/[\n\r]//g;
1.8       www      1204:     my $transname="$filename.in.transfer";
1.828     www      1205: # FIXME: this should flock
1.607     raeburn  1206:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1207:     my $remoteurl=subscribe($filename);
1.64      www      1208:     if ($remoteurl =~ /^con_lost by/) {
                   1209: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1210:            return 'unavailable';
1.8       www      1211:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1212: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1213: 	   return 'not_found';
1.64      www      1214:     } elsif ($remoteurl =~ /^rejected by/) {
                   1215: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1216:            return 'forbidden';
1.20      www      1217:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1218:            return 'ok';
1.8       www      1219:     } else {
1.290     www      1220:         my $author=$filename;
                   1221:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1222:         my ($udom,$uname)=split(/\//,$author);
                   1223:         my $home=homeserver($uname,$udom);
                   1224:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1225:            my @parts=split(/\//,$filename);
                   1226:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1227:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1228:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1229: 	       return 'bad_request';
1.8       www      1230:            }
                   1231:            my $count;
                   1232:            for ($count=5;$count<$#parts;$count++) {
                   1233:                $path.="/$parts[$count]";
                   1234:                if ((-e $path)!=1) {
                   1235: 		   mkdir($path,0777);
                   1236:                }
                   1237:            }
                   1238:            my $ua=new LWP::UserAgent;
                   1239:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1240:            my $response=$ua->request($request,$transname);
                   1241:            if ($response->is_error()) {
                   1242: 	       unlink($transname);
                   1243:                my $message=$response->status_line;
1.672     albertel 1244:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      1245:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1246:                return 'unavailable';
1.8       www      1247:            } else {
1.16      www      1248: 	       if ($remoteurl!~/\.meta$/) {
                   1249:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1250:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1251:                   if ($mresponse->is_error()) {
                   1252: 		      unlink($filename.'.meta');
                   1253:                       &logthis(
1.672     albertel 1254:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      1255:                   }
                   1256: 	       }
1.8       www      1257:                rename($transname,$filename);
1.607     raeburn  1258:                return 'ok';
1.8       www      1259:            }
1.290     www      1260:        }
1.8       www      1261:     }
1.330     www      1262: }
                   1263: 
                   1264: # ------------------------------------------------ Get server side include body
                   1265: sub ssi_body {
1.381     albertel 1266:     my ($filelink,%form)=@_;
1.606     matthew  1267:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1268:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1269:     }
1.330     www      1270:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
1.381     albertel 1271:                                      &ssi($filelink,%form));
1.778     albertel 1272:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1273:     $output=~s/^.*?\<body[^\>]*\>//si;
                   1274:     $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
1.330     www      1275:     return $output;
1.8       www      1276: }
                   1277: 
1.15      www      1278: # --------------------------------------------------------- Server Side Include
                   1279: 
1.782     albertel 1280: sub absolute_url {
                   1281:     my ($host_name) = @_;
                   1282:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   1283:     if ($host_name eq '') {
                   1284: 	$host_name = $ENV{'SERVER_NAME'};
                   1285:     }
                   1286:     return $protocol.$host_name;
                   1287: }
                   1288: 
1.15      www      1289: sub ssi {
                   1290: 
1.23      www      1291:     my ($fn,%form)=@_;
1.15      www      1292: 
                   1293:     my $ua=new LWP::UserAgent;
1.23      www      1294:     
                   1295:     my $request;
1.711     albertel 1296: 
                   1297:     $form{'no_update_last_known'}=1;
                   1298: 
1.23      www      1299:     if (%form) {
1.782     albertel 1300:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.201     albertel 1301:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www      1302:     } else {
1.782     albertel 1303:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      1304:     }
                   1305: 
1.15      www      1306:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1307:     my $response=$ua->request($request);
                   1308: 
1.324     www      1309:     return $response->content;
                   1310: }
                   1311: 
                   1312: sub externalssi {
                   1313:     my ($url)=@_;
                   1314:     my $ua=new LWP::UserAgent;
                   1315:     my $request=new HTTP::Request('GET',$url);
                   1316:     my $response=$ua->request($request);
1.15      www      1317:     return $response->content;
                   1318: }
1.254     www      1319: 
1.492     albertel 1320: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1321: 
                   1322: sub allowuploaded {
                   1323:     my ($srcurl,$url)=@_;
                   1324:     $url=&clutter(&declutter($url));
                   1325:     my $dir=$url;
                   1326:     $dir=~s/\/[^\/]+$//;
                   1327:     my %httpref=();
                   1328:     my $httpurl=&hreflocation('',$url);
                   1329:     $httpref{'httpref.'.$httpurl}=$srcurl;
                   1330:     &Apache::lonnet::appenv(%httpref);
1.254     www      1331: }
1.477     raeburn  1332: 
1.478     albertel 1333: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 1334: # input: action, courseID, current domain, intended
1.637     raeburn  1335: #        path to file, source of file, instruction to parse file for objects,
                   1336: #        ref to hash for embedded objects,
                   1337: #        ref to hash for codebase of java objects.
                   1338: #
1.485     raeburn  1339: # output: url to file (if action was uploaddoc), 
                   1340: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  1341: #
1.478     albertel 1342: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   1343: # course.
1.477     raeburn  1344: #
1.478     albertel 1345: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1346: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   1347: #          course's home server.
1.477     raeburn  1348: #
1.478     albertel 1349: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   1350: #          be copied from $source (current location) to 
                   1351: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1352: #         and will then be copied to
                   1353: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   1354: #         course's home server.
1.485     raeburn  1355: #
1.481     raeburn  1356: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 1357: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  1358: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1359: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   1360: #         in course's home server.
1.637     raeburn  1361: #
1.477     raeburn  1362: 
                   1363: sub process_coursefile {
1.638     albertel 1364:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  1365:     my $fetchresult;
1.638     albertel 1366:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  1367:     if ($action eq 'propagate') {
1.638     albertel 1368:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1369: 			     $home);
1.481     raeburn  1370:     } else {
1.477     raeburn  1371:         my $fpath = '';
                   1372:         my $fname = $file;
1.478     albertel 1373:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  1374:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  1375:         my $filepath = &build_filepath($fpath);
1.481     raeburn  1376:         if ($action eq 'copy') {
                   1377:             if ($source eq '') {
                   1378:                 $fetchresult = 'no source file';
                   1379:                 return $fetchresult;
                   1380:             } else {
                   1381:                 my $destination = $filepath.'/'.$fname;
                   1382:                 rename($source,$destination);
                   1383:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1384:                                  $home);
1.481     raeburn  1385:             }
                   1386:         } elsif ($action eq 'uploaddoc') {
                   1387:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 1388:             print $fh $env{'form.'.$source};
1.481     raeburn  1389:             close($fh);
1.637     raeburn  1390:             if ($parser eq 'parse') {
                   1391:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
                   1392:                 unless ($parse_result eq 'ok') {
                   1393:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   1394:                 }
                   1395:             }
1.477     raeburn  1396:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1397:                                  $home);
1.481     raeburn  1398:             if ($fetchresult eq 'ok') {
                   1399:                 return '/uploaded/'.$fpath.'/'.$fname;
                   1400:             } else {
                   1401:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1402:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  1403:                 return '/adm/notfound.html';
                   1404:             }
1.477     raeburn  1405:         }
                   1406:     }
1.485     raeburn  1407:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  1408:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1409:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  1410:     }
                   1411:     return $fetchresult;
                   1412: }
                   1413: 
1.637     raeburn  1414: sub build_filepath {
                   1415:     my ($fpath) = @_;
                   1416:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   1417:     unless ($fpath eq '') {
                   1418:         my @parts=split('/',$fpath);
                   1419:         foreach my $part (@parts) {
                   1420:             $filepath.= '/'.$part;
                   1421:             if ((-e $filepath)!=1) {
                   1422:                 mkdir($filepath,0777);
                   1423:             }
                   1424:         }
                   1425:     }
                   1426:     return $filepath;
                   1427: }
                   1428: 
                   1429: sub store_edited_file {
1.638     albertel 1430:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  1431:     my $file = $primary_url;
                   1432:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   1433:     my $fpath = '';
                   1434:     my $fname = $file;
                   1435:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   1436:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   1437:     my $filepath = &build_filepath($fpath);
                   1438:     open(my $fh,'>'.$filepath.'/'.$fname);
                   1439:     print $fh $content;
                   1440:     close($fh);
1.638     albertel 1441:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  1442:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1443: 			  $home);
1.637     raeburn  1444:     if ($$fetchresult eq 'ok') {
                   1445:         return '/uploaded/'.$fpath.'/'.$fname;
                   1446:     } else {
1.638     albertel 1447:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   1448: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  1449:         return '/adm/notfound.html';
                   1450:     }
                   1451: }
                   1452: 
1.531     albertel 1453: sub clean_filename {
                   1454:     my ($fname)=@_;
1.315     www      1455: # Replace Windows backslashes by forward slashes
1.257     www      1456:     $fname=~s/\\/\//g;
1.315     www      1457: # Get rid of everything but the actual filename
1.257     www      1458:     $fname=~s/^.*\/([^\/]+)$/$1/;
1.315     www      1459: # Replace spaces by underscores
                   1460:     $fname=~s/\s+/\_/g;
                   1461: # Replace all other weird characters by nothing
1.317     www      1462:     $fname=~s/[^\w\.\-]//g;
1.540     albertel 1463: # Replace all .\d. sequences with _\d. so they no longer look like version
                   1464: # numbers
                   1465:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 1466:     return $fname;
                   1467: }
                   1468: 
1.608     albertel 1469: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 1470: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 1471: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 1472: #        $coursedoc - if true up to the current course
                   1473: #                     if false
                   1474: #        $subdir - directory in userfile to store the file into
                   1475: #        $parser, $allfiles, $codebase - unknown
                   1476: #
                   1477: # output: url of file in userspace, or error: <message> 
                   1478: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 1479: 
                   1480: 
1.531     albertel 1481: sub userfileupload {
1.719     banghart 1482:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,$destudom)=@_;
1.531     albertel 1483:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 1484:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 1485:     $fname=&clean_filename($fname);
1.315     www      1486: # See if there is anything left
1.257     www      1487:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 1488:     chop($env{'form.'.$formname});
1.523     raeburn  1489:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   1490:         my $now = time;
                   1491:         my $filepath = 'tmp/helprequests/'.$now;
                   1492:         my @parts=split(/\//,$filepath);
                   1493:         my $fullpath = $perlvar{'lonDaemons'};
                   1494:         for (my $i=0;$i<@parts;$i++) {
                   1495:             $fullpath .= '/'.$parts[$i];
                   1496:             if ((-e $fullpath)!=1) {
                   1497:                 mkdir($fullpath,0777);
                   1498:             }
                   1499:         }
                   1500:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 1501:         print $fh $env{'form.'.$formname};
1.523     raeburn  1502:         close($fh);
1.741     raeburn  1503:         return $fullpath.'/'.$fname;
                   1504:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   1505:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   1506:                        '_'.$env{'user.domain'}.'/pending';
                   1507:         my @parts=split(/\//,$filepath);
                   1508:         my $fullpath = $perlvar{'lonDaemons'};
                   1509:         for (my $i=0;$i<@parts;$i++) {
                   1510:             $fullpath .= '/'.$parts[$i];
                   1511:             if ((-e $fullpath)!=1) {
                   1512:                 mkdir($fullpath,0777);
                   1513:             }
                   1514:         }
                   1515:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   1516:         print $fh $env{'form.'.$formname};
                   1517:         close($fh);
                   1518:         return $fullpath.'/'.$fname;
1.523     raeburn  1519:     }
1.719     banghart 1520:     
1.258     www      1521: # Create the directory if not present
1.493     albertel 1522:     $fname="$subdir/$fname";
1.259     www      1523:     if ($coursedoc) {
1.638     albertel 1524: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1525: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  1526:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 1527:             return &finishuserfileupload($docuname,$docudom,
                   1528: 					 $formname,$fname,$parser,$allfiles,
                   1529: 					 $codebase);
1.481     raeburn  1530:         } else {
1.620     albertel 1531:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 1532:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   1533: 				       $fname,$formname,$parser,
                   1534: 				       $allfiles,$codebase);
1.481     raeburn  1535:         }
1.719     banghart 1536:     } elsif (defined($destuname)) {
                   1537:         my $docuname=$destuname;
                   1538:         my $docudom=$destudom;
                   1539: 	return &finishuserfileupload($docuname,$docudom,$formname,
                   1540: 				     $fname,$parser,$allfiles,$codebase);
                   1541:         
1.259     www      1542:     } else {
1.638     albertel 1543:         my $docuname=$env{'user.name'};
                   1544:         my $docudom=$env{'user.domain'};
1.714     raeburn  1545:         if (exists($env{'form.group'})) {
                   1546:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1547:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1548:         }
1.638     albertel 1549: 	return &finishuserfileupload($docuname,$docudom,$formname,
                   1550: 				     $fname,$parser,$allfiles,$codebase);
1.259     www      1551:     }
1.271     www      1552: }
                   1553: 
                   1554: sub finishuserfileupload {
1.638     albertel 1555:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase) = @_;
1.477     raeburn  1556:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      1557:     my $filepath=$perlvar{'lonDocRoot'};
1.494     albertel 1558:     my ($fnamepath,$file);
                   1559:     $file=$fname;
                   1560:     if ($fname=~m|/|) {
                   1561:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   1562: 	$path.=$fnamepath.'/';
                   1563:     }
1.259     www      1564:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      1565:     my $count;
                   1566:     for ($count=4;$count<=$#parts;$count++) {
                   1567:         $filepath.="/$parts[$count]";
                   1568:         if ((-e $filepath)!=1) {
                   1569: 	    mkdir($filepath,0777);
                   1570:         }
                   1571:     }
                   1572: # Save the file
                   1573:     {
1.701     albertel 1574: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   1575: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   1576: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   1577: 	    return '/adm/notfound.html';
                   1578: 	}
                   1579: 	if (!print FH ($env{'form.'.$formname})) {
                   1580: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   1581: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   1582: 	    return '/adm/notfound.html';
                   1583: 	}
1.570     albertel 1584: 	close(FH);
1.258     www      1585:     }
1.637     raeburn  1586:     if ($parser eq 'parse') {
1.638     albertel 1587:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
                   1588: 						   $codebase);
1.637     raeburn  1589:         unless ($parse_result eq 'ok') {
1.638     albertel 1590:             &logthis('Failed to parse '.$filepath.$file.
                   1591: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  1592:         }
                   1593:     }
1.259     www      1594: # Notify homeserver to grep it
                   1595: #
1.638     albertel 1596:     my $docuhome=&homeserver($docuname,$docudom);
1.494     albertel 1597:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      1598:     if ($fetchresult eq 'ok') {
1.259     www      1599: #
1.258     www      1600: # Return the URL to it
1.494     albertel 1601:         return '/uploaded/'.$path.$file;
1.263     www      1602:     } else {
1.494     albertel 1603:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   1604: 		 ': '.$fetchresult);
1.263     www      1605:         return '/adm/notfound.html';
                   1606:     }    
1.493     albertel 1607: }
                   1608: 
1.637     raeburn  1609: sub extract_embedded_items {
1.648     raeburn  1610:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
1.637     raeburn  1611:     my @state = ();
                   1612:     my %javafiles = (
                   1613:                       codebase => '',
                   1614:                       code => '',
                   1615:                       archive => ''
                   1616:                     );
                   1617:     my %mediafiles = (
                   1618:                       src => '',
                   1619:                       movie => '',
                   1620:                      );
1.648     raeburn  1621:     my $p;
                   1622:     if ($content) {
                   1623:         $p = HTML::LCParser->new($content);
                   1624:     } else {
                   1625:         $p = HTML::LCParser->new($filepath.'/'.$file);
                   1626:     }
1.641     albertel 1627:     while (my $t=$p->get_token()) {
1.640     albertel 1628: 	if ($t->[0] eq 'S') {
                   1629: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
                   1630: 	    push (@state, $tagname);
1.648     raeburn  1631:             if (lc($tagname) eq 'allow') {
                   1632:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   1633:             }
1.640     albertel 1634: 	    if (lc($tagname) eq 'img') {
                   1635: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   1636: 	    }
1.645     raeburn  1637:             if (lc($tagname) eq 'script') {
                   1638:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   1639:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   1640:                 } else {
                   1641:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   1642:                 }
                   1643:             }
                   1644:             if (lc($tagname) eq 'link') {
                   1645:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   1646:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   1647:                 }
                   1648:             }
1.640     albertel 1649: 	    if (lc($tagname) eq 'object' ||
                   1650: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   1651: 		foreach my $item (keys(%javafiles)) {
                   1652: 		    $javafiles{$item} = '';
                   1653: 		}
                   1654: 	    }
                   1655: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   1656: 		my $name = lc($attr->{'name'});
                   1657: 		foreach my $item (keys(%javafiles)) {
                   1658: 		    if ($name eq $item) {
                   1659: 			$javafiles{$item} = $attr->{'value'};
                   1660: 			last;
                   1661: 		    }
                   1662: 		}
                   1663: 		foreach my $item (keys(%mediafiles)) {
                   1664: 		    if ($name eq $item) {
                   1665: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   1666: 			last;
                   1667: 		    }
                   1668: 		}
                   1669: 	    }
                   1670: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   1671: 		foreach my $item (keys(%javafiles)) {
                   1672: 		    if ($attr->{$item}) {
                   1673: 			$javafiles{$item} = $attr->{$item};
                   1674: 			last;
                   1675: 		    }
                   1676: 		}
                   1677: 		foreach my $item (keys(%mediafiles)) {
                   1678: 		    if ($attr->{$item}) {
                   1679: 			&add_filetype($allfiles,$attr->{$item},$item);
                   1680: 			last;
                   1681: 		    }
                   1682: 		}
                   1683: 	    }
                   1684: 	} elsif ($t->[0] eq 'E') {
                   1685: 	    my ($tagname) = ($t->[1]);
                   1686: 	    if ($javafiles{'codebase'} ne '') {
                   1687: 		$javafiles{'codebase'} .= '/';
                   1688: 	    }  
                   1689: 	    if (lc($tagname) eq 'applet' ||
                   1690: 		lc($tagname) eq 'object' ||
                   1691: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   1692: 		) {
                   1693: 		foreach my $item (keys(%javafiles)) {
                   1694: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   1695: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   1696: 			&add_filetype($allfiles,$file,$item);
                   1697: 		    }
                   1698: 		}
                   1699: 	    } 
                   1700: 	    pop @state;
                   1701: 	}
                   1702:     }
1.637     raeburn  1703:     return 'ok';
                   1704: }
                   1705: 
1.639     albertel 1706: sub add_filetype {
                   1707:     my ($allfiles,$file,$type)=@_;
                   1708:     if (exists($allfiles->{$file})) {
                   1709: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   1710: 	    push(@{$allfiles->{$file}}, &escape($type));
                   1711: 	}
                   1712:     } else {
                   1713: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  1714:     }
                   1715: }
                   1716: 
1.493     albertel 1717: sub removeuploadedurl {
                   1718:     my ($url)=@_;
                   1719:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613     albertel 1720:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 1721: }
                   1722: 
                   1723: sub removeuserfile {
                   1724:     my ($docuname,$docudom,$fname)=@_;
                   1725:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  1726:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
                   1727:     if ($result eq 'ok') {
                   1728:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   1729:             my $metafile = $fname.'.meta';
                   1730:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 1731: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
                   1732:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  1733:             my $sqlresult = 
1.823     albertel 1734:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  1735:                                         'portfolio_metadata',$group,
                   1736:                                         'delete');
1.798     raeburn  1737:         }
                   1738:     }
                   1739:     return $result;
1.257     www      1740: }
1.15      www      1741: 
1.530     albertel 1742: sub mkdiruserfile {
                   1743:     my ($docuname,$docudom,$dir)=@_;
                   1744:     my $home=&homeserver($docuname,$docudom);
                   1745:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   1746: }
                   1747: 
1.531     albertel 1748: sub renameuserfile {
                   1749:     my ($docuname,$docudom,$old,$new)=@_;
                   1750:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  1751:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   1752:                         &escape("$old").':'.&escape("$new"),$home);
                   1753:     if ($result eq 'ok') {
                   1754:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   1755:             my $oldmeta = $old.'.meta';
                   1756:             my $newmeta = $new.'.meta';
                   1757:             my $metaresult = 
                   1758:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 1759: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   1760:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  1761:             my $sqlresult = 
1.823     albertel 1762:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  1763:                                         'portfolio_metadata',$group,
                   1764:                                         'delete');
1.798     raeburn  1765:         }
                   1766:     }
                   1767:     return $result;
1.531     albertel 1768: }
                   1769: 
1.14      www      1770: # ------------------------------------------------------------------------- Log
                   1771: 
                   1772: sub log {
                   1773:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      1774:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      1775: }
                   1776: 
                   1777: # ------------------------------------------------------------------ Course Log
1.352     www      1778: #
                   1779: # This routine flushes several buffers of non-mission-critical nature
                   1780: #
1.157     www      1781: 
                   1782: sub flushcourselogs {
1.352     www      1783:     &logthis('Flushing log buffers');
                   1784: #
                   1785: # course logs
                   1786: # This is a log of all transactions in a course, which can be used
                   1787: # for data mining purposes
                   1788: #
                   1789: # It also collects the courseid database, which lists last transaction
                   1790: # times and course titles for all courseids
                   1791: #
                   1792:     my %courseidbuffer=();
1.800     albertel 1793:     foreach my $crsid (keys %courselogs) {
1.352     www      1794:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      1795: 		          &escape($courselogs{$crsid}),
                   1796: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      1797: 	    delete $courselogs{$crsid};
                   1798:         } else {
                   1799:             &logthis('Failed to flush log buffer for '.$crsid);
                   1800:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 1801:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      1802:                         " exceeded maximum size, deleting.</font>");
                   1803:                delete $courselogs{$crsid};
                   1804:             }
1.352     www      1805:         }
                   1806:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
                   1807:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
1.516     raeburn  1808: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  1809:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.352     www      1810:         } else {
                   1811:            $courseidbuffer{$coursehombuf{$crsid}}=
1.516     raeburn  1812: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  1813:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.571     raeburn  1814:         }
1.191     harris41 1815:     }
1.352     www      1816: #
                   1817: # Write course id database (reverse lookup) to homeserver of courses 
                   1818: # Is used in pickcourse
                   1819: #
1.800     albertel 1820:     foreach my $crsid (keys(%courseidbuffer)) {
                   1821:         &courseidput($hostdom{$crsid},$courseidbuffer{$crsid},$crsid);
1.352     www      1822:     }
                   1823: #
                   1824: # File accesses
                   1825: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   1826: #
1.449     matthew  1827:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  1828:         if ($entry =~ /___count$/) {
                   1829:             my ($dom,$name);
1.807     albertel 1830:             ($dom,$name,undef)=
1.811     albertel 1831: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  1832:             if (! defined($dom) || $dom eq '' || 
                   1833:                 ! defined($name) || $name eq '') {
1.620     albertel 1834:                 my $cid = $env{'request.course.id'};
                   1835:                 $dom  = $env{'request.'.$cid.'.domain'};
                   1836:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  1837:             }
1.450     matthew  1838:             my $value = $accesshash{$entry};
                   1839:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   1840:             my %temphash=($url => $value);
1.449     matthew  1841:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   1842:             if ($result eq 'ok') {
                   1843:                 delete $accesshash{$entry};
                   1844:             } elsif ($result eq 'unknown_cmd') {
                   1845:                 # Target server has old code running on it.
1.450     matthew  1846:                 my %temphash=($entry => $value);
1.449     matthew  1847:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1848:                     delete $accesshash{$entry};
                   1849:                 }
                   1850:             }
                   1851:         } else {
1.811     albertel 1852:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  1853:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  1854:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1855:                 delete $accesshash{$entry};
                   1856:             }
1.185     www      1857:         }
1.191     harris41 1858:     }
1.352     www      1859: #
                   1860: # Roles
                   1861: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   1862: #
1.800     albertel 1863:     foreach my $entry (keys(%userrolehash)) {
1.351     www      1864:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      1865: 	    split(/\:/,$entry);
                   1866:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      1867:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      1868:                 $rudom,$runame) eq 'ok') {
                   1869: 	    delete $userrolehash{$entry};
                   1870:         }
                   1871:     }
1.662     raeburn  1872: #
                   1873: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   1874: #
                   1875:     my %domrolebuffer = ();
                   1876:     foreach my $entry (keys %domainrolehash) {
                   1877:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split/:/,$entry;
                   1878:         if ($domrolebuffer{$rudom}) {
                   1879:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   1880:                       '='.&escape($domainrolehash{$entry});
                   1881:         } else {
                   1882:             $domrolebuffer{$rudom}.=&escape($entry).
                   1883:                       '='.&escape($domainrolehash{$entry});
                   1884:         }
                   1885:         delete $domainrolehash{$entry};
                   1886:     }
                   1887:     foreach my $dom (keys(%domrolebuffer)) {
                   1888:         foreach my $tryserver (keys %libserv) {
                   1889:             if ($hostdom{$tryserver} eq $dom) {
                   1890:                 unless (&reply('domroleput:'.$dom.':'.
                   1891:                   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   1892:                     &logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   1893:                 }
                   1894:             }
                   1895:         }
                   1896:     }
1.186     www      1897:     $dumpcount++;
1.157     www      1898: }
                   1899: 
                   1900: sub courselog {
                   1901:     my $what=shift;
1.158     www      1902:     $what=time.':'.$what;
1.620     albertel 1903:     unless ($env{'request.course.id'}) { return ''; }
                   1904:     $coursedombuf{$env{'request.course.id'}}=
                   1905:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   1906:     $coursenumbuf{$env{'request.course.id'}}=
                   1907:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   1908:     $coursehombuf{$env{'request.course.id'}}=
                   1909:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   1910:     $coursedescrbuf{$env{'request.course.id'}}=
                   1911:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   1912:     $courseinstcodebuf{$env{'request.course.id'}}=
                   1913:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   1914:     $courseownerbuf{$env{'request.course.id'}}=
                   1915:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  1916:     $coursetypebuf{$env{'request.course.id'}}=
                   1917:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 1918:     if (defined $courselogs{$env{'request.course.id'}}) {
                   1919: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      1920:     } else {
1.620     albertel 1921: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      1922:     }
1.620     albertel 1923:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      1924: 	&flushcourselogs();
                   1925:     }
1.158     www      1926: }
                   1927: 
                   1928: sub courseacclog {
                   1929:     my $fnsymb=shift;
1.620     albertel 1930:     unless ($env{'request.course.id'}) { return ''; }
                   1931:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 1932:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      1933:         $what.=':POST';
1.583     matthew  1934:         # FIXME: Probably ought to escape things....
1.800     albertel 1935: 	foreach my $key (keys(%env)) {
                   1936:             if ($key=~/^form\.(.*)/) {
                   1937: 		$what.=':'.$1.'='.$env{$key};
1.158     www      1938:             }
1.191     harris41 1939:         }
1.583     matthew  1940:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   1941:         # FIXME: We should not be depending on a form parameter that someone
                   1942:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 1943:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  1944:             $what.= ':POST';
                   1945:             # FIXME: Probably ought to escape things....
                   1946:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   1947:                                  'crsdiscuss') {
1.620     albertel 1948:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  1949:             }
                   1950:         }
1.158     www      1951:     }
                   1952:     &courselog($what);
1.149     www      1953: }
                   1954: 
1.185     www      1955: sub countacc {
                   1956:     my $url=&declutter(shift);
1.458     matthew  1957:     return if (! defined($url) || $url eq '');
1.620     albertel 1958:     unless ($env{'request.course.id'}) { return ''; }
                   1959:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      1960:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  1961:     $accesshash{$key}++;
1.185     www      1962: }
1.349     www      1963: 
1.361     www      1964: sub linklog {
                   1965:     my ($from,$to)=@_;
                   1966:     $from=&declutter($from);
                   1967:     $to=&declutter($to);
                   1968:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   1969:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   1970: }
                   1971:   
1.349     www      1972: sub userrolelog {
                   1973:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  1974:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  1975:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  1976:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   1977:         ($trole=~/^ta/)) {
1.350     www      1978:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   1979:        $userrolehash
                   1980:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      1981:                     =$tend.':'.$tstart;
1.662     raeburn  1982:     }
                   1983:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   1984:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   1985:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   1986:         ($trole=~/^sc/)) {
                   1987:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   1988:        $domainrolehash
                   1989:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   1990:                     = $tend.':'.$tstart;
                   1991:     }
1.351     www      1992: }
                   1993: 
                   1994: sub get_course_adv_roles {
                   1995:     my $cid=shift;
1.620     albertel 1996:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      1997:     my %coursehash=&coursedescription($cid);
1.470     www      1998:     my %nothide=();
1.800     albertel 1999:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2000: 	$nothide{join(':',split(/[\@\:]/,$user))}=1;
1.470     www      2001:     }
1.351     www      2002:     my %returnhash=();
                   2003:     my %dumphash=
                   2004:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   2005:     my $now=time;
1.800     albertel 2006:     foreach my $entry (keys %dumphash) {
                   2007: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      2008:         if (($tstart) && ($tstart<0)) { next; }
                   2009:         if (($tend) && ($tend<$now)) { next; }
                   2010:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 2011:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 2012: 	if ($username eq '' || $domain eq '') { next; }
1.470     www      2013: 	if ((&privileged($username,$domain)) && 
                   2014: 	    (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 2015: 	if ($role eq 'cr') { next; }
1.351     www      2016:         my $key=&plaintext($role);
                   2017:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
                   2018:         if ($returnhash{$key}) {
                   2019: 	    $returnhash{$key}.=','.$username.':'.$domain;
                   2020:         } else {
                   2021:             $returnhash{$key}=$username.':'.$domain;
                   2022:         }
1.400     www      2023:      }
                   2024:     return %returnhash;
                   2025: }
                   2026: 
                   2027: sub get_my_roles {
                   2028:     my ($uname,$udom)=@_;
1.620     albertel 2029:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   2030:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.400     www      2031:     my %dumphash=
                   2032:             &dump('nohist_userroles',$udom,$uname);
                   2033:     my %returnhash=();
                   2034:     my $now=time;
1.800     albertel 2035:     foreach my $entry (keys(%dumphash)) {
                   2036: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.400     www      2037:         if (($tstart) && ($tstart<0)) { next; }
                   2038:         if (($tend) && ($tend<$now)) { next; }
                   2039:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 2040:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.400     www      2041: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
1.373     www      2042:      }
                   2043:     return %returnhash;
1.399     www      2044: }
                   2045: 
                   2046: # ----------------------------------------------------- Frontpage Announcements
                   2047: #
                   2048: #
                   2049: 
                   2050: sub postannounce {
                   2051:     my ($server,$text)=@_;
                   2052:     unless (&allowed('psa',$hostdom{$server})) { return 'refused'; }
                   2053:     unless ($text=~/\w/) { $text=''; }
                   2054:     return &reply('setannounce:'.&escape($text),$server);
                   2055: }
                   2056: 
                   2057: sub getannounce {
1.448     albertel 2058: 
                   2059:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      2060: 	my $announcement='';
1.800     albertel 2061: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 2062: 	close($fh);
1.399     www      2063: 	if ($announcement=~/\w/) { 
                   2064: 	    return 
                   2065:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 2066:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      2067: 	} else {
                   2068: 	    return '';
                   2069: 	}
                   2070:     } else {
                   2071: 	return '';
                   2072:     }
1.351     www      2073: }
1.353     www      2074: 
                   2075: # ---------------------------------------------------------- Course ID routines
                   2076: # Deal with domain's nohist_courseid.db files
                   2077: #
                   2078: 
                   2079: sub courseidput {
                   2080:     my ($domain,$what,$coursehome)=@_;
                   2081:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   2082: }
                   2083: 
                   2084: sub courseiddump {
1.791     raeburn  2085:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok)=@_;
1.353     www      2086:     my %returnhash=();
1.355     www      2087:     unless ($domfilter) { $domfilter=''; }
1.353     www      2088:     foreach my $tryserver (keys %libserv) {
1.511     raeburn  2089:         if ( ($hostidflag == 1 && grep/^$tryserver$/,@{$hostidref}) || (!defined($hostidflag)) ) {
1.506     raeburn  2090: 	    if ((!$domfilter) || ($hostdom{$tryserver} eq $domfilter)) {
1.800     albertel 2091: 	        foreach my $line (
1.506     raeburn  2092:                  split(/\&/,&reply('courseiddump:'.$hostdom{$tryserver}.':'.
1.571     raeburn  2093: 			       $sincefilter.':'.&escape($descfilter).':'.
1.791     raeburn  2094:                                &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter).':'.&escape($typefilter).':'.&escape($regexp_ok),
1.354     www      2095:                                $tryserver))) {
1.800     albertel 2096: 		    my ($key,$value)=split(/\=/,$line,2);
1.506     raeburn  2097:                     if (($key) && ($value)) {
1.516     raeburn  2098: 		        $returnhash{&unescape($key)}=$value;
1.506     raeburn  2099:                     }
1.353     www      2100:                 }
                   2101:             }
                   2102:         }
                   2103:     }
                   2104:     return %returnhash;
                   2105: }
                   2106: 
1.658     raeburn  2107: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  2108: 
                   2109: sub dcmailput {
1.685     raeburn  2110:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  2111:     my $status = &Apache::lonnet::critical(
1.740     www      2112:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   2113:        &escape($message),$server);
1.662     raeburn  2114:     return $status;
                   2115: }
                   2116: 
1.658     raeburn  2117: sub dcmaildump {
                   2118:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  2119:     my %returnhash=();
                   2120:     if (exists($domain_primary{$dom})) {
                   2121:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   2122:                                                          &escape($enddate).':';
                   2123: 	my @esc_senders=map { &escape($_)} @$senders;
                   2124: 	$cmd.=&escape(join('&',@esc_senders));
1.800     albertel 2125: 	foreach my $line (split(/\&/,&reply($cmd,$domain_primary{$dom}))) {
                   2126:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  2127:             if (($key) && ($value)) {
                   2128:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  2129:             }
                   2130:         }
                   2131:     }
                   2132:     return %returnhash;
                   2133: }
1.662     raeburn  2134: # ---------------------------------------------------------- Domain roles
                   2135: 
                   2136: sub get_domain_roles {
                   2137:     my ($dom,$roles,$startdate,$enddate)=@_;
                   2138:     if (undef($startdate) || $startdate eq '') {
                   2139:         $startdate = '.';
                   2140:     }
                   2141:     if (undef($enddate) || $enddate eq '') {
                   2142:         $enddate = '.';
                   2143:     }
                   2144:     my $rolelist = join(':',@{$roles});
                   2145:     my %personnel = ();
                   2146:     foreach my $tryserver (keys(%libserv)) {
                   2147:         if ($hostdom{$tryserver} eq $dom) {
                   2148:             %{$personnel{$tryserver}}=();
1.800     albertel 2149:             foreach my $line (
1.662     raeburn  2150:                 split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   2151:                    &escape($startdate).':'.&escape($enddate).':'.
                   2152:                    &escape($rolelist), $tryserver))) {
1.800     albertel 2153:                 my ($key,$value) = split(/\=/,$line,2);
1.662     raeburn  2154:                 if (($key) && ($value)) {
                   2155:                     $personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   2156:                 }
                   2157:             }
                   2158:         }
                   2159:     }
                   2160:     return %personnel;
                   2161: }
1.658     raeburn  2162: 
1.149     www      2163: # ----------------------------------------------------------- Check out an item
                   2164: 
1.504     albertel 2165: sub get_first_access {
                   2166:     my ($type,$argsymb)=@_;
1.790     albertel 2167:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2168:     if ($argsymb) { $symb=$argsymb; }
                   2169:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2170:     if ($type eq 'map') {
                   2171: 	$res=&symbread($map);
                   2172:     } else {
                   2173: 	$res=$symb;
                   2174:     }
                   2175:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   2176:     return $times{"$courseid\0$res"};
1.504     albertel 2177: }
                   2178: 
                   2179: sub set_first_access {
                   2180:     my ($type)=@_;
1.790     albertel 2181:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2182:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2183:     if ($type eq 'map') {
                   2184: 	$res=&symbread($map);
                   2185:     } else {
                   2186: 	$res=$symb;
                   2187:     }
                   2188:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 2189:     if (!$firstaccess) {
1.588     albertel 2190: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 2191:     }
                   2192:     return 'already_set';
1.504     albertel 2193: }
                   2194: 
1.149     www      2195: sub checkout {
                   2196:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   2197:     my $now=time;
                   2198:     my $lonhost=$perlvar{'lonHostID'};
                   2199:     my $infostr=&escape(
1.234     www      2200:                  'CHECKOUTTOKEN&'.
1.149     www      2201:                  $tuname.'&'.
                   2202:                  $tudom.'&'.
                   2203:                  $tcrsid.'&'.
                   2204:                  $symb.'&'.
                   2205: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   2206:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      2207:     if ($token=~/^error\:/) { 
1.672     albertel 2208:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2209:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2210:                  "</font>");
                   2211:         return ''; 
                   2212:     }
                   2213: 
1.149     www      2214:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   2215:     $token=~tr/a-z/A-Z/;
                   2216: 
1.153     www      2217:     my %infohash=('resource.0.outtoken' => $token,
                   2218:                   'resource.0.checkouttime' => $now,
                   2219:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      2220: 
                   2221:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2222:        return '';
1.151     www      2223:     } else {
1.672     albertel 2224:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2225:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2226:                  "</font>");
1.149     www      2227:     }    
                   2228: 
                   2229:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2230:                          &escape('Checkout '.$infostr.' - '.
                   2231:                                                  $token)) ne 'ok') {
                   2232: 	return '';
1.151     www      2233:     } else {
1.672     albertel 2234:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2235:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2236:                  "</font>");
1.149     www      2237:     }
1.151     www      2238:     return $token;
1.149     www      2239: }
                   2240: 
                   2241: # ------------------------------------------------------------ Check in an item
                   2242: 
                   2243: sub checkin {
                   2244:     my $token=shift;
1.150     www      2245:     my $now=time;
                   2246:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   2247:     $lonhost=~tr/A-Z/a-z/;
1.595     albertel 2248:     my $dtoken=$ta.'_'.$hostname{$lonhost}.'_'.$tb;
1.150     www      2249:     $dtoken=~s/\W/\_/g;
1.234     www      2250:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      2251:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   2252: 
1.154     www      2253:     unless (($tuname) && ($tudom)) {
                   2254:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   2255:         return '';
                   2256:     }
                   2257:     
                   2258:     unless (&allowed('mgr',$tcrsid)) {
                   2259:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 2260:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      2261:         return '';
                   2262:     }
                   2263: 
1.153     www      2264:     my %infohash=('resource.0.intoken' => $token,
                   2265:                   'resource.0.checkintime' => $now,
                   2266:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      2267: 
                   2268:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2269:        return '';
                   2270:     }    
                   2271: 
                   2272:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2273:                          &escape('Checkin - '.$token)) ne 'ok') {
                   2274: 	return '';
                   2275:     }
                   2276: 
                   2277:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      2278: }
                   2279: 
                   2280: # --------------------------------------------- Set Expire Date for Spreadsheet
                   2281: 
                   2282: sub expirespread {
                   2283:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 2284:     my $cid=$env{'request.course.id'}; 
1.110     www      2285:     if ($cid) {
                   2286:        my $now=time;
                   2287:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 2288:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   2289:                             $env{'course.'.$cid.'.num'}.
1.110     www      2290: 	        	    ':nohist_expirationdates:'.
                   2291:                             &escape($key).'='.$now,
1.620     albertel 2292:                             $env{'course.'.$cid.'.home'})
1.110     www      2293:     }
                   2294:     return 'ok';
1.14      www      2295: }
                   2296: 
1.109     www      2297: # ----------------------------------------------------- Devalidate Spreadsheets
                   2298: 
                   2299: sub devalidate {
1.325     www      2300:     my ($symb,$uname,$udom)=@_;
1.620     albertel 2301:     my $cid=$env{'request.course.id'}; 
1.109     www      2302:     if ($cid) {
1.391     matthew  2303:         # delete the stored spreadsheets for
                   2304:         # - the student level sheet of this user in course's homespace
                   2305:         # - the assessment level sheet for this resource 
                   2306:         #   for this user in user's homespace
1.553     albertel 2307: 	# - current conditional state info
1.325     www      2308: 	my $key=$uname.':'.$udom.':';
1.109     www      2309:         my $status=
1.299     matthew  2310: 	    &del('nohist_calculatedsheets',
1.391     matthew  2311: 		 [$key.'studentcalc:'],
1.620     albertel 2312: 		 $env{'course.'.$cid.'.domain'},
                   2313: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 2314: 		.' '.
                   2315: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  2316: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      2317:         unless ($status eq 'ok ok') {
                   2318:            &logthis('Could not devalidate spreadsheet '.
1.325     www      2319:                     $uname.' at '.$udom.' for '.
1.109     www      2320: 		    $symb.': '.$status);
1.133     albertel 2321:         }
1.553     albertel 2322: 	&delenv('user.state.'.$cid);
1.109     www      2323:     }
                   2324: }
                   2325: 
1.265     albertel 2326: sub get_scalar {
                   2327:     my ($string,$end) = @_;
                   2328:     my $value;
                   2329:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   2330: 	$value = $1;
                   2331:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   2332: 	$value = $1;
                   2333:     }
                   2334:     return &unescape($value);
                   2335: }
                   2336: 
                   2337: sub array2str {
                   2338:   my (@array) = @_;
                   2339:   my $result=&arrayref2str(\@array);
                   2340:   $result=~s/^__ARRAY_REF__//;
                   2341:   $result=~s/__END_ARRAY_REF__$//;
                   2342:   return $result;
                   2343: }
                   2344: 
1.204     albertel 2345: sub arrayref2str {
                   2346:   my ($arrayref) = @_;
1.265     albertel 2347:   my $result='__ARRAY_REF__';
1.204     albertel 2348:   foreach my $elem (@$arrayref) {
1.265     albertel 2349:     if(ref($elem) eq 'ARRAY') {
                   2350:       $result.=&arrayref2str($elem).'&';
                   2351:     } elsif(ref($elem) eq 'HASH') {
                   2352:       $result.=&hashref2str($elem).'&';
                   2353:     } elsif(ref($elem)) {
                   2354:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 2355:     } else {
                   2356:       $result.=&escape($elem).'&';
                   2357:     }
                   2358:   }
                   2359:   $result=~s/\&$//;
1.265     albertel 2360:   $result .= '__END_ARRAY_REF__';
1.204     albertel 2361:   return $result;
                   2362: }
                   2363: 
1.168     albertel 2364: sub hash2str {
1.204     albertel 2365:   my (%hash) = @_;
                   2366:   my $result=&hashref2str(\%hash);
1.265     albertel 2367:   $result=~s/^__HASH_REF__//;
                   2368:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 2369:   return $result;
                   2370: }
                   2371: 
                   2372: sub hashref2str {
                   2373:   my ($hashref)=@_;
1.265     albertel 2374:   my $result='__HASH_REF__';
1.800     albertel 2375:   foreach my $key (sort(keys(%$hashref))) {
                   2376:     if (ref($key) eq 'ARRAY') {
                   2377:       $result.=&arrayref2str($key).'=';
                   2378:     } elsif (ref($key) eq 'HASH') {
                   2379:       $result.=&hashref2str($key).'=';
                   2380:     } elsif (ref($key)) {
1.265     albertel 2381:       $result.='=';
1.800     albertel 2382:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 2383:     } else {
1.800     albertel 2384: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 2385:     }
                   2386: 
1.800     albertel 2387:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   2388:       $result.=&arrayref2str($hashref->{$key}).'&';
                   2389:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   2390:       $result.=&hashref2str($hashref->{$key}).'&';
                   2391:     } elsif(ref($hashref->{$key})) {
1.265     albertel 2392:        $result.='&';
1.800     albertel 2393:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 2394:     } else {
1.800     albertel 2395:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 2396:     }
                   2397:   }
1.168     albertel 2398:   $result=~s/\&$//;
1.265     albertel 2399:   $result .= '__END_HASH_REF__';
1.168     albertel 2400:   return $result;
                   2401: }
                   2402: 
                   2403: sub str2hash {
1.265     albertel 2404:     my ($string)=@_;
                   2405:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   2406:     return %$hash;
                   2407: }
                   2408: 
                   2409: sub str2hashref {
1.168     albertel 2410:   my ($string) = @_;
1.265     albertel 2411: 
                   2412:   my %hash;
                   2413: 
                   2414:   if($string !~ /^__HASH_REF__/) {
                   2415:       if (! ($string eq '' || !defined($string))) {
                   2416: 	  $hash{'error'}='Not hash reference';
                   2417:       }
                   2418:       return (\%hash, $string);
                   2419:   }
                   2420: 
                   2421:   $string =~ s/^__HASH_REF__//;
                   2422: 
                   2423:   while($string !~ /^__END_HASH_REF__/) {
                   2424:       #key
                   2425:       my $key='';
                   2426:       if($string =~ /^__HASH_REF__/) {
                   2427:           ($key, $string)=&str2hashref($string);
                   2428:           if(defined($key->{'error'})) {
                   2429:               $hash{'error'}='Bad data';
                   2430:               return (\%hash, $string);
                   2431:           }
                   2432:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2433:           ($key, $string)=&str2arrayref($string);
                   2434:           if($key->[0] eq 'Array reference error') {
                   2435:               $hash{'error'}='Bad data';
                   2436:               return (\%hash, $string);
                   2437:           }
                   2438:       } else {
                   2439:           $string =~ s/^(.*?)=//;
1.267     albertel 2440: 	  $key=&unescape($1);
1.265     albertel 2441:       }
                   2442:       $string =~ s/^=//;
                   2443: 
                   2444:       #value
                   2445:       my $value='';
                   2446:       if($string =~ /^__HASH_REF__/) {
                   2447:           ($value, $string)=&str2hashref($string);
                   2448:           if(defined($value->{'error'})) {
                   2449:               $hash{'error'}='Bad data';
                   2450:               return (\%hash, $string);
                   2451:           }
                   2452:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2453:           ($value, $string)=&str2arrayref($string);
                   2454:           if($value->[0] eq 'Array reference error') {
                   2455:               $hash{'error'}='Bad data';
                   2456:               return (\%hash, $string);
                   2457:           }
                   2458:       } else {
                   2459: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   2460:       }
                   2461:       $string =~ s/^&//;
                   2462: 
                   2463:       $hash{$key}=$value;
1.204     albertel 2464:   }
1.265     albertel 2465: 
                   2466:   $string =~ s/^__END_HASH_REF__//;
                   2467: 
                   2468:   return (\%hash, $string);
1.204     albertel 2469: }
                   2470: 
                   2471: sub str2array {
1.265     albertel 2472:     my ($string)=@_;
                   2473:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   2474:     return @$array;
                   2475: }
                   2476: 
                   2477: sub str2arrayref {
1.204     albertel 2478:   my ($string) = @_;
1.265     albertel 2479:   my @array;
                   2480: 
                   2481:   if($string !~ /^__ARRAY_REF__/) {
                   2482:       if (! ($string eq '' || !defined($string))) {
                   2483: 	  $array[0]='Array reference error';
                   2484:       }
                   2485:       return (\@array, $string);
                   2486:   }
                   2487: 
                   2488:   $string =~ s/^__ARRAY_REF__//;
                   2489: 
                   2490:   while($string !~ /^__END_ARRAY_REF__/) {
                   2491:       my $value='';
                   2492:       if($string =~ /^__HASH_REF__/) {
                   2493:           ($value, $string)=&str2hashref($string);
                   2494:           if(defined($value->{'error'})) {
                   2495:               $array[0] ='Array reference error';
                   2496:               return (\@array, $string);
                   2497:           }
                   2498:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2499:           ($value, $string)=&str2arrayref($string);
                   2500:           if($value->[0] eq 'Array reference error') {
                   2501:               $array[0] ='Array reference error';
                   2502:               return (\@array, $string);
                   2503:           }
                   2504:       } else {
                   2505: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   2506:       }
                   2507:       $string =~ s/^&//;
                   2508: 
                   2509:       push(@array, $value);
1.191     harris41 2510:   }
1.265     albertel 2511: 
                   2512:   $string =~ s/^__END_ARRAY_REF__//;
                   2513: 
                   2514:   return (\@array, $string);
1.168     albertel 2515: }
                   2516: 
1.167     albertel 2517: # -------------------------------------------------------------------Temp Store
                   2518: 
1.168     albertel 2519: sub tmpreset {
                   2520:   my ($symb,$namespace,$domain,$stuname) = @_;
                   2521:   if (!$symb) {
                   2522:     $symb=&symbread();
1.620     albertel 2523:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2524:   }
                   2525:   $symb=escape($symb);
                   2526: 
1.620     albertel 2527:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 2528:   $namespace=~s/\//\_/g;
                   2529:   $namespace=~s/\W//g;
                   2530: 
1.620     albertel 2531:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2532:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2533:   if ($domain eq 'public' && $stuname eq 'public') {
                   2534:       $stuname=$ENV{'REMOTE_ADDR'};
                   2535:   }
1.168     albertel 2536:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2537:   my %hash;
                   2538:   if (tie(%hash,'GDBM_File',
                   2539: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2540: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2541:     foreach my $key (keys %hash) {
1.180     albertel 2542:       if ($key=~ /:$symb/) {
1.168     albertel 2543: 	delete($hash{$key});
                   2544:       }
                   2545:     }
                   2546:   }
                   2547: }
                   2548: 
1.167     albertel 2549: sub tmpstore {
1.168     albertel 2550:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2551: 
                   2552:   if (!$symb) {
                   2553:     $symb=&symbread();
1.620     albertel 2554:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2555:   }
                   2556:   $symb=escape($symb);
                   2557: 
                   2558:   if (!$namespace) {
                   2559:     # I don't think we would ever want to store this for a course.
                   2560:     # it seems this will only be used if we don't have a course.
1.620     albertel 2561:     #$namespace=$env{'request.course.id'};
1.168     albertel 2562:     #if (!$namespace) {
1.620     albertel 2563:       $namespace=$env{'request.state'};
1.168     albertel 2564:     #}
                   2565:   }
                   2566:   $namespace=~s/\//\_/g;
                   2567:   $namespace=~s/\W//g;
1.620     albertel 2568:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2569:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2570:   if ($domain eq 'public' && $stuname eq 'public') {
                   2571:       $stuname=$ENV{'REMOTE_ADDR'};
                   2572:   }
1.168     albertel 2573:   my $now=time;
                   2574:   my %hash;
                   2575:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2576:   if (tie(%hash,'GDBM_File',
                   2577: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2578: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2579:     $hash{"version:$symb"}++;
                   2580:     my $version=$hash{"version:$symb"};
                   2581:     my $allkeys=''; 
                   2582:     foreach my $key (keys(%$storehash)) {
                   2583:       $allkeys.=$key.':';
1.591     albertel 2584:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 2585:     }
                   2586:     $hash{"$version:$symb:timestamp"}=$now;
                   2587:     $allkeys.='timestamp';
                   2588:     $hash{"$version:keys:$symb"}=$allkeys;
                   2589:     if (untie(%hash)) {
                   2590:       return 'ok';
                   2591:     } else {
                   2592:       return "error:$!";
                   2593:     }
                   2594:   } else {
                   2595:     return "error:$!";
                   2596:   }
                   2597: }
1.167     albertel 2598: 
1.168     albertel 2599: # -----------------------------------------------------------------Temp Restore
1.167     albertel 2600: 
1.168     albertel 2601: sub tmprestore {
                   2602:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 2603: 
1.168     albertel 2604:   if (!$symb) {
                   2605:     $symb=&symbread();
1.620     albertel 2606:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2607:   }
                   2608:   $symb=escape($symb);
                   2609: 
1.620     albertel 2610:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 2611: 
1.620     albertel 2612:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2613:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2614:   if ($domain eq 'public' && $stuname eq 'public') {
                   2615:       $stuname=$ENV{'REMOTE_ADDR'};
                   2616:   }
1.168     albertel 2617:   my %returnhash;
                   2618:   $namespace=~s/\//\_/g;
                   2619:   $namespace=~s/\W//g;
                   2620:   my %hash;
                   2621:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2622:   if (tie(%hash,'GDBM_File',
                   2623: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2624: 	  &GDBM_READER(),0640)) {
1.168     albertel 2625:     my $version=$hash{"version:$symb"};
                   2626:     $returnhash{'version'}=$version;
                   2627:     my $scope;
                   2628:     for ($scope=1;$scope<=$version;$scope++) {
                   2629:       my $vkeys=$hash{"$scope:keys:$symb"};
                   2630:       my @keys=split(/:/,$vkeys);
                   2631:       my $key;
                   2632:       $returnhash{"$scope:keys"}=$vkeys;
                   2633:       foreach $key (@keys) {
1.591     albertel 2634: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   2635: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 2636:       }
                   2637:     }
1.168     albertel 2638:     if (!(untie(%hash))) {
                   2639:       return "error:$!";
                   2640:     }
                   2641:   } else {
                   2642:     return "error:$!";
                   2643:   }
                   2644:   return %returnhash;
1.167     albertel 2645: }
                   2646: 
1.9       www      2647: # ----------------------------------------------------------------------- Store
                   2648: 
                   2649: sub store {
1.124     www      2650:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2651:     my $home='';
                   2652: 
1.168     albertel 2653:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2654: 
1.213     www      2655:     $symb=&symbclean($symb);
1.122     albertel 2656:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2657: 
1.620     albertel 2658:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2659:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2660: 
                   2661:     &devalidate($symb,$stuname,$domain);
1.109     www      2662: 
                   2663:     $symb=escape($symb);
1.187     www      2664:     if (!$namespace) { 
1.620     albertel 2665:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2666:           return ''; 
                   2667:        } 
                   2668:     }
1.620     albertel 2669:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2670: 
                   2671:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2672:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   2673: 
1.12      www      2674:     my $namevalue='';
1.800     albertel 2675:     foreach my $key (keys(%$storehash)) {
                   2676:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 2677:     }
1.12      www      2678:     $namevalue=~s/\&$//;
1.187     www      2679:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      2680:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      2681: }
                   2682: 
1.47      www      2683: # -------------------------------------------------------------- Critical Store
                   2684: 
                   2685: sub cstore {
1.124     www      2686:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2687:     my $home='';
                   2688: 
1.168     albertel 2689:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2690: 
1.213     www      2691:     $symb=&symbclean($symb);
1.122     albertel 2692:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2693: 
1.620     albertel 2694:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2695:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2696: 
                   2697:     &devalidate($symb,$stuname,$domain);
1.109     www      2698: 
                   2699:     $symb=escape($symb);
1.187     www      2700:     if (!$namespace) { 
1.620     albertel 2701:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2702:           return ''; 
                   2703:        } 
                   2704:     }
1.620     albertel 2705:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2706: 
                   2707:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2708:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 2709: 
1.47      www      2710:     my $namevalue='';
1.800     albertel 2711:     foreach my $key (keys(%$storehash)) {
                   2712:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 2713:     }
1.47      www      2714:     $namevalue=~s/\&$//;
1.187     www      2715:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      2716:     return critical
                   2717:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      2718: }
                   2719: 
1.9       www      2720: # --------------------------------------------------------------------- Restore
                   2721: 
                   2722: sub restore {
1.124     www      2723:     my ($symb,$namespace,$domain,$stuname) = @_;
                   2724:     my $home='';
                   2725: 
1.168     albertel 2726:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2727: 
1.122     albertel 2728:     if (!$symb) {
                   2729:       unless ($symb=escape(&symbread())) { return ''; }
                   2730:     } else {
1.213     www      2731:       $symb=&escape(&symbclean($symb));
1.122     albertel 2732:     }
1.188     www      2733:     if (!$namespace) { 
1.620     albertel 2734:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      2735:           return ''; 
                   2736:        } 
                   2737:     }
1.620     albertel 2738:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2739:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   2740:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 2741:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   2742: 
1.12      www      2743:     my %returnhash=();
1.800     albertel 2744:     foreach my $line (split(/\&/,$answer)) {
                   2745: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 2746:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 2747:     }
1.75      www      2748:     my $version;
                   2749:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 2750:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   2751:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 2752:        }
1.75      www      2753:     }
1.13      www      2754:     return %returnhash;
1.34      www      2755: }
                   2756: 
                   2757: # ---------------------------------------------------------- Course Description
                   2758: 
                   2759: sub coursedescription {
1.731     albertel 2760:     my ($courseid,$args)=@_;
1.34      www      2761:     $courseid=~s/^\///;
1.49      www      2762:     $courseid=~s/\_/\//g;
1.34      www      2763:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 2764:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 2765:     my $normalid=$cdomain.'_'.$cnum;
                   2766:     # need to always cache even if we get errors otherwise we keep 
                   2767:     # trying and trying and trying to get the course description.
                   2768:     my %envhash=();
                   2769:     my %returnhash=();
1.731     albertel 2770:     
                   2771:     my $expiretime=600;
                   2772:     if ($env{'request.course.id'} eq $normalid) {
                   2773: 	$expiretime=120;
                   2774:     }
                   2775: 
                   2776:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   2777:     if (!$args->{'freshen_cache'}
                   2778: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   2779: 	foreach my $key (keys(%env)) {
                   2780: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   2781: 	    my ($setting) = $1;
                   2782: 	    $returnhash{$setting} = $env{$key};
                   2783: 	}
                   2784: 	return %returnhash;
                   2785:     }
                   2786: 
                   2787:     # get the data agin
                   2788:     if (!$args->{'one_time'}) {
                   2789: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   2790:     }
1.811     albertel 2791: 
1.34      www      2792:     if ($chome ne 'no_host') {
1.302     albertel 2793:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 2794:        if (!exists($returnhash{'con_lost'})) {
                   2795:            $returnhash{'home'}= $chome;
                   2796: 	   $returnhash{'domain'} = $cdomain;
                   2797: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  2798:            if (!defined($returnhash{'type'})) {
                   2799:                $returnhash{'type'} = 'Course';
                   2800:            }
1.130     albertel 2801:            while (my ($name,$value) = each %returnhash) {
1.53      www      2802:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 2803:            }
1.270     www      2804:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      2805:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 2806: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      2807:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   2808:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   2809:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      2810:        }
                   2811:     }
1.731     albertel 2812:     if (!$args->{'one_time'}) {
                   2813: 	&appenv(%envhash);
                   2814:     }
1.302     albertel 2815:     return %returnhash;
1.461     www      2816: }
                   2817: 
                   2818: # -------------------------------------------------See if a user is privileged
                   2819: 
                   2820: sub privileged {
                   2821:     my ($username,$domain)=@_;
                   2822:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   2823: 			&homeserver($username,$domain));
                   2824:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   2825:     my $now=time;
                   2826:     if ($rolesdump ne '') {
1.800     albertel 2827:         foreach my $entry (split(/&/,$rolesdump)) {
                   2828: 	    if ($entry!~/^rolesdef_/) {
                   2829: 		my ($area,$role)=split(/=/,$entry);
1.461     www      2830: 		$area=~s/\_\w\w$//;
                   2831: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   2832: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   2833: 		    my $active=1;
                   2834: 		    if ($tend) {
                   2835: 			if ($tend<$now) { $active=0; }
                   2836: 		    }
                   2837: 		    if ($tstart) {
                   2838: 			if ($tstart>$now) { $active=0; }
                   2839: 		    }
                   2840: 		    if ($active) { return 1; }
                   2841: 		}
                   2842: 	    }
                   2843: 	}
                   2844:     }
                   2845:     return 0;
1.9       www      2846: }
1.1       albertel 2847: 
1.103     harris41 2848: # -------------------------------------------------------- Get user privileges
1.11      www      2849: 
                   2850: sub rolesinit {
                   2851:     my ($domain,$username,$authhost)=@_;
                   2852:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12      www      2853:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11      www      2854:     my %allroles=();
1.678     raeburn  2855:     my %allgroups=();   
1.11      www      2856:     my $now=time;
1.743     albertel 2857:     my %userroles = ('user.login.time' => $now);
1.678     raeburn  2858:     my $group_privs;
1.11      www      2859: 
                   2860:     if ($rolesdump ne '') {
1.800     albertel 2861:         foreach my $entry (split(/&/,$rolesdump)) {
                   2862: 	  if ($entry!~/^rolesdef_/) {
                   2863:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 2864: 	    $area=~s/\_\w\w$//;
1.678     raeburn  2865:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 2866: 	    if ($role=~/^cr/) { 
1.807     albertel 2867: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   2868: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 2869: 		    ($tend,$tstart)=split('_',$trest);
                   2870: 		} else {
                   2871: 		    $trole=$role;
                   2872: 		}
1.678     raeburn  2873:             } elsif ($role =~ m|^gr/|) {
                   2874:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   2875:                 ($trole,$group_privs) = split(/\//,$trole);
                   2876:                 $group_privs = &unescape($group_privs);
1.587     albertel 2877: 	    } else {
                   2878: 		($trole,$tend,$tstart)=split(/_/,$role);
                   2879: 	    }
1.743     albertel 2880: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   2881: 					 $username);
                   2882: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  2883:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   2884:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      2885:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 2886: 		my $spec=$trole.'.'.$area;
                   2887: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   2888: 		if ($trole =~ /^cr\//) {
1.567     raeburn  2889:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  2890:                 } elsif ($trole eq 'gr') {
                   2891:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 2892: 		} else {
1.567     raeburn  2893:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 2894: 		}
1.12      www      2895:             }
1.662     raeburn  2896:           }
1.191     harris41 2897:         }
1.743     albertel 2898:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   2899:         $userroles{'user.adv'}    = $adv;
                   2900: 	$userroles{'user.author'} = $author;
1.620     albertel 2901:         $env{'user.adv'}=$adv;
1.11      www      2902:     }
1.743     albertel 2903:     return \%userroles;  
1.11      www      2904: }
                   2905: 
1.567     raeburn  2906: sub set_arearole {
                   2907:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   2908: # log the associated role with the area
                   2909:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 2910:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  2911: }
                   2912: 
                   2913: sub custom_roleprivs {
                   2914:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   2915:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   2916:     my $homsvr=homeserver($rauthor,$rdomain);
                   2917:     if ($hostname{$homsvr} ne '') {
                   2918:         my ($rdummy,$roledef)=
                   2919:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   2920:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   2921:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   2922:             if (defined($syspriv)) {
                   2923:                 $$allroles{'cm./'}.=':'.$syspriv;
                   2924:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   2925:             }
                   2926:             if ($tdomain ne '') {
                   2927:                 if (defined($dompriv)) {
                   2928:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   2929:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   2930:                 }
                   2931:                 if (($trest ne '') && (defined($coursepriv))) {
                   2932:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   2933:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   2934:                 }
                   2935:             }
                   2936:         }
                   2937:     }
                   2938: }
                   2939: 
1.678     raeburn  2940: sub group_roleprivs {
                   2941:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   2942:     my $access = 1;
                   2943:     my $now = time;
                   2944:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   2945:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   2946:     if ($access) {
1.811     albertel 2947:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  2948:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   2949:     }
                   2950: }
1.567     raeburn  2951: 
                   2952: sub standard_roleprivs {
                   2953:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   2954:     if (defined($pr{$trole.':s'})) {
                   2955:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   2956:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   2957:     }
                   2958:     if ($tdomain ne '') {
                   2959:         if (defined($pr{$trole.':d'})) {
                   2960:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   2961:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   2962:         }
                   2963:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   2964:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   2965:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   2966:         }
                   2967:     }
                   2968: }
                   2969: 
                   2970: sub set_userprivs {
1.678     raeburn  2971:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  2972:     my $author=0;
                   2973:     my $adv=0;
1.678     raeburn  2974:     my %grouproles = ();
                   2975:     if (keys(%{$allgroups}) > 0) {
                   2976:         foreach my $role (keys %{$allroles}) {
1.681     raeburn  2977:             my ($trole,$area,$sec,$extendedarea);
1.811     albertel 2978:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)-) {
1.678     raeburn  2979:                 $trole = $1;
                   2980:                 $area = $2;
1.681     raeburn  2981:                 $sec = $3;
                   2982:                 $extendedarea = $area.$sec;
                   2983:                 if (exists($$allgroups{$area})) {
                   2984:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   2985:                         my $spec = $trole.'.'.$extendedarea;
                   2986:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   2987:                                                 $$allgroups{$area}{$group};
1.678     raeburn  2988:                     }
                   2989:                 }
                   2990:             }
                   2991:         }
                   2992:     }
1.800     albertel 2993:     foreach my $group (keys(%grouproles)) {
                   2994:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  2995:     }
1.800     albertel 2996:     foreach my $role (keys(%{$allroles})) {
                   2997:         my %thesepriv;
                   2998:         if (($role=~/^au/) || ($role=~/^ca/)) { $author=1; }
                   2999:         foreach my $item (split(/:/,$$allroles{$role})) {
                   3000:             if ($item ne '') {
                   3001:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  3002:                 if ($restrictions eq '') {
                   3003:                     $thesepriv{$privilege}='F';
                   3004:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   3005:                     $thesepriv{$privilege}.=$restrictions;
                   3006:                 }
                   3007:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   3008:             }
                   3009:         }
                   3010:         my $thesestr='';
1.800     albertel 3011:         foreach my $priv (keys(%thesepriv)) {
                   3012: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   3013: 	}
                   3014:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  3015:     }
                   3016:     return ($author,$adv);
                   3017: }
                   3018: 
1.12      www      3019: # --------------------------------------------------------------- get interface
                   3020: 
                   3021: sub get {
1.131     albertel 3022:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3023:    my $items='';
1.800     albertel 3024:    foreach my $item (@$storearr) {
                   3025:        $items.=&escape($item).'&';
1.191     harris41 3026:    }
1.12      www      3027:    $items=~s/\&$//;
1.620     albertel 3028:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3029:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 3030:    my $uhome=&homeserver($uname,$udomain);
                   3031: 
1.133     albertel 3032:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3033:    my @pairs=split(/\&/,$rep);
1.273     albertel 3034:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   3035:      return @pairs;
                   3036:    }
1.15      www      3037:    my %returnhash=();
1.42      www      3038:    my $i=0;
1.800     albertel 3039:    foreach my $item (@$storearr) {
                   3040:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3041:       $i++;
1.191     harris41 3042:    }
1.15      www      3043:    return %returnhash;
1.27      www      3044: }
                   3045: 
                   3046: # --------------------------------------------------------------- del interface
                   3047: 
                   3048: sub del {
1.133     albertel 3049:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      3050:    my $items='';
1.800     albertel 3051:    foreach my $item (@$storearr) {
                   3052:        $items.=&escape($item).'&';
1.191     harris41 3053:    }
1.27      www      3054:    $items=~s/\&$//;
1.620     albertel 3055:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3056:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3057:    my $uhome=&homeserver($uname,$udomain);
                   3058: 
                   3059:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3060: }
                   3061: 
                   3062: # -------------------------------------------------------------- dump interface
                   3063: 
                   3064: sub dump {
1.755     albertel 3065:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   3066:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3067:     if (!$uname) { $uname=$env{'user.name'}; }
                   3068:     my $uhome=&homeserver($uname,$udomain);
                   3069:     if ($regexp) {
                   3070: 	$regexp=&escape($regexp);
                   3071:     } else {
                   3072: 	$regexp='.';
                   3073:     }
                   3074:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3075:     my @pairs=split(/\&/,$rep);
                   3076:     my %returnhash=();
                   3077:     foreach my $item (@pairs) {
                   3078: 	my ($key,$value)=split(/=/,$item,2);
                   3079: 	$key = &unescape($key);
                   3080: 	next if ($key =~ /^error: 2 /);
                   3081: 	$returnhash{$key}=&thaw_unescape($value);
                   3082:     }
                   3083:     return %returnhash;
1.407     www      3084: }
                   3085: 
1.717     albertel 3086: # --------------------------------------------------------- dumpstore interface
                   3087: 
                   3088: sub dumpstore {
                   3089:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 3090:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3091:    if (!$uname) { $uname=$env{'user.name'}; }
                   3092:    my $uhome=&homeserver($uname,$udomain);
                   3093:    if ($regexp) {
                   3094:        $regexp=&escape($regexp);
                   3095:    } else {
                   3096:        $regexp='.';
                   3097:    }
                   3098:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3099:    my @pairs=split(/\&/,$rep);
                   3100:    my %returnhash=();
                   3101:    foreach my $item (@pairs) {
                   3102:        my ($key,$value)=split(/=/,$item,2);
                   3103:        next if ($key =~ /^error: 2 /);
                   3104:        $returnhash{$key}=&thaw_unescape($value);
                   3105:    }
                   3106:    return %returnhash;
1.717     albertel 3107: }
                   3108: 
1.407     www      3109: # -------------------------------------------------------------- keys interface
                   3110: 
                   3111: sub getkeys {
                   3112:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 3113:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3114:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      3115:    my $uhome=&homeserver($uname,$udomain);
                   3116:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   3117:    my @keyarray=();
1.800     albertel 3118:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  3119:       next if ($key =~ /^error: 2 /);
1.800     albertel 3120:       push(@keyarray,&unescape($key));
1.407     www      3121:    }
                   3122:    return @keyarray;
1.318     matthew  3123: }
                   3124: 
1.319     matthew  3125: # --------------------------------------------------------------- currentdump
                   3126: sub currentdump {
1.328     matthew  3127:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 3128:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   3129:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   3130:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  3131:    my $uhome = &homeserver($sname,$sdom);
                   3132:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  3133:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  3134:    #
1.318     matthew  3135:    my %returnhash=();
1.319     matthew  3136:    #
                   3137:    if ($rep eq "unknown_cmd") { 
                   3138:        # an old lond will not know currentdump
                   3139:        # Do a dump and make it look like a currentdump
1.822     albertel 3140:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  3141:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   3142:        my %hash = @tmp;
                   3143:        @tmp=();
1.424     matthew  3144:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  3145:    } else {
                   3146:        my @pairs=split(/\&/,$rep);
1.800     albertel 3147:        foreach my $pair (@pairs) {
                   3148:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  3149:            my ($symb,$param) = split(/:/,$key);
                   3150:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 3151:                                                         &thaw_unescape($value);
1.319     matthew  3152:        }
1.191     harris41 3153:    }
1.12      www      3154:    return %returnhash;
1.424     matthew  3155: }
                   3156: 
                   3157: sub convert_dump_to_currentdump{
                   3158:     my %hash = %{shift()};
                   3159:     my %returnhash;
                   3160:     # Code ripped from lond, essentially.  The only difference
                   3161:     # here is the unescaping done by lonnet::dump().  Conceivably
                   3162:     # we might run in to problems with parameter names =~ /^v\./
                   3163:     while (my ($key,$value) = each(%hash)) {
                   3164:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 3165: 	$symb  = &unescape($symb);
                   3166: 	$param = &unescape($param);
1.424     matthew  3167:         next if ($v eq 'version' || $symb eq 'keys');
                   3168:         next if (exists($returnhash{$symb}) &&
                   3169:                  exists($returnhash{$symb}->{$param}) &&
                   3170:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   3171:         $returnhash{$symb}->{$param}=$value;
                   3172:         $returnhash{$symb}->{'v.'.$param}=$v;
                   3173:     }
                   3174:     #
                   3175:     # Remove all of the keys in the hashes which keep track of
                   3176:     # the version of the parameter.
                   3177:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   3178:         # use a foreach because we are going to delete from the hash.
                   3179:         foreach my $key (keys(%$param_hash)) {
                   3180:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   3181:         }
                   3182:     }
                   3183:     return \%returnhash;
1.12      www      3184: }
                   3185: 
1.627     albertel 3186: # ------------------------------------------------------ critical inc interface
                   3187: 
                   3188: sub cinc {
                   3189:     return &inc(@_,'critical');
                   3190: }
                   3191: 
1.449     matthew  3192: # --------------------------------------------------------------- inc interface
                   3193: 
                   3194: sub inc {
1.627     albertel 3195:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 3196:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3197:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  3198:     my $uhome=&homeserver($uname,$udomain);
                   3199:     my $items='';
                   3200:     if (! ref($store)) {
                   3201:         # got a single value, so use that instead
                   3202:         $items = &escape($store).'=&';
                   3203:     } elsif (ref($store) eq 'SCALAR') {
                   3204:         $items = &escape($$store).'=&';        
                   3205:     } elsif (ref($store) eq 'ARRAY') {
                   3206:         $items = join('=&',map {&escape($_);} @{$store});
                   3207:     } elsif (ref($store) eq 'HASH') {
                   3208:         while (my($key,$value) = each(%{$store})) {
                   3209:             $items.= &escape($key).'='.&escape($value).'&';
                   3210:         }
                   3211:     }
                   3212:     $items=~s/\&$//;
1.627     albertel 3213:     if ($critical) {
                   3214: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3215:     } else {
                   3216: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3217:     }
1.449     matthew  3218: }
                   3219: 
1.12      www      3220: # --------------------------------------------------------------- put interface
                   3221: 
                   3222: sub put {
1.134     albertel 3223:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3224:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3225:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3226:    my $uhome=&homeserver($uname,$udomain);
1.12      www      3227:    my $items='';
1.800     albertel 3228:    foreach my $item (keys(%$storehash)) {
                   3229:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3230:    }
1.12      www      3231:    $items=~s/\&$//;
1.134     albertel 3232:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      3233: }
                   3234: 
1.631     albertel 3235: # ------------------------------------------------------------ newput interface
                   3236: 
                   3237: sub newput {
                   3238:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   3239:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3240:    if (!$uname) { $uname=$env{'user.name'}; }
                   3241:    my $uhome=&homeserver($uname,$udomain);
                   3242:    my $items='';
                   3243:    foreach my $key (keys(%$storehash)) {
                   3244:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   3245:    }
                   3246:    $items=~s/\&$//;
                   3247:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   3248: }
                   3249: 
                   3250: # ---------------------------------------------------------  putstore interface
                   3251: 
1.524     raeburn  3252: sub putstore {
1.715     albertel 3253:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 3254:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3255:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  3256:    my $uhome=&homeserver($uname,$udomain);
                   3257:    my $items='';
1.715     albertel 3258:    foreach my $key (keys(%$storehash)) {
                   3259:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  3260:    }
1.715     albertel 3261:    $items=~s/\&$//;
1.716     albertel 3262:    my $esc_symb=&escape($symb);
                   3263:    my $esc_v=&escape($version);
1.715     albertel 3264:    my $reply =
1.716     albertel 3265:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 3266: 	      $uhome);
                   3267:    if ($reply eq 'unknown_cmd') {
1.716     albertel 3268:        # gfall back to way things use to be done
1.715     albertel 3269:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   3270: 			    $uname);
1.524     raeburn  3271:    }
1.715     albertel 3272:    return $reply;
                   3273: }
                   3274: 
                   3275: sub old_putstore {
1.716     albertel 3276:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   3277:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3278:     if (!$uname) { $uname=$env{'user.name'}; }
                   3279:     my $uhome=&homeserver($uname,$udomain);
                   3280:     my %newstorehash;
1.800     albertel 3281:     foreach my $item (keys(%$storehash)) {
                   3282: 	my $key = $version.':'.&escape($symb).':'.$item;
                   3283: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 3284:     }
                   3285:     my $items='';
                   3286:     my %allitems = ();
1.800     albertel 3287:     foreach my $item (keys(%newstorehash)) {
                   3288: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 3289: 	    my $key = $1.':keys:'.$2;
                   3290: 	    $allitems{$key} .= $3.':';
                   3291: 	}
1.800     albertel 3292: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 3293:     }
1.800     albertel 3294:     foreach my $item (keys(%allitems)) {
                   3295: 	$allitems{$item} =~ s/\:$//;
                   3296: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 3297:     }
                   3298:     $items=~s/\&$//;
                   3299:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  3300: }
                   3301: 
1.47      www      3302: # ------------------------------------------------------ critical put interface
                   3303: 
                   3304: sub cput {
1.134     albertel 3305:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3306:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3307:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3308:    my $uhome=&homeserver($uname,$udomain);
1.47      www      3309:    my $items='';
1.800     albertel 3310:    foreach my $item (keys(%$storehash)) {
                   3311:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3312:    }
1.47      www      3313:    $items=~s/\&$//;
1.134     albertel 3314:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3315: }
                   3316: 
                   3317: # -------------------------------------------------------------- eget interface
                   3318: 
                   3319: sub eget {
1.133     albertel 3320:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3321:    my $items='';
1.800     albertel 3322:    foreach my $item (@$storearr) {
                   3323:        $items.=&escape($item).'&';
1.191     harris41 3324:    }
1.12      www      3325:    $items=~s/\&$//;
1.620     albertel 3326:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3327:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3328:    my $uhome=&homeserver($uname,$udomain);
                   3329:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3330:    my @pairs=split(/\&/,$rep);
                   3331:    my %returnhash=();
1.42      www      3332:    my $i=0;
1.800     albertel 3333:    foreach my $item (@$storearr) {
                   3334:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3335:       $i++;
1.191     harris41 3336:    }
1.12      www      3337:    return %returnhash;
                   3338: }
                   3339: 
1.667     albertel 3340: # ------------------------------------------------------------ tmpput interface
                   3341: sub tmpput {
1.802     raeburn  3342:     my ($storehash,$server,$context)=@_;
1.667     albertel 3343:     my $items='';
1.800     albertel 3344:     foreach my $item (keys(%$storehash)) {
                   3345: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 3346:     }
                   3347:     $items=~s/\&$//;
1.802     raeburn  3348:     if (defined($context)) {
                   3349:         $items .= ':'.&escape($context);
                   3350:     }
1.667     albertel 3351:     return &reply("tmpput:$items",$server);
                   3352: }
                   3353: 
                   3354: # ------------------------------------------------------------ tmpget interface
                   3355: sub tmpget {
1.688     albertel 3356:     my ($token,$server)=@_;
                   3357:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3358:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 3359:     my %returnhash;
                   3360:     foreach my $item (split(/\&/,$rep)) {
                   3361: 	my ($key,$value)=split(/=/,$item);
                   3362: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   3363:     }
                   3364:     return %returnhash;
                   3365: }
                   3366: 
1.688     albertel 3367: # ------------------------------------------------------------ tmpget interface
                   3368: sub tmpdel {
                   3369:     my ($token,$server)=@_;
                   3370:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3371:     return &reply("tmpdel:$token",$server);
                   3372: }
                   3373: 
1.765     albertel 3374: # -------------------------------------------------- portfolio access checking
                   3375: 
                   3376: sub portfolio_access {
1.766     albertel 3377:     my ($requrl) = @_;
1.765     albertel 3378:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   3379:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  3380:     if ($result) {
                   3381:         my %setters;
                   3382:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3383:             my ($startblock,$endblock) =
                   3384:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   3385:             if ($startblock && $endblock) {
                   3386:                 return 'B';
                   3387:             }
                   3388:         } else {
                   3389:             my ($startblock,$endblock) =
                   3390:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   3391:             if ($startblock && $endblock) {
                   3392:                 return 'B';
                   3393:             }
                   3394:         }
                   3395:     }
1.765     albertel 3396:     if ($result eq 'ok') {
1.766     albertel 3397:        return 'F';
1.765     albertel 3398:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 3399:        return 'A';
1.765     albertel 3400:     }
1.766     albertel 3401:     return '';
1.765     albertel 3402: }
                   3403: 
                   3404: sub get_portfolio_access {
1.767     albertel 3405:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   3406: 
                   3407:     if (!ref($access_hash)) {
                   3408: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   3409: 	my %access_controls = &get_access_controls($current_perms,$group,
                   3410: 						   $file_name);
                   3411: 	$access_hash = $access_controls{$file_name};
                   3412:     }
                   3413: 
1.765     albertel 3414:     my ($public,$guest,@domains,@users,@courses,@groups);
                   3415:     my $now = time;
                   3416:     if (ref($access_hash) eq 'HASH') {
                   3417:         foreach my $key (keys(%{$access_hash})) {
                   3418:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   3419:             if ($start > $now) {
                   3420:                 next;
                   3421:             }
                   3422:             if ($end && $end<$now) {
                   3423:                 next;
                   3424:             }
                   3425:             if ($scope eq 'public') {
                   3426:                 $public = $key;
                   3427:                 last;
                   3428:             } elsif ($scope eq 'guest') {
                   3429:                 $guest = $key;
                   3430:             } elsif ($scope eq 'domains') {
                   3431:                 push(@domains,$key);
                   3432:             } elsif ($scope eq 'users') {
                   3433:                 push(@users,$key);
                   3434:             } elsif ($scope eq 'course') {
                   3435:                 push(@courses,$key);
                   3436:             } elsif ($scope eq 'group') {
                   3437:                 push(@groups,$key);
                   3438:             }
                   3439:         }
                   3440:         if ($public) {
                   3441:             return 'ok';
                   3442:         }
                   3443:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3444:             if ($guest) {
                   3445:                 return $guest;
                   3446:             }
                   3447:         } else {
                   3448:             if (@domains > 0) {
                   3449:                 foreach my $domkey (@domains) {
                   3450:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   3451:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   3452:                             return 'ok';
                   3453:                         }
                   3454:                     }
                   3455:                 }
                   3456:             }
                   3457:             if (@users > 0) {
                   3458:                 foreach my $userkey (@users) {
                   3459:                     if (exists($access_hash->{$userkey}{'users'}{$env{'user.name'}.':'.$env{'user.domain'}})) {
                   3460:                         return 'ok';
                   3461:                     }
                   3462:                 }
                   3463:             }
                   3464:             my %roleshash;
                   3465:             my @courses_and_groups = @courses;
                   3466:             push(@courses_and_groups,@groups); 
                   3467:             if (@courses_and_groups > 0) {
                   3468:                 my (%allgroups,%allroles); 
                   3469:                 my ($start,$end,$role,$sec,$group);
                   3470:                 foreach my $envkey (%env) {
1.811     albertel 3471:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 3472:                         my $cid = $2.'_'.$3; 
                   3473:                         if ($1 eq 'gr') {
                   3474:                             $group = $4;
                   3475:                             $allgroups{$cid}{$group} = $env{$envkey};
                   3476:                         } else {
                   3477:                             if ($4 eq '') {
                   3478:                                 $sec = 'none';
                   3479:                             } else {
                   3480:                                 $sec = $4;
                   3481:                             }
                   3482:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3483:                         }
1.811     albertel 3484:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 3485:                         my $cid = $2.'_'.$3;
                   3486:                         if ($4 eq '') {
                   3487:                             $sec = 'none';
                   3488:                         } else {
                   3489:                             $sec = $4;
                   3490:                         }
                   3491:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3492:                     }
                   3493:                 }
                   3494:                 if (keys(%allroles) == 0) {
                   3495:                     return;
                   3496:                 }
                   3497:                 foreach my $key (@courses_and_groups) {
                   3498:                     my %content = %{$$access_hash{$key}};
                   3499:                     my $cnum = $content{'number'};
                   3500:                     my $cdom = $content{'domain'};
                   3501:                     my $cid = $cdom.'_'.$cnum;
                   3502:                     if (!exists($allroles{$cid})) {
                   3503:                         next;
                   3504:                     }    
                   3505:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   3506:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   3507:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   3508:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   3509:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   3510:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   3511:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   3512:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   3513:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   3514:                                         if (grep/^all$/,@sections) {
                   3515:                                             return 'ok';
                   3516:                                         } else {
                   3517:                                             if (grep/^$sec$/,@sections) {
                   3518:                                                 return 'ok';
                   3519:                                             }
                   3520:                                         }
                   3521:                                     }
                   3522:                                 }
                   3523:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   3524:                                     if (grep/^none$/,@groups) {
                   3525:                                         return 'ok';
                   3526:                                     }
                   3527:                                 } else {
                   3528:                                     if (grep/^all$/,@groups) {
                   3529:                                         return 'ok';
                   3530:                                     } 
                   3531:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   3532:                                         if (grep/^$group$/,@groups) {
                   3533:                                             return 'ok';
                   3534:                                         }
                   3535:                                     }
                   3536:                                 } 
                   3537:                             }
                   3538:                         }
                   3539:                     }
                   3540:                 }
                   3541:             }
                   3542:             if ($guest) {
                   3543:                 return $guest;
                   3544:             }
                   3545:         }
                   3546:     }
                   3547:     return;
                   3548: }
                   3549: 
                   3550: sub course_group_datechecker {
                   3551:     my ($dates,$now,$status) = @_;
                   3552:     my ($start,$end) = split(/\./,$dates);
                   3553:     if (!$start && !$end) {
                   3554:         return 'ok';
                   3555:     }
                   3556:     if (grep/^active$/,@{$status}) {
                   3557:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   3558:             return 'ok';
                   3559:         }
                   3560:     }
                   3561:     if (grep/^previous$/,@{$status}) {
                   3562:         if ($end > $now ) {
                   3563:             return 'ok';
                   3564:         }
                   3565:     }
                   3566:     if (grep/^future$/,@{$status}) {
                   3567:         if ($start > $now) {
                   3568:             return 'ok';
                   3569:         }
                   3570:     }
                   3571:     return; 
                   3572: }
                   3573: 
                   3574: sub parse_portfolio_url {
                   3575:     my ($url) = @_;
                   3576: 
                   3577:     my ($type,$udom,$unum,$group,$file_name);
                   3578:     
1.823     albertel 3579:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 3580: 	$type = 1;
                   3581:         $udom = $1;
                   3582:         $unum = $2;
                   3583:         $file_name = $3;
1.823     albertel 3584:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 3585: 	$type = 2;
                   3586:         $udom = $1;
                   3587:         $unum = $2;
                   3588:         $group = $3;
                   3589:         $file_name = $3.'/'.$4;
                   3590:     }
                   3591:     if (wantarray) {
                   3592: 	return ($type,$udom,$unum,$file_name,$group);
                   3593:     }
                   3594:     return $type;
                   3595: }
                   3596: 
                   3597: sub is_portfolio_url {
                   3598:     my ($url) = @_;
                   3599:     return scalar(&parse_portfolio_url($url));
                   3600: }
                   3601: 
1.798     raeburn  3602: sub is_portfolio_file {
                   3603:     my ($file) = @_;
1.820     raeburn  3604:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  3605:         return 1;
                   3606:     }
                   3607:     return;
                   3608: }
                   3609: 
                   3610: 
1.341     www      3611: # ---------------------------------------------- Custom access rule evaluation
                   3612: 
                   3613: sub customaccess {
                   3614:     my ($priv,$uri)=@_;
1.807     albertel 3615:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      3616:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 3617:     $udom = &LONCAPA::clean_domain($udom);
                   3618:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      3619:     my $access=0;
1.800     albertel 3620:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
                   3621: 	my ($effect,$realm,$role)=split(/\:/,$right);
1.343     www      3622:         if ($role) {
                   3623: 	   if ($role ne $urole) { next; }
                   3624:         }
1.800     albertel 3625:         foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   3626:             my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
1.343     www      3627:             if ($tdom) {
                   3628: 		if ($tdom ne $udom) { next; }
                   3629:             }
                   3630:             if ($tcrs) {
                   3631: 		if ($tcrs ne $ucrs) { next; }
                   3632:             }
                   3633:             if ($tsec) {
                   3634: 		if ($tsec ne $usec) { next; }
                   3635:             }
                   3636:             $access=($effect eq 'allow');
                   3637:             last;
1.342     www      3638:         }
1.402     bowersj2 3639: 	if ($realm eq '' && $role eq '') {
                   3640:             $access=($effect eq 'allow');
                   3641: 	}
1.341     www      3642:     }
                   3643:     return $access;
                   3644: }
                   3645: 
1.103     harris41 3646: # ------------------------------------------------- Check for a user privilege
1.12      www      3647: 
                   3648: sub allowed {
1.810     raeburn  3649:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 3650:     my $ver_orguri=$uri;
1.439     www      3651:     $uri=&deversion($uri);
1.152     www      3652:     my $orguri=$uri;
1.52      www      3653:     $uri=&declutter($uri);
1.809     raeburn  3654: 
1.810     raeburn  3655:     if ($priv eq 'evb') {
                   3656: # Evade communication block restrictions for specified role in a course
                   3657:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   3658:             return $1;
                   3659:         } else {
                   3660:             return;
                   3661:         }
                   3662:     }
                   3663: 
1.620     albertel 3664:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      3665: # Free bre access to adm and meta resources
1.775     albertel 3666:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 3667: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   3668: 	&& ($priv eq 'bre')) {
1.14      www      3669: 	return 'F';
1.159     www      3670:     }
                   3671: 
1.545     banghart 3672: # Free bre access to user's own portfolio contents
1.714     raeburn  3673:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  3674:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  3675: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  3676:         my %setters;
                   3677:         my ($startblock,$endblock) = 
                   3678:             &Apache::loncommon::blockcheck(\%setters,'port');
                   3679:         if ($startblock && $endblock) {
                   3680:             return 'B';
                   3681:         } else {
                   3682:             return 'F';
                   3683:         }
1.545     banghart 3684:     }
                   3685: 
1.762     raeburn  3686: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  3687:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   3688:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   3689:         if (exists($env{'request.course.id'})) {
                   3690:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3691:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3692:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   3693:                 my $courseprivid=$env{'request.course.id'};
                   3694:                 $courseprivid=~s/\_/\//;
                   3695:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   3696:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   3697:                     return $1; 
1.762     raeburn  3698:                 } else {
                   3699:                     if ($env{'request.course.sec'}) {
                   3700:                         $courseprivid.='/'.$env{'request.course.sec'};
                   3701:                     }
                   3702:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   3703:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   3704:                         return $2;
                   3705:                     }
1.714     raeburn  3706:                 }
                   3707:             }
                   3708:         }
                   3709:     }
                   3710: 
1.159     www      3711: # Free bre to public access
                   3712: 
                   3713:     if ($priv eq 'bre') {
1.238     www      3714:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 3715: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      3716:            return 'F'; 
                   3717:         }
1.238     www      3718:         if ($copyright eq 'priv') {
                   3719:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3720: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      3721: 		return '';
                   3722:             }
                   3723:         }
                   3724:         if ($copyright eq 'domain') {
                   3725:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3726: 	    unless (($env{'user.domain'} eq $1) ||
                   3727:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      3728: 		return '';
                   3729:             }
1.262     matthew  3730:         }
1.620     albertel 3731:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  3732:             # Library role, so allow browsing of resources in this domain.
                   3733:             return 'F';
1.238     www      3734:         }
1.341     www      3735:         if ($copyright eq 'custom') {
                   3736: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   3737:         }
1.14      www      3738:     }
1.264     matthew  3739:     # Domain coordinator is trying to create a course
1.620     albertel 3740:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  3741:         # uri is the requested domain in this case.
                   3742:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  3743:         # a role of dc for the domain in question.
1.620     albertel 3744:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  3745:     }
1.29      www      3746: 
1.52      www      3747:     my $thisallowed='';
                   3748:     my $statecond=0;
                   3749:     my $courseprivid='';
                   3750: 
                   3751: # Course
                   3752: 
1.620     albertel 3753:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3754:        $thisallowed.=$1;
                   3755:     }
1.29      www      3756: 
1.52      www      3757: # Domain
                   3758: 
1.620     albertel 3759:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 3760:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3761:        $thisallowed.=$1;
                   3762:     }
1.52      www      3763: 
                   3764: # Course: uri itself is a course
1.66      www      3765:     my $courseuri=$uri;
                   3766:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      3767:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      3768: 
1.620     albertel 3769:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 3770:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3771:        $thisallowed.=$1;
                   3772:     }
1.29      www      3773: 
1.665     albertel 3774: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 3775: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 3776:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 3777: 	$thisallowed='';
1.671     raeburn  3778:         my ($match)=&is_on_map($uri);
                   3779:         if ($match) {
                   3780:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   3781:                   =~/\Q$priv\E\&([^\:]*)/) {
                   3782:                 $thisallowed.=$1;
                   3783:             }
                   3784:         } else {
1.705     albertel 3785:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  3786:             if ($refuri) {
                   3787:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  3788:                     $thisallowed='F';
1.671     raeburn  3789:                 } else {
                   3790:                     $refuri=&declutter($refuri);
                   3791:                     my ($match) = &is_on_map($refuri);
                   3792:                     if ($match) {
                   3793:                         $thisallowed='F';
                   3794:                     }
1.669     raeburn  3795:                 }
1.671     raeburn  3796:             }
                   3797:         }
1.314     www      3798:     }
1.492     albertel 3799: 
1.766     albertel 3800:     if ($priv eq 'bre'
                   3801: 	&& $thisallowed ne 'F' 
                   3802: 	&& $thisallowed ne '2'
                   3803: 	&& &is_portfolio_url($uri)) {
                   3804: 	$thisallowed = &portfolio_access($uri);
                   3805:     }
                   3806:     
1.52      www      3807: # Full access at system, domain or course-wide level? Exit.
1.29      www      3808: 
                   3809:     if ($thisallowed=~/F/) {
                   3810: 	return 'F';
                   3811:     }
                   3812: 
1.52      www      3813: # If this is generating or modifying users, exit with special codes
1.29      www      3814: 
1.643     www      3815:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   3816: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 3817: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      3818: # no author name given, so this just checks on the general right to make a co-author in this domain
                   3819: 	    unless ($auname) { return $thisallowed; }
                   3820: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 3821: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   3822: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   3823: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   3824: 	}
1.52      www      3825: 	return $thisallowed;
                   3826:     }
                   3827: #
1.103     harris41 3828: # Gathered so far: system, domain and course wide privileges
1.52      www      3829: #
                   3830: # Course: See if uri or referer is an individual resource that is part of 
                   3831: # the course
                   3832: 
1.620     albertel 3833:     if ($env{'request.course.id'}) {
1.232     www      3834: 
1.620     albertel 3835:        $courseprivid=$env{'request.course.id'};
                   3836:        if ($env{'request.course.sec'}) {
                   3837:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      3838:        }
                   3839:        $courseprivid=~s/\_/\//;
                   3840:        my $checkreferer=1;
1.232     www      3841:        my ($match,$cond)=&is_on_map($uri);
                   3842:        if ($match) {
                   3843:            $statecond=$cond;
1.620     albertel 3844:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 3845:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3846:                $thisallowed.=$1;
                   3847:                $checkreferer=0;
                   3848:            }
1.29      www      3849:        }
1.83      www      3850:        
1.148     www      3851:        if ($checkreferer) {
1.620     albertel 3852: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      3853:             unless ($refuri) {
1.800     albertel 3854:                 foreach my $key (keys(%env)) {
                   3855: 		    if ($key=~/^httpref\..*\*/) {
                   3856: 			my $pattern=$key;
1.156     www      3857:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      3858:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   3859:                         $pattern=~s/\//\\\//g;
1.152     www      3860:                         if ($orguri=~/$pattern/) {
1.800     albertel 3861: 			    $refuri=$env{$key};
1.148     www      3862:                         }
                   3863:                     }
1.191     harris41 3864:                 }
1.148     www      3865:             }
1.232     www      3866: 
1.148     www      3867:          if ($refuri) { 
1.152     www      3868: 	  $refuri=&declutter($refuri);
1.232     www      3869:           my ($match,$cond)=&is_on_map($refuri);
                   3870:             if ($match) {
                   3871:               my $refstatecond=$cond;
1.620     albertel 3872:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 3873:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3874:                   $thisallowed.=$1;
1.53      www      3875:                   $uri=$refuri;
                   3876:                   $statecond=$refstatecond;
1.52      www      3877:               }
                   3878:           }
1.148     www      3879:         }
1.29      www      3880:        }
1.52      www      3881:    }
1.29      www      3882: 
1.52      www      3883: #
1.103     harris41 3884: # Gathered now: all privileges that could apply, and condition number
1.52      www      3885: # 
                   3886: #
                   3887: # Full or no access?
                   3888: #
1.29      www      3889: 
1.52      www      3890:     if ($thisallowed=~/F/) {
                   3891: 	return 'F';
                   3892:     }
1.29      www      3893: 
1.52      www      3894:     unless ($thisallowed) {
                   3895:         return '';
                   3896:     }
1.29      www      3897: 
1.52      www      3898: # Restrictions exist, deal with them
                   3899: #
                   3900: #   C:according to course preferences
                   3901: #   R:according to resource settings
                   3902: #   L:unless locked
                   3903: #   X:according to user session state
                   3904: #
                   3905: 
                   3906: # Possibly locked functionality, check all courses
1.54      www      3907: # Locks might take effect only after 10 minutes cache expiration for other
                   3908: # courses, and 2 minutes for current course
1.52      www      3909: 
                   3910:     my $envkey;
                   3911:     if ($thisallowed=~/L/) {
1.620     albertel 3912:         foreach $envkey (keys %env) {
1.54      www      3913:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   3914:                my $courseid=$2;
                   3915:                my $roleid=$1.'.'.$2;
1.92      www      3916:                $courseid=~s/^\///;
1.54      www      3917:                my $expiretime=600;
1.620     albertel 3918:                if ($env{'request.role'} eq $roleid) {
1.54      www      3919: 		  $expiretime=120;
                   3920:                }
                   3921: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   3922:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 3923:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 3924: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      3925:                }
1.620     albertel 3926:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   3927:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   3928: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   3929:                        &log($env{'user.domain'},$env{'user.name'},
                   3930:                             $env{'user.home'},
1.57      www      3931:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      3932:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 3933:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      3934: 		       return '';
                   3935:                    }
                   3936:                }
1.620     albertel 3937:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   3938:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   3939: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   3940:                        &log($env{'user.domain'},$env{'user.name'},
                   3941:                             $env{'user.home'},
1.57      www      3942:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      3943:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 3944:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      3945: 		       return '';
                   3946:                    }
                   3947:                }
                   3948: 	   }
1.29      www      3949:        }
1.52      www      3950:     }
                   3951:    
                   3952: #
                   3953: # Rest of the restrictions depend on selected course
                   3954: #
                   3955: 
1.620     albertel 3956:     unless ($env{'request.course.id'}) {
1.766     albertel 3957: 	if ($thisallowed eq 'A') {
                   3958: 	    return 'A';
1.814     raeburn  3959:         } elsif ($thisallowed eq 'B') {
                   3960:             return 'B';
1.766     albertel 3961: 	} else {
                   3962: 	    return '1';
                   3963: 	}
1.52      www      3964:     }
1.29      www      3965: 
1.52      www      3966: #
                   3967: # Now user is definitely in a course
                   3968: #
1.53      www      3969: 
                   3970: 
                   3971: # Course preferences
                   3972: 
                   3973:    if ($thisallowed=~/C/) {
1.620     albertel 3974:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   3975:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   3976:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 3977: 	   =~/\Q$rolecode\E/) {
1.689     albertel 3978: 	   if ($priv ne 'pch') { 
                   3979: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   3980: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   3981: 			$env{'request.course.id'});
                   3982: 	   }
1.237     www      3983:            return '';
                   3984:        }
                   3985: 
1.620     albertel 3986:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 3987: 	   =~/\Q$unamedom\E/) {
1.689     albertel 3988: 	   if ($priv ne 'pch') { 
                   3989: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   3990: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   3991: 			$env{'request.course.id'});
                   3992: 	   }
1.54      www      3993:            return '';
                   3994:        }
1.53      www      3995:    }
                   3996: 
                   3997: # Resource preferences
                   3998: 
                   3999:    if ($thisallowed=~/R/) {
1.620     albertel 4000:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 4001:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 4002: 	   if ($priv ne 'pch') { 
                   4003: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4004: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   4005: 	   }
                   4006: 	   return '';
1.54      www      4007:        }
1.53      www      4008:    }
1.30      www      4009: 
1.246     www      4010: # Restricted by state or randomout?
1.30      www      4011: 
1.52      www      4012:    if ($thisallowed=~/X/) {
1.620     albertel 4013:       if ($env{'acc.randomout'}) {
1.579     albertel 4014: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 4015:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      4016:             return ''; 
                   4017:          }
1.247     www      4018:       }
                   4019:       if (&condval($statecond)) {
1.52      www      4020: 	 return '2';
                   4021:       } else {
                   4022:          return '';
                   4023:       }
                   4024:    }
1.30      www      4025: 
1.766     albertel 4026:     if ($thisallowed eq 'A') {
                   4027: 	return 'A';
1.814     raeburn  4028:     } elsif ($thisallowed eq 'B') {
                   4029:         return 'B';
1.766     albertel 4030:     }
1.52      www      4031:    return 'F';
1.232     www      4032: }
                   4033: 
1.710     albertel 4034: sub split_uri_for_cond {
                   4035:     my $uri=&deversion(&declutter(shift));
                   4036:     my @uriparts=split(/\//,$uri);
                   4037:     my $filename=pop(@uriparts);
                   4038:     my $pathname=join('/',@uriparts);
                   4039:     return ($pathname,$filename);
                   4040: }
1.232     www      4041: # --------------------------------------------------- Is a resource on the map?
                   4042: 
                   4043: sub is_on_map {
1.710     albertel 4044:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 4045:     #Trying to find the conditional for the file
1.620     albertel 4046:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 4047: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      4048:     if ($match) {
1.289     bowersj2 4049: 	return (1,$1);
                   4050:     } else {
1.434     www      4051: 	return (0,0);
1.289     bowersj2 4052:     }
1.12      www      4053: }
                   4054: 
1.427     www      4055: # --------------------------------------------------------- Get symb from alias
                   4056: 
                   4057: sub get_symb_from_alias {
                   4058:     my $symb=shift;
                   4059:     my ($map,$resid,$url)=&decode_symb($symb);
                   4060: # Already is a symb
                   4061:     if ($url) { return $symb; }
                   4062: # Must be an alias
                   4063:     my $aliassymb='';
                   4064:     my %bighash;
1.620     albertel 4065:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      4066:                             &GDBM_READER(),0640)) {
                   4067:         my $rid=$bighash{'mapalias_'.$symb};
                   4068: 	if ($rid) {
                   4069: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 4070: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   4071: 				    $resid,$bighash{'src_'.$rid});
1.427     www      4072: 	}
                   4073:         untie %bighash;
                   4074:     }
                   4075:     return $aliassymb;
                   4076: }
                   4077: 
1.12      www      4078: # ----------------------------------------------------------------- Define Role
                   4079: 
                   4080: sub definerole {
                   4081:   if (allowed('mcr','/')) {
                   4082:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 4083:     foreach my $role (split(':',$sysrole)) {
                   4084: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4085:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   4086:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   4087: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4088:                return "refused:s:$crole&$cqual"; 
                   4089:             }
                   4090:         }
1.191     harris41 4091:     }
1.800     albertel 4092:     foreach my $role (split(':',$domrole)) {
                   4093: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4094:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   4095:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   4096: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      4097:                return "refused:d:$crole&$cqual"; 
                   4098:             }
                   4099:         }
1.191     harris41 4100:     }
1.800     albertel 4101:     foreach my $role (split(':',$courole)) {
                   4102: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4103:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   4104:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   4105: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4106:                return "refused:c:$crole&$cqual"; 
                   4107:             }
                   4108:         }
1.191     harris41 4109:     }
1.620     albertel 4110:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   4111:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4112: 	        "rolesdef_$rolename=".
                   4113:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 4114:     return reply($command,$env{'user.home'});
1.12      www      4115:   } else {
                   4116:     return 'refused';
                   4117:   }
1.105     harris41 4118: }
                   4119: 
                   4120: # ---------------- Make a metadata query against the network of library servers
                   4121: 
                   4122: sub metadata_query {
1.244     matthew  4123:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 4124:     my %rhash;
1.244     matthew  4125:     my @server_list = (defined($server_array) ? @$server_array
                   4126:                                               : keys(%libserv) );
                   4127:     for my $server (@server_list) {
1.118     harris41 4128: 	unless ($custom or $customshow) {
                   4129: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   4130: 	    $rhash{$server}=$reply;
                   4131: 	}
                   4132: 	else {
                   4133: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   4134: 			     &escape($custom).':'.&escape($customshow),
                   4135: 			     $server);
                   4136: 	    $rhash{$server}=$reply;
                   4137: 	}
1.112     harris41 4138:     }
1.118     harris41 4139:     return \%rhash;
1.240     www      4140: }
                   4141: 
                   4142: # ----------------------------------------- Send log queries and wait for reply
                   4143: 
                   4144: sub log_query {
                   4145:     my ($uname,$udom,$query,%filters)=@_;
                   4146:     my $uhome=&homeserver($uname,$udom);
                   4147:     if ($uhome eq 'no_host') { return 'error: no_host'; }
                   4148:     my $uhost=$hostname{$uhome};
1.800     albertel 4149:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      4150:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   4151:                        $uhome);
1.479     albertel 4152:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      4153:     return get_query_reply($queryid);
                   4154: }
                   4155: 
1.818     raeburn  4156: # -------------------------- Update MySQL table for portfolio file
                   4157: 
                   4158: sub update_portfolio_table {
1.821     raeburn  4159:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.818     raeburn  4160:     my $homeserver = &homeserver($uname,$udom);
                   4161:     my $queryid=
1.821     raeburn  4162:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   4163:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  4164:     my $reply = &get_query_reply($queryid);
                   4165:     return $reply;
                   4166: }
                   4167: 
1.508     raeburn  4168: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  4169: 
                   4170: sub fetch_enrollment_query {
1.511     raeburn  4171:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  4172:     my $homeserver;
1.547     raeburn  4173:     my $maxtries = 1;
1.508     raeburn  4174:     if ($context eq 'automated') {
                   4175:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  4176:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  4177:     } else {
                   4178:         $homeserver = &homeserver($cnum,$dom);
                   4179:     }
1.506     raeburn  4180:     my $host=$hostname{$homeserver};
                   4181:     my $cmd = '';
1.800     albertel 4182:     foreach my $affiliate (keys %{$affiliatesref}) {
                   4183:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  4184:     }
                   4185:     $cmd =~ s/%%$//;
                   4186:     $cmd = &escape($cmd);
                   4187:     my $query = 'fetchenrollment';
1.620     albertel 4188:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  4189:     unless ($queryid=~/^\Q$host\E\_/) { 
                   4190:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   4191:         return 'error: '.$queryid;
                   4192:     }
1.506     raeburn  4193:     my $reply = &get_query_reply($queryid);
1.547     raeburn  4194:     my $tries = 1;
                   4195:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4196:         $reply = &get_query_reply($queryid);
                   4197:         $tries ++;
                   4198:     }
1.526     raeburn  4199:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 4200:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  4201:     } else {
1.515     raeburn  4202:         my @responses = split/:/,$reply;
                   4203:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 4204:             foreach my $line (@responses) {
                   4205:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  4206:                 $$replyref{$key} = $value;
                   4207:             }
                   4208:         } else {
1.506     raeburn  4209:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 4210:             foreach my $line (@responses) {
                   4211:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  4212:                 $$replyref{$key} = $value;
                   4213:                 if ($value > 0) {
1.800     albertel 4214:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   4215:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  4216:                         my $destname = $pathname.'/'.$filename;
                   4217:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  4218:                         if ($xml_classlist =~ /^error/) {
                   4219:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   4220:                         } else {
1.506     raeburn  4221:                             if ( open(FILE,">$destname") ) {
                   4222:                                 print FILE &unescape($xml_classlist);
                   4223:                                 close(FILE);
1.526     raeburn  4224:                             } else {
                   4225:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  4226:                             }
                   4227:                         }
                   4228:                     }
                   4229:                 }
                   4230:             }
                   4231:         }
                   4232:         return 'ok';
                   4233:     }
                   4234:     return 'error';
                   4235: }
                   4236: 
1.242     www      4237: sub get_query_reply {
                   4238:     my $queryid=shift;
1.240     www      4239:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   4240:     my $reply='';
                   4241:     for (1..100) {
                   4242: 	sleep 2;
                   4243:         if (-e $replyfile.'.end') {
1.448     albertel 4244: 	    if (open(my $fh,$replyfile)) {
1.240     www      4245:                $reply.=<$fh>;
1.448     albertel 4246:                close($fh);
1.240     www      4247: 	   } else { return 'error: reply_file_error'; }
1.242     www      4248:            return &unescape($reply);
                   4249: 	}
1.240     www      4250:     }
1.242     www      4251:     return 'timeout:'.$queryid;
1.240     www      4252: }
                   4253: 
                   4254: sub courselog_query {
1.241     www      4255: #
                   4256: # possible filters:
                   4257: # url: url or symb
                   4258: # username
                   4259: # domain
                   4260: # action: view, submit, grade
                   4261: # start: timestamp
                   4262: # end: timestamp
                   4263: #
1.240     www      4264:     my (%filters)=@_;
1.620     albertel 4265:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      4266:     if ($filters{'url'}) {
                   4267: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   4268:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   4269:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   4270:     }
1.620     albertel 4271:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4272:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      4273:     return &log_query($cname,$cdom,'courselog',%filters);
                   4274: }
                   4275: 
                   4276: sub userlog_query {
                   4277:     my ($uname,$udom,%filters)=@_;
                   4278:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      4279: }
                   4280: 
1.506     raeburn  4281: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   4282: 
                   4283: sub auto_run {
1.508     raeburn  4284:     my ($cnum,$cdom) = @_;
                   4285:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4286:     my $response = &reply('autorun:'.$cdom,$homeserver);
1.506     raeburn  4287:     return $response;
                   4288: }
1.776     albertel 4289: 
1.506     raeburn  4290: sub auto_get_sections {
1.508     raeburn  4291:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   4292:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  4293:     my @secs = ();
1.511     raeburn  4294:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  4295:     unless ($response eq 'refused') {
                   4296:         @secs = split/:/,$response;
                   4297:     }
                   4298:     return @secs;
                   4299: }
1.776     albertel 4300: 
1.506     raeburn  4301: sub auto_new_course {
1.508     raeburn  4302:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   4303:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  4304:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  4305:     return $response;
                   4306: }
1.776     albertel 4307: 
1.506     raeburn  4308: sub auto_validate_courseID {
1.508     raeburn  4309:     my ($cnum,$cdom,$inst_course_id) = @_;
                   4310:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4311:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  4312:     return $response;
                   4313: }
1.776     albertel 4314: 
1.506     raeburn  4315: sub auto_create_password {
1.508     raeburn  4316:     my ($cnum,$cdom,$authparam) = @_;
                   4317:     my $homeserver = &homeserver($cnum,$cdom); 
1.506     raeburn  4318:     my $create_passwd = 0;
                   4319:     my $authchk = '';
1.511     raeburn  4320:     my $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
1.506     raeburn  4321:     if ($response eq 'refused') {
                   4322:         $authchk = 'refused';
                   4323:     } else {
                   4324:         ($authparam,$create_passwd,$authchk) = split/:/,$response;
                   4325:     }
                   4326:     return ($authparam,$create_passwd,$authchk);
                   4327: }
                   4328: 
1.706     raeburn  4329: sub auto_photo_permission {
                   4330:     my ($cnum,$cdom,$students) = @_;
                   4331:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 4332:     my ($outcome,$perm_reqd,$conditions) = 
                   4333: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 4334:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4335: 	return (undef,undef);
                   4336:     }
1.706     raeburn  4337:     return ($outcome,$perm_reqd,$conditions);
                   4338: }
                   4339: 
                   4340: sub auto_checkphotos {
                   4341:     my ($uname,$udom,$pid) = @_;
                   4342:     my $homeserver = &homeserver($uname,$udom);
                   4343:     my ($result,$resulttype);
                   4344:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 4345: 				   &escape($uname).':'.&escape($pid),
                   4346: 				   $homeserver));
1.709     albertel 4347:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4348: 	return (undef,undef);
                   4349:     }
1.706     raeburn  4350:     if ($outcome) {
                   4351:         ($result,$resulttype) = split(/:/,$outcome);
                   4352:     } 
                   4353:     return ($result,$resulttype);
                   4354: }
                   4355: 
                   4356: sub auto_photochoice {
                   4357:     my ($cnum,$cdom) = @_;
                   4358:     my $homeserver = &homeserver($cnum,$cdom);
                   4359:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 4360: 						       &escape($cdom),
                   4361: 						       $homeserver)));
1.709     albertel 4362:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4363: 	return (undef,undef);
                   4364:     }
1.706     raeburn  4365:     return ($update,$comment);
                   4366: }
                   4367: 
                   4368: sub auto_photoupdate {
                   4369:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   4370:     my $homeserver = &homeserver($cnum,$dom);
                   4371:     my $host=$hostname{$homeserver};
                   4372:     my $cmd = '';
                   4373:     my $maxtries = 1;
1.800     albertel 4374:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   4375:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  4376:     }
                   4377:     $cmd =~ s/%%$//;
                   4378:     $cmd = &escape($cmd);
                   4379:     my $query = 'institutionalphotos';
                   4380:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   4381:     unless ($queryid=~/^\Q$host\E\_/) {
                   4382:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   4383:         return 'error: '.$queryid;
                   4384:     }
                   4385:     my $reply = &get_query_reply($queryid);
                   4386:     my $tries = 1;
                   4387:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4388:         $reply = &get_query_reply($queryid);
                   4389:         $tries ++;
                   4390:     }
                   4391:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   4392:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   4393:     } else {
                   4394:         my @responses = split(/:/,$reply);
                   4395:         my $outcome = shift(@responses); 
                   4396:         foreach my $item (@responses) {
                   4397:             my ($key,$value) = split(/=/,$item);
                   4398:             $$photo{$key} = $value;
                   4399:         }
                   4400:         return $outcome;
                   4401:     }
                   4402:     return 'error';
                   4403: }
                   4404: 
1.521     raeburn  4405: sub auto_instcode_format {
1.793     albertel 4406:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   4407: 	$cat_order) = @_;
1.521     raeburn  4408:     my $courses = '';
1.772     raeburn  4409:     my @homeservers;
1.521     raeburn  4410:     if ($caller eq 'global') {
1.793     albertel 4411:         foreach my $tryserver (keys(%libserv)) {
1.584     raeburn  4412:             if ($hostdom{$tryserver} eq $codedom) {
1.793     albertel 4413:                 if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
1.772     raeburn  4414:                     push(@homeservers,$tryserver);
                   4415:                 }
1.584     raeburn  4416:             }
                   4417:         }
1.521     raeburn  4418:     } else {
1.772     raeburn  4419:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  4420:     }
1.793     albertel 4421:     foreach my $code (keys(%{$instcodes})) {
                   4422:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  4423:     }
                   4424:     chop($courses);
1.772     raeburn  4425:     my $ok_response = 0;
                   4426:     my $response;
                   4427:     while (@homeservers > 0 && $ok_response == 0) {
                   4428:         my $server = shift(@homeservers); 
                   4429:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   4430:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   4431:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.793     albertel 4432: 		split/:/,$response;
1.772     raeburn  4433:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   4434:             push(@{$codetitles},&str2array($codetitles_str));
                   4435:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   4436:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   4437:             $ok_response = 1;
                   4438:         }
                   4439:     }
                   4440:     if ($ok_response) {
1.521     raeburn  4441:         return 'ok';
1.772     raeburn  4442:     } else {
                   4443:         return $response;
1.521     raeburn  4444:     }
                   4445: }
                   4446: 
1.792     raeburn  4447: sub auto_instcode_defaults {
                   4448:     my ($domain,$returnhash,$code_order) = @_;
                   4449:     my @homeservers;
1.793     albertel 4450:     foreach my $tryserver (keys(%libserv)) {
1.792     raeburn  4451:         if ($hostdom{$tryserver} eq $domain) {
1.793     albertel 4452:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
1.792     raeburn  4453:                 push(@homeservers,$tryserver);
                   4454:             }
                   4455:         }
                   4456:     }
                   4457:     my $ok_response = 0;
                   4458:     my $response;
                   4459:     while (@homeservers > 0 && $ok_response == 0) {
                   4460:         my $server = shift(@homeservers);
                   4461:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
                   4462:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
1.793     albertel 4463:             foreach my $pair (split(/\&/,$response)) {
                   4464:                 my ($name,$value)=split(/\=/,$pair);
1.792     raeburn  4465:                 if ($name eq 'code_order') {
1.796     raeburn  4466:                     @{$code_order} = split(/\&/,&unescape($value));
1.792     raeburn  4467:                 } else {
1.796     raeburn  4468:                     $returnhash->{&unescape($name)}=&unescape($value);
1.792     raeburn  4469:                 }
                   4470:             }
1.804     raeburn  4471:             $ok_response = 1;
1.792     raeburn  4472:         }
                   4473:     }
                   4474:     if ($ok_response) {
                   4475:         return 'ok';
                   4476:     } else {
                   4477:         return $response;
                   4478:     }
                   4479: } 
                   4480: 
1.777     albertel 4481: sub auto_validate_class_sec {
1.773     raeburn  4482:     my ($cdom,$cnum,$owner,$inst_class) = @_;
                   4483:     my $homeserver = &homeserver($cnum,$cdom);
                   4484:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.774     banghart 4485:                         &escape($owner).':'.$cdom,$homeserver);
1.773     raeburn  4486:     return $response;
                   4487: }
                   4488: 
1.679     raeburn  4489: # ------------------------------------------------------- Course Group routines
                   4490: 
                   4491: sub get_coursegroups {
1.809     raeburn  4492:     my ($cdom,$cnum,$group,$namespace) = @_;
                   4493:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  4494: }
                   4495: 
1.679     raeburn  4496: sub modify_coursegroup {
                   4497:     my ($cdom,$cnum,$groupsettings) = @_;
                   4498:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   4499: }
                   4500: 
1.809     raeburn  4501: sub toggle_coursegroup_status {
                   4502:     my ($cdom,$cnum,$group,$action) = @_;
                   4503:     my ($from_namespace,$to_namespace);
                   4504:     if ($action eq 'delete') {
                   4505:         $from_namespace = 'coursegroups';
                   4506:         $to_namespace = 'deleted_groups';
                   4507:     } else {
                   4508:         $from_namespace = 'deleted_groups';
                   4509:         $to_namespace = 'coursegroups';
                   4510:     }
                   4511:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  4512:     if (my $tmp = &error(%curr_group)) {
                   4513:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   4514:         return ('read error',$tmp);
                   4515:     } else {
                   4516:         my %savedsettings = %curr_group; 
1.809     raeburn  4517:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  4518:         my $deloutcome;
                   4519:         if ($result eq 'ok') {
1.809     raeburn  4520:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  4521:         } else {
                   4522:             return ('write error',$result);
                   4523:         }
                   4524:         if ($deloutcome eq 'ok') {
                   4525:             return 'ok';
                   4526:         } else {
                   4527:             return ('delete error',$deloutcome);
                   4528:         }
                   4529:     }
                   4530: }
                   4531: 
1.679     raeburn  4532: sub modify_group_roles {
                   4533:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
                   4534:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   4535:     my $role = 'gr/'.&escape($userprivs);
                   4536:     my ($uname,$udom) = split(/:/,$user);
                   4537:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
1.684     raeburn  4538:     if ($result eq 'ok') {
                   4539:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   4540:     }
1.679     raeburn  4541:     return $result;
                   4542: }
                   4543: 
                   4544: sub modify_coursegroup_membership {
                   4545:     my ($cdom,$cnum,$membership) = @_;
                   4546:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   4547:     return $result;
                   4548: }
                   4549: 
1.682     raeburn  4550: sub get_active_groups {
                   4551:     my ($udom,$uname,$cdom,$cnum) = @_;
                   4552:     my $now = time;
                   4553:     my %groups = ();
                   4554:     foreach my $key (keys(%env)) {
1.811     albertel 4555:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  4556:             my ($start,$end) = split(/\./,$env{$key});
                   4557:             if (($end!=0) && ($end<$now)) { next; }
                   4558:             if (($start!=0) && ($start>$now)) { next; }
                   4559:             if ($1 eq $cdom && $2 eq $cnum) {
                   4560:                 $groups{$3} = $env{$key} ;
                   4561:             }
                   4562:         }
                   4563:     }
                   4564:     return %groups;
                   4565: }
                   4566: 
1.683     raeburn  4567: sub get_group_membership {
                   4568:     my ($cdom,$cnum,$group) = @_;
                   4569:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   4570: }
                   4571: 
                   4572: sub get_users_groups {
                   4573:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  4574:     my @usersgroups;
1.683     raeburn  4575:     my $cachetime=1800;
                   4576: 
                   4577:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  4578:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   4579:     if (defined($cached)) {
1.734     albertel 4580:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  4581:     } else {  
                   4582:         $grouplist = '';
1.816     raeburn  4583:         my $courseurl = &courseid_to_courseurl($courseid);
                   4584:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  4585:         my $access_end = $env{'course.'.$courseid.
                   4586:                               '.default_enrollment_end_date'};
                   4587:         my $now = time;
                   4588:         foreach my $key (keys(%roleshash)) {
                   4589:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   4590:                 my $group = $1;
                   4591:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   4592:                     my $start = $2;
                   4593:                     my $end = $1;
                   4594:                     if ($start == -1) { next; } # deleted from group
                   4595:                     if (($start!=0) && ($start>$now)) { next; }
                   4596:                     if (($end!=0) && ($end<$now)) {
                   4597:                         if ($access_end && $access_end < $now) {
                   4598:                             if ($access_end - $end < 86400) {
                   4599:                                 push(@usersgroups,$group);
1.733     raeburn  4600:                             }
                   4601:                         }
1.817     raeburn  4602:                         next;
1.733     raeburn  4603:                     }
1.817     raeburn  4604:                     push(@usersgroups,$group);
1.683     raeburn  4605:                 }
                   4606:             }
                   4607:         }
1.817     raeburn  4608:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   4609:         $grouplist = join(':',@usersgroups);
                   4610:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  4611:     }
1.733     raeburn  4612:     return @usersgroups;
1.683     raeburn  4613: }
                   4614: 
                   4615: sub devalidate_getgroups_cache {
                   4616:     my ($udom,$uname,$cdom,$cnum)=@_;
                   4617:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 4618: 
1.683     raeburn  4619:     my $hashid="$udom:$uname:$courseid";
                   4620:     &devalidate_cache_new('getgroups',$hashid);
                   4621: }
                   4622: 
1.12      www      4623: # ------------------------------------------------------------------ Plain Text
                   4624: 
                   4625: sub plaintext {
1.742     raeburn  4626:     my ($short,$type,$cid) = @_;
1.758     albertel 4627:     if ($short =~ /^cr/) {
                   4628: 	return (split('/',$short))[-1];
                   4629:     }
1.742     raeburn  4630:     if (!defined($cid)) {
                   4631:         $cid = $env{'request.course.id'};
                   4632:     }
                   4633:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
                   4634:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
                   4635:                                           '.plaintext'});
                   4636:     }
                   4637:     my %rolenames = (
                   4638:                       Course => 'std',
                   4639:                       Group => 'alt1',
                   4640:                     );
                   4641:     if (defined($type) && 
                   4642:          defined($rolenames{$type}) && 
                   4643:          defined($prp{$short}{$rolenames{$type}})) {
                   4644:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   4645:     } else {
                   4646:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   4647:     }
1.12      www      4648: }
                   4649: 
                   4650: # ----------------------------------------------------------------- Assign Role
                   4651: 
                   4652: sub assignrole {
1.357     www      4653:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
1.21      www      4654:     my $mrole;
                   4655:     if ($role =~ /^cr\//) {
1.393     www      4656:         my $cwosec=$url;
1.811     albertel 4657:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      4658: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      4659:            &logthis('Refused custom assignrole: '.
                   4660:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4661: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4662:            return 'refused'; 
                   4663:         }
1.21      www      4664:         $mrole='cr';
1.678     raeburn  4665:     } elsif ($role =~ /^gr\//) {
                   4666:         my $cwogrp=$url;
1.811     albertel 4667:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  4668:         unless (&allowed('mdg',$cwogrp)) {
                   4669:             &logthis('Refused group assignrole: '.
                   4670:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   4671:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   4672:             return 'refused';
                   4673:         }
                   4674:         $mrole='gr';
1.21      www      4675:     } else {
1.82      www      4676:         my $cwosec=$url;
1.811     albertel 4677:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.373     www      4678:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
1.104     www      4679:            &logthis('Refused assignrole: '.
                   4680:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4681: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4682:            return 'refused'; 
                   4683:         }
1.21      www      4684:         $mrole=$role;
                   4685:     }
1.620     albertel 4686:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4687:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      4688:     if ($end) { $command.='_'.$end; }
1.21      www      4689:     if ($start) {
                   4690: 	if ($end) { 
1.81      www      4691:            $command.='_'.$start; 
1.21      www      4692:         } else {
1.81      www      4693:            $command.='_0_'.$start;
1.21      www      4694:         }
                   4695:     }
1.739     raeburn  4696:     my $origstart = $start;
                   4697:     my $origend = $end;
1.357     www      4698: # actually delete
                   4699:     if ($deleteflag) {
1.373     www      4700: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      4701: # modify command to delete the role
1.620     albertel 4702:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      4703:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 4704: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      4705: # set start and finish to negative values for userrolelog
                   4706:            $start=-1;
                   4707:            $end=-1;
                   4708:         }
                   4709:     }
                   4710: # send command
1.349     www      4711:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      4712: # log new user role if status is ok
1.349     www      4713:     if ($answer eq 'ok') {
1.663     raeburn  4714: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  4715: # for course roles, perform group memberships changes triggered by role change.
                   4716:         unless ($role =~ /^gr/) {
                   4717:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   4718:                                              $origstart);
                   4719:         }
1.349     www      4720:     }
                   4721:     return $answer;
1.169     harris41 4722: }
                   4723: 
                   4724: # -------------------------------------------------- Modify user authentication
1.197     www      4725: # Overrides without validation
                   4726: 
1.169     harris41 4727: sub modifyuserauth {
                   4728:     my ($udom,$uname,$umode,$upass)=@_;
                   4729:     my $uhome=&homeserver($uname,$udom);
1.197     www      4730:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   4731:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 4732:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4733:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 4734:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   4735: 		     &escape($upass),$uhome);
1.620     albertel 4736:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      4737:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   4738:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   4739:     &log($udom,,$uname,$uhome,
1.620     albertel 4740:         'Authentication changed by '.$env{'user.domain'}.', '.
                   4741:                                      $env{'user.name'}.', '.$umode.
1.197     www      4742:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 4743:     unless ($reply eq 'ok') {
1.197     www      4744:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 4745: 	return 'error: '.$reply;
                   4746:     }   
1.170     harris41 4747:     return 'ok';
1.80      www      4748: }
                   4749: 
1.81      www      4750: # --------------------------------------------------------------- Modify a user
1.80      www      4751: 
1.81      www      4752: sub modifyuser {
1.206     matthew  4753:     my ($udom,    $uname, $uid,
                   4754:         $umode,   $upass, $first,
                   4755:         $middle,  $last,  $gene,
1.387     www      4756:         $forceid, $desiredhome, $email)=@_;
1.807     albertel 4757:     $udom= &LONCAPA::clean_domain($udom);
                   4758:     $uname=&LONCAPA::clean_username($uname);
1.81      www      4759:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4760:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  4761: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   4762:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   4763:                                      ' desiredhome not specified'). 
1.620     albertel 4764:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4765:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 4766:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      4767: # ----------------------------------------------------------------- Create User
1.406     albertel 4768:     if (($uhome eq 'no_host') && 
                   4769: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      4770:         my $unhome='';
1.209     matthew  4771:         if (defined($desiredhome) && $hostdom{$desiredhome} eq $udom) { 
                   4772:             $unhome = $desiredhome;
1.620     albertel 4773: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   4774: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  4775:         } else { # load balancing routine for determining $unhome
1.80      www      4776:             my $tryserver;
1.81      www      4777:             my $loadm=10000000;
1.80      www      4778:             foreach $tryserver (keys %libserv) {
                   4779: 	       if ($hostdom{$tryserver} eq $udom) {
                   4780:                   my $answer=reply('load',$tryserver);
                   4781:                   if (($answer=~/\d+/) && ($answer<$loadm)) {
                   4782: 		      $loadm=$answer;
                   4783:                       $unhome=$tryserver;
                   4784:                   }
                   4785: 	       }
                   4786: 	    }
                   4787:         }
                   4788:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  4789: 	    return 'error: unable to find a home server for '.$uname.
                   4790:                    ' in domain '.$udom;
1.80      www      4791:         }
                   4792:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   4793:                          &escape($upass),$unhome);
                   4794: 	unless ($reply eq 'ok') {
                   4795:             return 'error: '.$reply;
                   4796:         }   
1.230     stredwic 4797:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      4798:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  4799: 	    return 'error: unable verify users home machine.';
1.80      www      4800:         }
1.209     matthew  4801:     }   # End of creation of new user
1.80      www      4802: # ---------------------------------------------------------------------- Add ID
                   4803:     if ($uid) {
                   4804:        $uid=~tr/A-Z/a-z/;
                   4805:        my %uidhash=&idrget($udom,$uname);
1.196     www      4806:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   4807:          && (!$forceid)) {
1.80      www      4808: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  4809: 	      return 'error: user id "'.$uid.'" does not match '.
                   4810:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      4811:           }
                   4812:        } else {
                   4813: 	  &idput($udom,($uname => $uid));
                   4814:        }
                   4815:     }
                   4816: # -------------------------------------------------------------- Add names, etc
1.313     matthew  4817:     my @tmp=&get('environment',
1.134     albertel 4818: 		   ['firstname','middlename','lastname','generation'],
                   4819: 		   $udom,$uname);
1.313     matthew  4820:     my %names;
                   4821:     if ($tmp[0] =~ m/^error:.*/) { 
                   4822:         %names=(); 
                   4823:     } else {
                   4824:         %names = @tmp;
                   4825:     }
1.388     www      4826: #
                   4827: # Make sure to not trash student environment if instructor does not bother
                   4828: # to supply name and email information
                   4829: #
                   4830:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  4831:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      4832:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  4833:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      4834:     if ($email) {
                   4835:        $email=~s/[^\w\@\.\-\,]//gs;
                   4836:        if ($email=~/\@/) { $names{'notification'} = $email;
                   4837: 			   $names{'critnotification'} = $email;
                   4838: 			   $names{'permanentemail'} = $email; }
                   4839:     }
1.134     albertel 4840:     my $reply = &put('environment', \%names, $udom,$uname);
                   4841:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.680     www      4842:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.81      www      4843:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4844:              $umode.', '.$first.', '.$middle.', '.
                   4845: 	     $last.', '.$gene.' by '.
1.620     albertel 4846:              $env{'user.name'}.' at '.$env{'user.domain'});
1.134     albertel 4847:     return 'ok';
1.80      www      4848: }
                   4849: 
1.81      www      4850: # -------------------------------------------------------------- Modify student
1.80      www      4851: 
1.81      www      4852: sub modifystudent {
                   4853:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.515     raeburn  4854:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
1.455     albertel 4855:     if (!$cid) {
1.620     albertel 4856: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 4857: 	    return 'not_in_class';
                   4858: 	}
1.80      www      4859:     }
                   4860: # --------------------------------------------------------------- Make the user
1.81      www      4861:     my $reply=&modifyuser
1.209     matthew  4862: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      4863:          $desiredhome,$email);
1.80      www      4864:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  4865:     # This will cause &modify_student_enrollment to get the uid from the
                   4866:     # students environment
                   4867:     $uid = undef if (!$forceid);
1.455     albertel 4868:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.515     raeburn  4869: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
1.297     matthew  4870:     return $reply;
                   4871: }
                   4872: 
                   4873: sub modify_student_enrollment {
1.515     raeburn  4874:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
1.455     albertel 4875:     my ($cdom,$cnum,$chome);
                   4876:     if (!$cid) {
1.620     albertel 4877: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 4878: 	    return 'not_in_class';
                   4879: 	}
1.620     albertel 4880: 	$cdom=$env{'course.'.$cid.'.domain'};
                   4881: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 4882:     } else {
                   4883: 	($cdom,$cnum)=split(/_/,$cid);
                   4884:     }
1.620     albertel 4885:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 4886:     if (!$chome) {
1.457     raeburn  4887: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  4888:     }
1.455     albertel 4889:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  4890:     # Make sure the user exists
1.81      www      4891:     my $uhome=&homeserver($uname,$udom);
                   4892:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   4893: 	return 'error: no such user';
                   4894:     }
1.297     matthew  4895:     # Get student data if we were not given enough information
                   4896:     if (!defined($first)  || $first  eq '' || 
                   4897:         !defined($last)   || $last   eq '' || 
                   4898:         !defined($uid)    || $uid    eq '' || 
                   4899:         !defined($middle) || $middle eq '' || 
                   4900:         !defined($gene)   || $gene   eq '') {
1.294     matthew  4901:         # They did not supply us with enough data to enroll the student, so
                   4902:         # we need to pick up more information.
1.297     matthew  4903:         my %tmp = &get('environment',
1.294     matthew  4904:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  4905:                        ,$udom,$uname);
                   4906: 
1.800     albertel 4907:         #foreach my $key (keys(%tmp)) {
                   4908:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 4909:         #}
1.294     matthew  4910:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   4911:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   4912:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  4913:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  4914:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   4915:     }
1.556     albertel 4916:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 4917:     my $reply=cput('classlist',
                   4918: 		   {"$uname:$udom" => 
1.515     raeburn  4919: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 4920: 		   $cdom,$cnum);
1.81      www      4921:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   4922: 	return 'error: '.$reply;
1.652     albertel 4923:     } else {
                   4924: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      4925:     }
1.297     matthew  4926:     # Add student role to user
1.83      www      4927:     my $uurl='/'.$cid;
1.81      www      4928:     $uurl=~s/\_/\//g;
                   4929:     if ($usec) {
                   4930: 	$uurl.='/'.$usec;
                   4931:     }
                   4932:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21      www      4933: }
                   4934: 
1.556     albertel 4935: sub format_name {
                   4936:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   4937:     my $name;
                   4938:     if ($first ne 'lastname') {
                   4939: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   4940:     } else {
                   4941: 	if ($lastname=~/\S/) {
                   4942: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   4943: 	    $name=~s/\s+,/,/;
                   4944: 	} else {
                   4945: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   4946: 	}
                   4947:     }
                   4948:     $name=~s/^\s+//;
                   4949:     $name=~s/\s+$//;
                   4950:     $name=~s/\s+/ /g;
                   4951:     return $name;
                   4952: }
                   4953: 
1.84      www      4954: # ------------------------------------------------- Write to course preferences
                   4955: 
                   4956: sub writecoursepref {
                   4957:     my ($courseid,%prefs)=@_;
                   4958:     $courseid=~s/^\///;
                   4959:     $courseid=~s/\_/\//g;
                   4960:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   4961:     my $chome=homeserver($cnum,$cdomain);
                   4962:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   4963: 	return 'error: no such course';
                   4964:     }
                   4965:     my $cstring='';
1.800     albertel 4966:     foreach my $pref (keys(%prefs)) {
                   4967: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 4968:     }
1.84      www      4969:     $cstring=~s/\&$//;
                   4970:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   4971: }
                   4972: 
                   4973: # ---------------------------------------------------------- Make/modify course
                   4974: 
                   4975: sub createcourse {
1.741     raeburn  4976:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
                   4977:         $course_owner,$crstype)=@_;
1.84      www      4978:     $url=&declutter($url);
                   4979:     my $cid='';
1.264     matthew  4980:     unless (&allowed('ccc',$udom)) {
1.84      www      4981:         return 'refused';
                   4982:     }
                   4983: # ------------------------------------------------------------------- Create ID
1.674     www      4984:    my $uname=int(1+rand(9)).
                   4985:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   4986:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      4987:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   4988: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 4989:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      4990:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   4991:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   4992:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 4993:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      4994:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   4995:            return 'error: unable to generate unique course-ID';
                   4996:        } 
                   4997:    }
1.264     matthew  4998: # ------------------------------------------------ Check supplied server name
1.620     albertel 4999:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.264     matthew  5000:     if (! exists($libserv{$course_server})) {
                   5001:         return 'error:bad server name '.$course_server;
                   5002:     }
1.84      www      5003: # ------------------------------------------------------------- Make the course
                   5004:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  5005:                       $course_server);
1.84      www      5006:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 5007:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      5008:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5009: 	return 'error: no such course';
                   5010:     }
1.271     www      5011: # ----------------------------------------------------------------- Course made
1.516     raeburn  5012: # log existence
                   5013:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
1.741     raeburn  5014:                  ':'.&escape($inst_code).':'.&escape($course_owner).':'.
                   5015:                   &escape($crstype),$uhome);
1.358     www      5016:     &flushcourselogs();
                   5017: # set toplevel url
1.271     www      5018:     my $topurl=$url;
                   5019:     unless ($nonstandard) {
                   5020: # ------------------------------------------ For standard courses, make top url
                   5021:         my $mapurl=&clutter($url);
1.278     www      5022:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 5023:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      5024: <map>
                   5025: <resource id="1" type="start"></resource>
                   5026: <resource id="2" src="$mapurl"></resource>
                   5027: <resource id="3" type="finish"></resource>
                   5028: <link index="1" from="1" to="2"></link>
                   5029: <link index="2" from="2" to="3"></link>
                   5030: </map>
                   5031: ENDINITMAP
                   5032:         $topurl=&declutter(
1.638     albertel 5033:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      5034:                           );
                   5035:     }
                   5036: # ----------------------------------------------------------- Write preferences
1.84      www      5037:     &writecoursepref($udom.'_'.$uname,
                   5038:                      ('description' => $description,
1.271     www      5039:                       'url'         => $topurl));
1.84      www      5040:     return '/'.$udom.'/'.$uname;
                   5041: }
                   5042: 
1.813     albertel 5043: sub is_course {
                   5044:     my ($cdom,$cnum) = @_;
                   5045:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
                   5046: 				undef,'.');
                   5047:     if (exists($courses{$cdom.'_'.$cnum})) {
                   5048:         return 1;
                   5049:     }
                   5050:     return 0;
                   5051: }
                   5052: 
1.21      www      5053: # ---------------------------------------------------------- Assign Custom Role
                   5054: 
                   5055: sub assigncustomrole {
1.357     www      5056:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21      www      5057:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357     www      5058:                        $end,$start,$deleteflag);
1.21      www      5059: }
                   5060: 
                   5061: # ----------------------------------------------------------------- Revoke Role
                   5062: 
                   5063: sub revokerole {
1.357     www      5064:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21      www      5065:     my $now=time;
1.357     www      5066:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21      www      5067: }
                   5068: 
                   5069: # ---------------------------------------------------------- Revoke Custom Role
                   5070: 
                   5071: sub revokecustomrole {
1.357     www      5072:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21      www      5073:     my $now=time;
1.357     www      5074:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
                   5075:            $deleteflag);
1.17      www      5076: }
                   5077: 
1.533     banghart 5078: # ------------------------------------------------------------ Disk usage
1.535     albertel 5079: sub diskusage {
1.533     banghart 5080:     my ($udom,$uname,$directoryRoot)=@_;
                   5081:     $directoryRoot =~ s/\/$//;
1.535     albertel 5082:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
1.514     albertel 5083:     return $listing;
1.512     banghart 5084: }
                   5085: 
1.566     banghart 5086: sub is_locked {
                   5087:     my ($file_name, $domain, $user) = @_;
                   5088:     my @check;
                   5089:     my $is_locked;
                   5090:     push @check, $file_name;
1.613     albertel 5091:     my %locked = &get('file_permissions',\@check,
1.620     albertel 5092: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 5093:     my ($tmp)=keys(%locked);
                   5094:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  5095:     
1.566     banghart 5096:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  5097:         $is_locked = 'false';
                   5098:         foreach my $entry (@{$locked{$file_name}}) {
                   5099:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  5100:                $is_locked = 'true';
                   5101:                last;
1.745     raeburn  5102:            }
                   5103:        }
1.566     banghart 5104:     } else {
                   5105:         $is_locked = 'false';
                   5106:     }
                   5107: }
                   5108: 
1.759     albertel 5109: sub declutter_portfile {
                   5110:     my ($file) = @_;
                   5111:     &logthis("got $file");
                   5112:     $file =~ s-^(/portfolio/|portfolio/)-/-;
                   5113:     &logthis("ret $file");
                   5114:     return $file;
                   5115: }
                   5116: 
1.559     banghart 5117: # ------------------------------------------------------------- Mark as Read Only
                   5118: 
                   5119: sub mark_as_readonly {
                   5120:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 5121:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5122:     my ($tmp)=keys(%current_permissions);
                   5123:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 5124:     foreach my $file (@{$files}) {
1.759     albertel 5125: 	$file = &declutter_portfile($file);
1.561     banghart 5126:         push(@{$current_permissions{$file}},$what);
1.559     banghart 5127:     }
1.613     albertel 5128:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5129:     return;
                   5130: }
                   5131: 
1.572     banghart 5132: # ------------------------------------------------------------Save Selected Files
                   5133: 
                   5134: sub save_selected_files {
                   5135:     my ($user, $path, @files) = @_;
                   5136:     my $filename = $user."savedfiles";
1.573     banghart 5137:     my @other_files = &files_not_in_path($user, $path);
1.574     banghart 5138:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 5139:     foreach my $file (@files) {
1.620     albertel 5140:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 5141:     }
                   5142:     foreach my $file (@other_files) {
1.574     banghart 5143:         print (OUT $file."\n");
1.572     banghart 5144:     }
1.574     banghart 5145:     close (OUT);
1.572     banghart 5146:     return 'ok';
                   5147: }
                   5148: 
1.574     banghart 5149: sub clear_selected_files {
                   5150:     my ($user) = @_;
                   5151:     my $filename = $user."savedfiles";
                   5152:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5153:     print (OUT undef);
                   5154:     close (OUT);
                   5155:     return ("ok");    
                   5156: }
                   5157: 
1.572     banghart 5158: sub files_in_path {
                   5159:     my ($user, $path) = @_;
                   5160:     my $filename = $user."savedfiles";
                   5161:     my %return_files;
1.574     banghart 5162:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 5163:     while (my $line_in = <IN>) {
1.574     banghart 5164:         chomp ($line_in);
                   5165:         my @paths_and_file = split (m!/!, $line_in);
                   5166:         my $file_part = pop (@paths_and_file);
                   5167:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 5168:         $path_part.='/';
                   5169:         my $path_and_file = $path_part.$file_part;
                   5170:         if ($path_part eq $path) {
                   5171:             $return_files{$file_part}= 'selected';
                   5172:         }
                   5173:     }
1.574     banghart 5174:     close (IN);
                   5175:     return (\%return_files);
1.572     banghart 5176: }
                   5177: 
                   5178: # called in portfolio select mode, to show files selected NOT in current directory
                   5179: sub files_not_in_path {
                   5180:     my ($user, $path) = @_;
                   5181:     my $filename = $user."savedfiles";
                   5182:     my @return_files;
                   5183:     my $path_part;
1.800     albertel 5184:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5185:     while (my $line = <IN>) {
1.572     banghart 5186:         #ok, I know it's clunky, but I want it to work
1.800     albertel 5187:         my @paths_and_file = split(m|/|, $line);
                   5188:         my $file_part = pop(@paths_and_file);
                   5189:         chomp($file_part);
                   5190:         my $path_part = join('/', @paths_and_file);
1.572     banghart 5191:         $path_part .= '/';
                   5192:         my $path_and_file = $path_part.$file_part;
                   5193:         if ($path_part ne $path) {
1.800     albertel 5194:             push(@return_files, ($path_and_file));
1.572     banghart 5195:         }
                   5196:     }
1.800     albertel 5197:     close(OUT);
1.574     banghart 5198:     return (@return_files);
1.572     banghart 5199: }
                   5200: 
1.745     raeburn  5201: #----------------------------------------------Get portfolio file permissions
1.629     banghart 5202: 
1.745     raeburn  5203: sub get_portfile_permissions {
                   5204:     my ($domain,$user) = @_;
1.613     albertel 5205:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5206:     my ($tmp)=keys(%current_permissions);
                   5207:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5208:     return \%current_permissions;
                   5209: }
                   5210: 
                   5211: #---------------------------------------------Get portfolio file access controls
                   5212: 
1.749     raeburn  5213: sub get_access_controls {
1.745     raeburn  5214:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 5215:     my %access;
                   5216:     my $real_file = $file;
                   5217:     $file =~ s/\.meta$//;
1.745     raeburn  5218:     if (defined($file)) {
1.749     raeburn  5219:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   5220:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 5221:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  5222:             }
                   5223:         }
1.745     raeburn  5224:     } else {
1.749     raeburn  5225:         foreach my $key (keys(%{$current_permissions})) {
                   5226:             if ($key =~ /\0accesscontrol$/) {
                   5227:                 if (defined($group)) {
                   5228:                     if ($key !~ m-^\Q$group\E/-) {
                   5229:                         next;
                   5230:                     }
                   5231:                 }
                   5232:                 my ($fullpath) = split(/\0/,$key);
                   5233:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   5234:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   5235:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   5236:                     }
                   5237:                 }
                   5238:             }
                   5239:         }
                   5240:     }
                   5241:     return %access;
                   5242: }
                   5243: 
                   5244: sub modify_access_controls {
                   5245:     my ($file_name,$changes,$domain,$user)=@_;
                   5246:     my ($outcome,$deloutcome);
                   5247:     my %store_permissions;
                   5248:     my %new_values;
                   5249:     my %new_control;
                   5250:     my %translation;
                   5251:     my @deletions = ();
                   5252:     my $now = time;
                   5253:     if (exists($$changes{'activate'})) {
                   5254:         if (ref($$changes{'activate'}) eq 'HASH') {
                   5255:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   5256:             my $numnew = scalar(@newitems);
                   5257:             for (my $i=0; $i<$numnew; $i++) {
                   5258:                 my $newkey = $newitems[$i];
                   5259:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  5260:                 if ($newkey =~ /^\d+:/) { 
                   5261:                     $newkey =~ s/^(\d+)/$newid/;
                   5262:                     $translation{$1} = $newid;
                   5263:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   5264:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   5265:                     $translation{$1} = $newid;
                   5266:                 }
1.749     raeburn  5267:                 $new_values{$file_name."\0".$newkey} = 
                   5268:                                           $$changes{'activate'}{$newitems[$i]};
                   5269:                 $new_control{$newkey} = $now;
                   5270:             }
                   5271:         }
                   5272:     }
                   5273:     my %todelete;
                   5274:     my %changed_items;
                   5275:     foreach my $action ('delete','update') {
                   5276:         if (exists($$changes{$action})) {
                   5277:             if (ref($$changes{$action}) eq 'HASH') {
                   5278:                 foreach my $key (keys(%{$$changes{$action}})) {
                   5279:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   5280:                     if ($action eq 'delete') { 
                   5281:                         $todelete{$itemnum} = 1;
                   5282:                     } else {
                   5283:                         $changed_items{$itemnum} = $key;
                   5284:                     }
                   5285:                 }
1.745     raeburn  5286:             }
                   5287:         }
1.749     raeburn  5288:     }
                   5289:     # get lock on access controls for file.
                   5290:     my $lockhash = {
                   5291:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   5292:                                                        ':'.$env{'user.domain'},
                   5293:                    }; 
                   5294:     my $tries = 0;
                   5295:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5296:    
                   5297:     while (($gotlock ne 'ok') && $tries <3) {
                   5298:         $tries ++;
                   5299:         sleep 1;
                   5300:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5301:     }
                   5302:     if ($gotlock eq 'ok') {
                   5303:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   5304:         my ($tmp)=keys(%curr_permissions);
                   5305:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   5306:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   5307:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   5308:             if (ref($curr_controls) eq 'HASH') {
                   5309:                 foreach my $control_item (keys(%{$curr_controls})) {
                   5310:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   5311:                     if (defined($todelete{$itemnum})) {
                   5312:                         push(@deletions,$file_name."\0".$control_item);
                   5313:                     } else {
                   5314:                         if (defined($changed_items{$itemnum})) {
                   5315:                             $new_control{$changed_items{$itemnum}} = $now;
                   5316:                             push(@deletions,$file_name."\0".$control_item);
                   5317:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   5318:                         } else {
                   5319:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   5320:                         }
                   5321:                     }
1.745     raeburn  5322:                 }
                   5323:             }
                   5324:         }
1.749     raeburn  5325:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   5326:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   5327:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   5328:         #  remove lock
                   5329:         my @del_lock = ($file_name."\0".'locked_access_records');
                   5330:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  5331:         my ($file,$group);
                   5332:         if (&is_course($domain,$user)) {
                   5333:             ($group,$file) = split(/\//,$file_name,2);
                   5334:         } else {
                   5335:             $file = $file_name;
                   5336:         }
                   5337:         my $sqlresult =
                   5338:             &update_portfolio_table($user,$domain,$file,'portfolio_access',
                   5339:                                     $group);
1.749     raeburn  5340:     } else {
                   5341:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  5342:     }
1.749     raeburn  5343:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  5344: }
                   5345: 
1.827     raeburn  5346: sub make_public_indefinitely {
                   5347:     my ($requrl) = @_;
                   5348:     my $now = time;
                   5349:     my $action = 'activate';
                   5350:     my $aclnum = 0;
                   5351:     if (&is_portfolio_url($requrl)) {
                   5352:         my (undef,$udom,$unum,$file_name,$group) =
                   5353:             &parse_portfolio_url($requrl);
                   5354:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   5355:         my %access_controls = &get_access_controls($current_perms,
                   5356:                                                    $group,$file_name);
                   5357:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   5358:             my ($num,$scope,$end,$start) = 
                   5359:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   5360:             if ($scope eq 'public') {
                   5361:                 if ($start <= $now && $end == 0) {
                   5362:                     $action = 'none';
                   5363:                 } else {
                   5364:                     $action = 'update';
                   5365:                     $aclnum = $num;
                   5366:                 }
                   5367:                 last;
                   5368:             }
                   5369:         }
                   5370:         if ($action eq 'none') {
                   5371:              return 'ok';
                   5372:         } else {
                   5373:             my %changes;
                   5374:             my $newend = 0;
                   5375:             my $newstart = $now;
                   5376:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   5377:             $changes{$action}{$newkey} = {
                   5378:                 type => 'public',
                   5379:                 time => {
                   5380:                     start => $newstart,
                   5381:                     end   => $newend,
                   5382:                 },
                   5383:             };
                   5384:             my ($outcome,$deloutcome,$new_values,$translation) =
                   5385:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   5386:             return $outcome;
                   5387:         }
                   5388:     } else {
                   5389:         return 'invalid';
                   5390:     }
                   5391: }
                   5392: 
1.745     raeburn  5393: #------------------------------------------------------Get Marked as Read Only
                   5394: 
                   5395: sub get_marked_as_readonly {
                   5396:     my ($domain,$user,$what,$group) = @_;
                   5397:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 5398:     my @readonly_files;
1.629     banghart 5399:     my $cmp1=$what;
                   5400:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  5401:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5402:         if (defined($group)) {
                   5403:             if ($file_name !~ m-^\Q$group\E/-) {
                   5404:                 next;
                   5405:             }
                   5406:         }
1.561     banghart 5407:         if (ref($value) eq "ARRAY"){
                   5408:             foreach my $stored_what (@{$value}) {
1.629     banghart 5409:                 my $cmp2=$stored_what;
1.759     albertel 5410:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  5411:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  5412:                 }
1.629     banghart 5413:                 if ($cmp1 eq $cmp2) {
1.561     banghart 5414:                     push(@readonly_files, $file_name);
1.745     raeburn  5415:                     last;
1.563     banghart 5416:                 } elsif (!defined($what)) {
                   5417:                     push(@readonly_files, $file_name);
1.745     raeburn  5418:                     last;
1.561     banghart 5419:                 }
                   5420:             }
1.745     raeburn  5421:         }
1.561     banghart 5422:     }
                   5423:     return @readonly_files;
                   5424: }
1.577     banghart 5425: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 5426: 
1.577     banghart 5427: sub get_marked_as_readonly_hash {
1.745     raeburn  5428:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 5429:     my %readonly_files;
1.745     raeburn  5430:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5431:         if (defined($group)) {
                   5432:             if ($file_name !~ m-^\Q$group\E/-) {
                   5433:                 next;
                   5434:             }
                   5435:         }
1.577     banghart 5436:         if (ref($value) eq "ARRAY"){
                   5437:             foreach my $stored_what (@{$value}) {
1.745     raeburn  5438:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 5439:                     foreach my $lock_descriptor(@{$stored_what}) {
                   5440:                         if ($lock_descriptor eq 'graded') {
                   5441:                             $readonly_files{$file_name} = 'graded';
                   5442:                         } elsif ($lock_descriptor eq 'handback') {
                   5443:                             $readonly_files{$file_name} = 'handback';
                   5444:                         } else {
                   5445:                             if (!exists($readonly_files{$file_name})) {
                   5446:                                 $readonly_files{$file_name} = 'locked';
                   5447:                             }
                   5448:                         }
1.745     raeburn  5449:                     }
1.750     banghart 5450:                 } 
1.577     banghart 5451:             }
                   5452:         } 
                   5453:     }
                   5454:     return %readonly_files;
                   5455: }
1.559     banghart 5456: # ------------------------------------------------------------ Unmark as Read Only
                   5457: 
                   5458: sub unmark_as_readonly {
1.629     banghart 5459:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   5460:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  5461:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 5462:     $file_name = &declutter_portfile($file_name);
1.634     albertel 5463:     my $symb_crs = $what;
                   5464:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  5465:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 5466:     my ($tmp)=keys(%current_permissions);
                   5467:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5468:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 5469:     foreach my $file (@readonly_files) {
1.759     albertel 5470: 	my $clean_file = &declutter_portfile($file);
                   5471: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 5472: 	my $current_locks = $current_permissions{$file};
1.563     banghart 5473:         my @new_locks;
                   5474:         my @del_keys;
                   5475:         if (ref($current_locks) eq "ARRAY"){
                   5476:             foreach my $locker (@{$current_locks}) {
1.632     albertel 5477:                 my $compare=$locker;
1.749     raeburn  5478:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  5479:                     $compare=join('',@{$locker});
1.746     raeburn  5480:                     if ($compare ne $symb_crs) {
                   5481:                         push(@new_locks, $locker);
                   5482:                     }
1.563     banghart 5483:                 }
                   5484:             }
1.650     albertel 5485:             if (scalar(@new_locks) > 0) {
1.563     banghart 5486:                 $current_permissions{$file} = \@new_locks;
                   5487:             } else {
                   5488:                 push(@del_keys, $file);
1.613     albertel 5489:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 5490:                 delete($current_permissions{$file});
1.563     banghart 5491:             }
                   5492:         }
1.561     banghart 5493:     }
1.613     albertel 5494:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5495:     return;
                   5496: }
1.512     banghart 5497: 
1.17      www      5498: # ------------------------------------------------------------ Directory lister
                   5499: 
                   5500: sub dirlist {
1.253     stredwic 5501:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
                   5502: 
1.18      www      5503:     $uri=~s/^\///;
                   5504:     $uri=~s/\/$//;
1.253     stredwic 5505:     my ($udom, $uname);
                   5506:     (undef,$udom,$uname)=split(/\//,$uri);
                   5507:     if(defined($userdomain)) {
                   5508:         $udom = $userdomain;
                   5509:     }
                   5510:     if(defined($username)) {
                   5511:         $uname = $username;
                   5512:     }
                   5513: 
                   5514:     my $dirRoot = $perlvar{'lonDocRoot'};
                   5515:     if(defined($alternateDirectoryRoot)) {
                   5516:         $dirRoot = $alternateDirectoryRoot;
                   5517:         $dirRoot =~ s/\/$//;
1.751     banghart 5518:     }
1.253     stredwic 5519: 
                   5520:     if($udom) {
                   5521:         if($uname) {
1.800     albertel 5522:             my $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   5523: 				 &homeserver($uname,$udom));
1.605     matthew  5524:             my @listing_results;
                   5525:             if ($listing eq 'unknown_cmd') {
1.800     albertel 5526:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   5527: 				  &homeserver($uname,$udom));
1.605     matthew  5528:                 @listing_results = split(/:/,$listing);
                   5529:             } else {
                   5530:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   5531:             }
                   5532:             return @listing_results;
1.253     stredwic 5533:         } elsif(!defined($alternateDirectoryRoot)) {
1.800     albertel 5534:             my %allusers;
                   5535:             foreach my $tryserver (keys(%libserv)) {
1.253     stredwic 5536:                 if($hostdom{$tryserver} eq $udom) {
1.800     albertel 5537:                     my $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   5538: 					 $udom, $tryserver);
1.605     matthew  5539:                     my @listing_results;
                   5540:                     if ($listing eq 'unknown_cmd') {
1.800     albertel 5541:                         $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   5542: 					  $udom, $tryserver);
1.605     matthew  5543:                         @listing_results = split(/:/,$listing);
                   5544:                     } else {
                   5545:                         @listing_results =
                   5546:                             map { &unescape($_); } split(/:/,$listing);
                   5547:                     }
                   5548:                     if ($listing_results[0] ne 'no_such_dir' && 
                   5549:                         $listing_results[0] ne 'empty'       &&
                   5550:                         $listing_results[0] ne 'con_lost') {
1.800     albertel 5551:                         foreach my $line (@listing_results) {
                   5552:                             my ($entry) = split(/&/,$line,2);
                   5553:                             $allusers{$entry} = 1;
1.253     stredwic 5554:                         }
                   5555:                     }
1.191     harris41 5556:                 }
1.253     stredwic 5557:             }
                   5558:             my $alluserstr='';
1.800     albertel 5559:             foreach my $user (sort(keys(%allusers))) {
                   5560:                 $alluserstr.=$user.'&user:';
1.253     stredwic 5561:             }
                   5562:             $alluserstr=~s/:$//;
                   5563:             return split(/:/,$alluserstr);
                   5564:         } else {
1.800     albertel 5565:             return ('missing user name');
1.253     stredwic 5566:         }
                   5567:     } elsif(!defined($alternateDirectoryRoot)) {
                   5568:         my $tryserver;
                   5569:         my %alldom=();
1.800     albertel 5570:         foreach $tryserver (keys(%libserv)) {
1.253     stredwic 5571:             $alldom{$hostdom{$tryserver}}=1;
                   5572:         }
                   5573:         my $alldomstr='';
1.800     albertel 5574:         foreach my $domain (sort(keys(%alldom))) {
                   5575:             $alldomstr.=$perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain:';
1.253     stredwic 5576:         }
                   5577:         $alldomstr=~s/:$//;
                   5578:         return split(/:/,$alldomstr);       
                   5579:     } else {
1.800     albertel 5580:         return ('missing domain');
1.275     stredwic 5581:     }
                   5582: }
                   5583: 
                   5584: # --------------------------------------------- GetFileTimestamp
                   5585: # This function utilizes dirlist and returns the date stamp for
                   5586: # when it was last modified.  It will also return an error of -1
                   5587: # if an error occurs
                   5588: 
1.410     matthew  5589: ##
                   5590: ## FIXME: This subroutine assumes its caller knows something about the
                   5591: ## directory structure of the home server for the student ($root).
                   5592: ## Not a good assumption to make.  Since this is for looking up files
                   5593: ## in user directories, the full path should be constructed by lond, not
                   5594: ## whatever machine we request data from.
                   5595: ##
1.275     stredwic 5596: sub GetFileTimestamp {
                   5597:     my ($studentDomain,$studentName,$filename,$root)=@_;
1.807     albertel 5598:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   5599:     $studentName   = &LONCAPA::clean_username($studentName);
1.275     stredwic 5600:     my $subdir=$studentName.'__';
                   5601:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   5602:     my $proname="$studentDomain/$subdir/$studentName";
                   5603:     $proname .= '/'.$filename;
1.375     matthew  5604:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
                   5605:                                               $studentName, $root);
1.275     stredwic 5606:     my @stats = split('&', $fileStat);
                   5607:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  5608:         # @stats contains first the filename, then the stat output
                   5609:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 5610:     } else {
                   5611:         return -1;
1.253     stredwic 5612:     }
1.26      www      5613: }
                   5614: 
1.712     albertel 5615: sub stat_file {
                   5616:     my ($uri) = @_;
1.787     albertel 5617:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 5618: 
1.712     albertel 5619:     my ($udom,$uname,$file,$dir);
                   5620:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   5621: 	($udom,$uname,$file) =
1.811     albertel 5622: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 5623: 	$file = 'userfiles/'.$file;
1.740     www      5624: 	$dir = &propath($udom,$uname);
1.712     albertel 5625:     }
                   5626:     if ($uri =~ m-^/res/-) {
                   5627: 	($udom,$uname) = 
1.807     albertel 5628: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 5629: 	$file = $uri;
                   5630:     }
                   5631: 
                   5632:     if (!$udom || !$uname || !$file) {
                   5633: 	# unable to handle the uri
                   5634: 	return ();
                   5635:     }
                   5636: 
                   5637:     my ($result) = &dirlist($file,$udom,$uname,$dir);
                   5638:     my @stats = split('&', $result);
1.721     banghart 5639:     
1.712     albertel 5640:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   5641: 	shift(@stats); #filename is first
                   5642: 	return @stats;
                   5643:     }
                   5644:     return ();
                   5645: }
                   5646: 
1.26      www      5647: # -------------------------------------------------------- Value of a Condition
                   5648: 
1.713     albertel 5649: # gets the value of a specific preevaluated condition
                   5650: #    stored in the string  $env{user.state.<cid>}
                   5651: # or looks up a condition reference in the bighash and if if hasn't
                   5652: # already been evaluated recurses into docondval to get the value of
                   5653: # the condition, then memoizing it to 
                   5654: #   $env{user.state.<cid>.<condition>}
1.40      www      5655: sub directcondval {
                   5656:     my $number=shift;
1.620     albertel 5657:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 5658: 	&Apache::lonuserstate::evalstate();
                   5659:     }
1.713     albertel 5660:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   5661: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   5662:     } elsif ($number =~ /^_/) {
                   5663: 	my $sub_condition;
                   5664: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   5665: 		&GDBM_READER(),0640)) {
                   5666: 	    $sub_condition=$bighash{'conditions'.$number};
                   5667: 	    untie(%bighash);
                   5668: 	}
                   5669: 	my $value = &docondval($sub_condition);
                   5670: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
                   5671: 	return $value;
                   5672:     }
1.620     albertel 5673:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   5674:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      5675:     } else {
                   5676:        return 2;
                   5677:     }
                   5678: }
                   5679: 
1.713     albertel 5680: # get the collection of conditions for this resource
1.26      www      5681: sub condval {
                   5682:     my $condidx=shift;
1.54      www      5683:     my $allpathcond='';
1.713     albertel 5684:     foreach my $cond (split(/\|/,$condidx)) {
                   5685: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   5686: 	    $allpathcond.=
                   5687: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   5688: 	}
1.191     harris41 5689:     }
1.54      www      5690:     $allpathcond=~s/\|$//;
1.713     albertel 5691:     return &docondval($allpathcond);
                   5692: }
                   5693: 
                   5694: #evaluates an expression of conditions
                   5695: sub docondval {
                   5696:     my ($allpathcond) = @_;
                   5697:     my $result=0;
                   5698:     if ($env{'request.course.id'}
                   5699: 	&& defined($allpathcond)) {
                   5700: 	my $operand='|';
                   5701: 	my @stack;
                   5702: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   5703: 	    if ($chunk eq '(') {
                   5704: 		push @stack,($operand,$result);
                   5705: 	    } elsif ($chunk eq ')') {
                   5706: 		my $before=pop @stack;
                   5707: 		if (pop @stack eq '&') {
                   5708: 		    $result=$result>$before?$before:$result;
                   5709: 		} else {
                   5710: 		    $result=$result>$before?$result:$before;
                   5711: 		}
                   5712: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   5713: 		$operand=$chunk;
                   5714: 	    } else {
                   5715: 		my $new=directcondval($chunk);
                   5716: 		if ($operand eq '&') {
                   5717: 		    $result=$result>$new?$new:$result;
                   5718: 		} else {
                   5719: 		    $result=$result>$new?$result:$new;
                   5720: 		}
                   5721: 	    }
                   5722: 	}
1.26      www      5723:     }
                   5724:     return $result;
1.421     albertel 5725: }
                   5726: 
                   5727: # ---------------------------------------------------- Devalidate courseresdata
                   5728: 
                   5729: sub devalidatecourseresdata {
                   5730:     my ($coursenum,$coursedomain)=@_;
                   5731:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 5732:     &devalidate_cache_new('courseres',$hashid);
1.28      www      5733: }
                   5734: 
1.763     www      5735: 
1.200     www      5736: # --------------------------------------------------- Course Resourcedata Query
                   5737: 
1.624     albertel 5738: sub get_courseresdata {
                   5739:     my ($coursenum,$coursedomain)=@_;
1.200     www      5740:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   5741:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 5742:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 5743:     my %dumpreply;
1.417     albertel 5744:     unless (defined($cached)) {
1.624     albertel 5745: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 5746: 	$result=\%dumpreply;
1.251     albertel 5747: 	my ($tmp) = keys(%dumpreply);
                   5748: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 5749: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 5750: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   5751: 	    return $tmp;
1.416     albertel 5752: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 5753: 	    $result=undef;
1.599     albertel 5754: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 5755: 	}
                   5756:     }
1.624     albertel 5757:     return $result;
                   5758: }
                   5759: 
1.633     albertel 5760: sub devalidateuserresdata {
                   5761:     my ($uname,$udom)=@_;
                   5762:     my $hashid="$udom:$uname";
                   5763:     &devalidate_cache_new('userres',$hashid);
                   5764: }
                   5765: 
1.624     albertel 5766: sub get_userresdata {
                   5767:     my ($uname,$udom)=@_;
                   5768:     #most student don\'t have any data set, check if there is some data
                   5769:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   5770: 
                   5771:     my $hashid="$udom:$uname";
                   5772:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   5773:     if (!defined($cached)) {
                   5774: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   5775: 	$result=\%resourcedata;
                   5776: 	&do_cache_new('userres',$hashid,$result,600);
                   5777:     }
                   5778:     my ($tmp)=keys(%$result);
                   5779:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   5780: 	return $result;
                   5781:     }
                   5782:     #error 2 occurs when the .db doesn't exist
                   5783:     if ($tmp!~/error: 2 /) {
1.672     albertel 5784: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 5785: 		 " Trying to get resource data for ".
                   5786: 		 $uname." at ".$udom.": ".
                   5787: 		 $tmp."</font>");
                   5788:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 5789: 	#&EXT_cache_set($udom,$uname);
                   5790: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 5791: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 5792:     }
                   5793:     return $tmp;
                   5794: }
                   5795: 
                   5796: sub resdata {
                   5797:     my ($name,$domain,$type,@which)=@_;
                   5798:     my $result;
                   5799:     if ($type eq 'course') {
                   5800: 	$result=&get_courseresdata($name,$domain);
                   5801:     } elsif ($type eq 'user') {
                   5802: 	$result=&get_userresdata($name,$domain);
                   5803:     }
                   5804:     if (!ref($result)) { return $result; }    
1.251     albertel 5805:     foreach my $item (@which) {
1.417     albertel 5806: 	if (defined($result->{$item})) {
                   5807: 	    return $result->{$item};
1.251     albertel 5808: 	}
1.250     albertel 5809:     }
1.291     albertel 5810:     return undef;
1.200     www      5811: }
                   5812: 
1.379     matthew  5813: #
                   5814: # EXT resource caching routines
                   5815: #
                   5816: 
                   5817: sub clear_EXT_cache_status {
1.383     albertel 5818:     &delenv('cache.EXT.');
1.379     matthew  5819: }
                   5820: 
                   5821: sub EXT_cache_status {
                   5822:     my ($target_domain,$target_user) = @_;
1.383     albertel 5823:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 5824:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  5825:         # We know already the user has no data
                   5826:         return 1;
                   5827:     } else {
                   5828:         return 0;
                   5829:     }
                   5830: }
                   5831: 
                   5832: sub EXT_cache_set {
                   5833:     my ($target_domain,$target_user) = @_;
1.383     albertel 5834:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.633     albertel 5835:     #&appenv($cachename => time);
1.379     matthew  5836: }
                   5837: 
1.28      www      5838: # --------------------------------------------------------- Value of a Variable
1.58      www      5839: sub EXT {
1.715     albertel 5840: 
1.395     albertel 5841:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      5842:     unless ($varname) { return ''; }
1.218     albertel 5843:     #get real user name/domain, courseid and symb
                   5844:     my $courseid;
1.359     albertel 5845:     my $publicuser;
1.427     www      5846:     if ($symbparm) {
                   5847: 	$symbparm=&get_symb_from_alias($symbparm);
                   5848:     }
1.218     albertel 5849:     if (!($uname && $udom)) {
1.790     albertel 5850:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 5851:       if (!$symbparm) {	$symbparm=$cursymb; }
                   5852:     } else {
1.620     albertel 5853: 	$courseid=$env{'request.course.id'};
1.218     albertel 5854:     }
1.48      www      5855:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   5856:     my $rest;
1.320     albertel 5857:     if (defined($therest[0])) {
1.48      www      5858:        $rest=join('.',@therest);
                   5859:     } else {
                   5860:        $rest='';
                   5861:     }
1.320     albertel 5862: 
1.57      www      5863:     my $qualifierrest=$qualifier;
                   5864:     if ($rest) { $qualifierrest.='.'.$rest; }
                   5865:     my $spacequalifierrest=$space;
                   5866:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      5867:     if ($realm eq 'user') {
1.48      www      5868: # --------------------------------------------------------------- user.resource
                   5869: 	if ($space eq 'resource') {
1.651     albertel 5870: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   5871: 		  || defined($Apache::lonhomework::parsing_a_task))
                   5872: 		 &&
1.744     albertel 5873: 		 ($symbparm eq &symbread()) ) {	
                   5874: 		# if we are in the middle of processing the resource the
                   5875: 		# get the value we are planning on committing
                   5876:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   5877:                     return $Apache::lonhomework::results{$qualifierrest};
                   5878:                 } else {
                   5879:                     return $Apache::lonhomework::history{$qualifierrest};
                   5880:                 }
1.335     albertel 5881: 	    } else {
1.359     albertel 5882: 		my %restored;
1.620     albertel 5883: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 5884: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   5885: 		} else {
                   5886: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   5887: 		}
1.335     albertel 5888: 		return $restored{$qualifierrest};
                   5889: 	    }
1.48      www      5890: # ----------------------------------------------------------------- user.access
                   5891:         } elsif ($space eq 'access') {
1.218     albertel 5892: 	    # FIXME - not supporting calls for a specific user
1.48      www      5893:             return &allowed($qualifier,$rest);
                   5894: # ------------------------------------------ user.preferences, user.environment
                   5895:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 5896: 	    if (($uname eq $env{'user.name'}) &&
                   5897: 		($udom eq $env{'user.domain'})) {
                   5898: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 5899: 	    } else {
1.359     albertel 5900: 		my %returnhash;
                   5901: 		if (!$publicuser) {
                   5902: 		    %returnhash=&userenvironment($udom,$uname,
                   5903: 						 $qualifierrest);
                   5904: 		}
1.218     albertel 5905: 		return $returnhash{$qualifierrest};
                   5906: 	    }
1.48      www      5907: # ----------------------------------------------------------------- user.course
                   5908:         } elsif ($space eq 'course') {
1.218     albertel 5909: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 5910:             return $env{join('.',('request.course',$qualifier))};
1.48      www      5911: # ------------------------------------------------------------------- user.role
                   5912:         } elsif ($space eq 'role') {
1.218     albertel 5913: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 5914:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      5915:             if ($qualifier eq 'value') {
                   5916: 		return $role;
                   5917:             } elsif ($qualifier eq 'extent') {
                   5918:                 return $where;
                   5919:             }
                   5920: # ----------------------------------------------------------------- user.domain
                   5921:         } elsif ($space eq 'domain') {
1.218     albertel 5922:             return $udom;
1.48      www      5923: # ------------------------------------------------------------------- user.name
                   5924:         } elsif ($space eq 'name') {
1.218     albertel 5925:             return $uname;
1.48      www      5926: # ---------------------------------------------------- Any other user namespace
1.29      www      5927:         } else {
1.359     albertel 5928: 	    my %reply;
                   5929: 	    if (!$publicuser) {
                   5930: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   5931: 	    }
                   5932: 	    return $reply{$qualifierrest};
1.48      www      5933:         }
1.236     www      5934:     } elsif ($realm eq 'query') {
                   5935: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 5936:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   5937: 						[$spacequalifierrest]);
1.620     albertel 5938: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      5939:    } elsif ($realm eq 'request') {
1.48      www      5940: # ------------------------------------------------------------- request.browser
                   5941:         if ($space eq 'browser') {
1.430     www      5942: 	    if ($qualifier eq 'textremote') {
1.676     albertel 5943: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      5944: 		    return 1;
                   5945: 		} else {
                   5946: 		    return 0;
                   5947: 		}
                   5948: 	    } else {
1.620     albertel 5949: 		return $env{'browser.'.$qualifier};
1.430     www      5950: 	    }
1.57      www      5951: # ------------------------------------------------------------ request.filename
                   5952:         } else {
1.620     albertel 5953:             return $env{'request.'.$spacequalifierrest};
1.29      www      5954:         }
1.28      www      5955:     } elsif ($realm eq 'course') {
1.48      www      5956: # ---------------------------------------------------------- course.description
1.620     albertel 5957:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      5958:     } elsif ($realm eq 'resource') {
1.165     www      5959: 
1.620     albertel 5960: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 5961: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   5962: 	}
1.693     albertel 5963: 
                   5964: 	if ($space eq 'title') {
                   5965: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   5966: 	    return &gettitle($symbparm);
                   5967: 	}
                   5968: 	
                   5969: 	if ($space eq 'map') {
                   5970: 	    my ($map) = &decode_symb($symbparm);
                   5971: 	    return &symbread($map);
                   5972: 	}
                   5973: 
                   5974: 	my ($section, $group, @groups);
1.593     albertel 5975: 	my ($courselevelm,$courselevel);
1.539     albertel 5976: 	if ($symbparm && defined($courseid) && 
1.620     albertel 5977: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      5978: 
1.218     albertel 5979: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      5980: 
1.60      www      5981: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 5982: 	    my $symbp=$symbparm;
1.735     albertel 5983: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 5984: 
                   5985: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   5986: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   5987: 
1.620     albertel 5988: 	    if (($env{'user.name'} eq $uname) &&
                   5989: 		($env{'user.domain'} eq $udom)) {
                   5990: 		$section=$env{'request.course.sec'};
1.733     raeburn  5991:                 @groups = split(/:/,$env{'request.course.groups'});  
                   5992:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 5993: 	    } else {
1.539     albertel 5994: 		if (! defined($usection)) {
1.551     albertel 5995: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 5996: 		} else {
                   5997: 		    $section = $usection;
                   5998: 		}
1.733     raeburn  5999:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 6000: 	    }
                   6001: 
                   6002: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   6003: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   6004: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   6005: 
1.593     albertel 6006: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 6007: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 6008: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      6009: 
1.60      www      6010: # ----------------------------------------------------------- first, check user
1.624     albertel 6011: 
                   6012: 	    my $userreply=&resdata($uname,$udom,'user',
                   6013: 				       ($courselevelr,$courselevelm,
                   6014: 					$courselevel));
                   6015: 	    if (defined($userreply)) { return $userreply; }
1.95      www      6016: 
1.594     albertel 6017: # ------------------------------------------------ second, check some of course
1.684     raeburn  6018:             my $coursereply;
1.691     raeburn  6019:             if (@groups > 0) {
                   6020:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   6021:                                        $mapparm,$spacequalifierrest);
1.684     raeburn  6022:                 if (defined($coursereply)) { return $coursereply; }
                   6023:             }
1.96      www      6024: 
1.684     raeburn  6025: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.624     albertel 6026: 				     $env{'course.'.$courseid.'.domain'},
                   6027: 				     'course',
                   6028: 				     ($seclevelr,$seclevelm,$seclevel,
                   6029: 				      $courselevelr));
1.287     albertel 6030: 	    if (defined($coursereply)) { return $coursereply; }
1.200     www      6031: 
1.60      www      6032: # ------------------------------------------------------ third, check map parms
1.218     albertel 6033: 	    my %parmhash=();
                   6034: 	    my $thisparm='';
                   6035: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 6036: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 6037: 		    &GDBM_READER(),0640)) {
1.218     albertel 6038: 		$thisparm=$parmhash{$symbparm};
                   6039: 		untie(%parmhash);
                   6040: 	    }
                   6041: 	    if ($thisparm) { return $thisparm; }
                   6042: 	}
1.594     albertel 6043: # ------------------------------------------ fourth, look in resource metadata
1.71      www      6044: 
1.218     albertel 6045: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 6046: 	my $filename;
                   6047: 	if (!$symbparm) { $symbparm=&symbread(); }
                   6048: 	if ($symbparm) {
1.409     www      6049: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 6050: 	} else {
1.620     albertel 6051: 	    $filename=$env{'request.filename'};
1.282     albertel 6052: 	}
                   6053: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.288     albertel 6054: 	if (defined($metadata)) { return $metadata; }
1.282     albertel 6055: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.288     albertel 6056: 	if (defined($metadata)) { return $metadata; }
1.142     www      6057: 
1.594     albertel 6058: # ---------------------------------------------- fourth, look in rest pf course
1.593     albertel 6059: 	if ($symbparm && defined($courseid) && 
1.620     albertel 6060: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 6061: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   6062: 				     $env{'course.'.$courseid.'.domain'},
                   6063: 				     'course',
                   6064: 				     ($courselevelm,$courselevel));
1.593     albertel 6065: 	    if (defined($coursereply)) { return $coursereply; }
                   6066: 	}
1.145     www      6067: # ------------------------------------------------------------------ Cascade up
1.218     albertel 6068: 	unless ($space eq '0') {
1.336     albertel 6069: 	    my @parts=split(/_/,$space);
                   6070: 	    my $id=pop(@parts);
                   6071: 	    my $part=join('_',@parts);
                   6072: 	    if ($part eq '') { $part='0'; }
                   6073: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 6074: 				 $symbparm,$udom,$uname,$section,1);
1.337     albertel 6075: 	    if (defined($partgeneral)) { return $partgeneral; }
1.218     albertel 6076: 	}
1.395     albertel 6077: 	if ($recurse) { return undef; }
                   6078: 	my $pack_def=&packages_tab_default($filename,$varname);
                   6079: 	if (defined($pack_def)) { return $pack_def; }
1.71      www      6080: 
1.48      www      6081: # ---------------------------------------------------- Any other user namespace
                   6082:     } elsif ($realm eq 'environment') {
                   6083: # ----------------------------------------------------------------- environment
1.620     albertel 6084: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   6085: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 6086: 	} else {
1.770     albertel 6087: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   6088: 		return '';
                   6089: 	    }
1.219     albertel 6090: 	    my %returnhash=&userenvironment($udom,$uname,
                   6091: 					    $spacequalifierrest);
                   6092: 	    return $returnhash{$spacequalifierrest};
                   6093: 	}
1.28      www      6094:     } elsif ($realm eq 'system') {
1.48      www      6095: # ----------------------------------------------------------------- system.time
                   6096: 	if ($space eq 'time') {
                   6097: 	    return time;
                   6098:         }
1.696     albertel 6099:     } elsif ($realm eq 'server') {
                   6100: # ----------------------------------------------------------------- system.time
                   6101: 	if ($space eq 'name') {
                   6102: 	    return $ENV{'SERVER_NAME'};
                   6103:         }
1.28      www      6104:     }
1.48      www      6105:     return '';
1.61      www      6106: }
                   6107: 
1.691     raeburn  6108: sub check_group_parms {
                   6109:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   6110:     my @groupitems = ();
                   6111:     my $resultitem;
                   6112:     my @levels = ($symbparm,$mapparm,$what);
                   6113:     foreach my $group (@{$groups}) {
                   6114:         foreach my $level (@levels) {
                   6115:              my $item = $courseid.'.['.$group.'].'.$level;
                   6116:              push(@groupitems,$item);
                   6117:         }
                   6118:     }
                   6119:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   6120:                             $env{'course.'.$courseid.'.domain'},
                   6121:                                      'course',@groupitems);
                   6122:     return $coursereply;
                   6123: }
                   6124: 
                   6125: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  6126:     my ($courseid,@groups) = @_;
                   6127:     @groups = sort(@groups);
1.691     raeburn  6128:     return @groups;
                   6129: }
                   6130: 
1.395     albertel 6131: sub packages_tab_default {
                   6132:     my ($uri,$varname)=@_;
                   6133:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 6134: 
                   6135:     my (@extension,@specifics,$do_default);
                   6136:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 6137: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 6138: 	if ($pack_type eq 'default') {
                   6139: 	    $do_default=1;
                   6140: 	} elsif ($pack_type eq 'extension') {
                   6141: 	    push(@extension,[$package,$pack_type,$pack_part]);
                   6142: 	} else {
                   6143: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   6144: 	}
                   6145:     }
                   6146:     # first look for a package that matches the requested part id
                   6147:     foreach my $package (@specifics) {
                   6148: 	my (undef,$pack_type,$pack_part)=@{$package};
                   6149: 	next if ($pack_part ne $part);
                   6150: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6151: 	    return $packagetab{"$pack_type&$name&default"};
                   6152: 	}
                   6153:     }
                   6154:     # look for any possible matching non extension_ package
                   6155:     foreach my $package (@specifics) {
                   6156: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 6157: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6158: 	    return $packagetab{"$pack_type&$name&default"};
                   6159: 	}
1.585     albertel 6160: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 6161: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   6162: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 6163: 	}
                   6164:     }
1.738     albertel 6165:     # look for any posible extension_ match
                   6166:     foreach my $package (@extension) {
                   6167: 	my ($package,$pack_type)=@{$package};
                   6168: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6169: 	    return $packagetab{"$pack_type&$name&default"};
                   6170: 	}
                   6171: 	if (defined($packagetab{$package."&$name&default"})) {
                   6172: 	    return $packagetab{$package."&$name&default"};
                   6173: 	}
                   6174:     }
                   6175:     # look for a global default setting
                   6176:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   6177: 	return $packagetab{"default&$name&default"};
                   6178:     }
1.395     albertel 6179:     return undef;
                   6180: }
                   6181: 
1.334     albertel 6182: sub add_prefix_and_part {
                   6183:     my ($prefix,$part)=@_;
                   6184:     my $keyroot;
                   6185:     if (defined($prefix) && $prefix !~ /^__/) {
                   6186: 	# prefix that has a part already
                   6187: 	$keyroot=$prefix;
                   6188:     } elsif (defined($prefix)) {
                   6189: 	# prefix that is missing a part
                   6190: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   6191:     } else {
                   6192: 	# no prefix at all
                   6193: 	if (defined($part)) { $keyroot='_'.$part; }
                   6194:     }
                   6195:     return $keyroot;
                   6196: }
                   6197: 
1.71      www      6198: # ---------------------------------------------------------------- Get metadata
                   6199: 
1.599     albertel 6200: my %metaentry;
1.71      www      6201: sub metadata {
1.176     www      6202:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      6203:     $uri=&declutter($uri);
1.288     albertel 6204:     # if it is a non metadata possible uri return quickly
1.529     albertel 6205:     if (($uri eq '') || 
                   6206: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 6207: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.423     albertel 6208:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
1.807     albertel 6209: 	($uri =~ m|home/$match_username/public_html/|)) {
1.468     albertel 6210: 	return undef;
1.288     albertel 6211:     }
1.73      www      6212:     my $filename=$uri;
                   6213:     $uri=~s/\.meta$//;
1.172     www      6214: #
                   6215: # Is the metadata already cached?
1.177     www      6216: # Look at timestamp of caching
1.172     www      6217: # Everything is cached by the main uri, libraries are never directly cached
                   6218: #
1.428     albertel 6219:     if (!defined($liburi)) {
1.599     albertel 6220: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 6221: 	if (defined($cached)) { return $result->{':'.$what}; }
                   6222:     }
                   6223:     {
1.172     www      6224: #
                   6225: # Is this a recursive call for a library?
                   6226: #
1.599     albertel 6227: #	if (! exists($metacache{$uri})) {
                   6228: #	    $metacache{$uri}={};
                   6229: #	}
1.171     www      6230:         if ($liburi) {
                   6231: 	    $liburi=&declutter($liburi);
                   6232:             $filename=$liburi;
1.401     bowersj2 6233:         } else {
1.599     albertel 6234: 	    &devalidate_cache_new('meta',$uri);
                   6235: 	    undef(%metaentry);
1.401     bowersj2 6236: 	}
1.140     www      6237:         my %metathesekeys=();
1.73      www      6238:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 6239: 	my $metastring;
1.768     albertel 6240: 	if ($uri !~ m -^(editupload)/-) {
1.543     albertel 6241: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 6242: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 6243: 	    $metastring=&getfile($file);
1.489     albertel 6244: 	}
1.208     albertel 6245:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      6246:         my $token;
1.140     www      6247:         undef %metathesekeys;
1.71      www      6248:         while ($token=$parser->get_token) {
1.339     albertel 6249: 	    if ($token->[0] eq 'S') {
                   6250: 		if (defined($token->[2]->{'package'})) {
1.172     www      6251: #
                   6252: # This is a package - get package info
                   6253: #
1.339     albertel 6254: 		    my $package=$token->[2]->{'package'};
                   6255: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6256: 		    if (defined($token->[2]->{'id'})) { 
                   6257: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   6258: 		    }
1.599     albertel 6259: 		    if ($metaentry{':packages'}) {
                   6260: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 6261: 		    } else {
1.599     albertel 6262: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 6263: 		    }
1.736     albertel 6264: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 6265: 			my $part=$keyroot;
                   6266: 			$part=~s/^\_//;
1.736     albertel 6267: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   6268: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   6269: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 6270: 			    # ignore package.tab specified default values
                   6271:                             # here &package_tab_default() will fetch those
                   6272: 			    if ($subp eq 'default') { next; }
1.736     albertel 6273: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 6274: 			    my $unikey;
                   6275: 			    if ($pack =~ /_0$/) {
                   6276: 				$unikey='parameter_0_'.$name;
                   6277: 				$part=0;
                   6278: 			    } else {
                   6279: 				$unikey='parameter'.$keyroot.'_'.$name;
                   6280: 			    }
1.339     albertel 6281: 			    if ($subp eq 'display') {
                   6282: 				$value.=' [Part: '.$part.']';
                   6283: 			    }
1.599     albertel 6284: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 6285: 			    $metathesekeys{$unikey}=1;
1.599     albertel 6286: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6287: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 6288: 			    }
1.599     albertel 6289: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   6290: 				$metaentry{':'.$unikey}=
                   6291: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 6292: 			    }
1.339     albertel 6293: 			}
                   6294: 		    }
                   6295: 		} else {
1.172     www      6296: #
                   6297: # This is not a package - some other kind of start tag
1.339     albertel 6298: #
                   6299: 		    my $entry=$token->[1];
                   6300: 		    my $unikey;
                   6301: 		    if ($entry eq 'import') {
                   6302: 			$unikey='';
                   6303: 		    } else {
                   6304: 			$unikey=$entry;
                   6305: 		    }
                   6306: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6307: 
                   6308: 		    if (defined($token->[2]->{'id'})) { 
                   6309: 			$unikey.='_'.$token->[2]->{'id'}; 
                   6310: 		    }
1.175     www      6311: 
1.339     albertel 6312: 		    if ($entry eq 'import') {
1.175     www      6313: #
                   6314: # Importing a library here
1.339     albertel 6315: #
                   6316: 			if ($depthcount<20) {
                   6317: 			    my $location=$parser->get_text('/import');
                   6318: 			    my $dir=$filename;
                   6319: 			    $dir=~s|[^/]*$||;
                   6320: 			    $location=&filelocation($dir,$location);
1.736     albertel 6321: 			    my $metadata = 
                   6322: 				&metadata($uri,'keys', $location,$unikey,
                   6323: 					  $depthcount+1);
                   6324: 			    foreach my $meta (split(',',$metadata)) {
                   6325: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   6326: 				$metathesekeys{$meta}=1;
1.339     albertel 6327: 			    }
                   6328: 			}
                   6329: 		    } else { 
                   6330: 			
                   6331: 			if (defined($token->[2]->{'name'})) { 
                   6332: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   6333: 			}
                   6334: 			$metathesekeys{$unikey}=1;
1.736     albertel 6335: 			foreach my $param (@{$token->[3]}) {
                   6336: 			    $metaentry{':'.$unikey.'.'.$param} =
                   6337: 				$token->[2]->{$param};
1.339     albertel 6338: 			}
                   6339: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 6340: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 6341: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   6342: 		 # only ws inside the tag, and not in default, so use default
                   6343: 		 # as value
1.599     albertel 6344: 			    $metaentry{':'.$unikey}=$default;
1.339     albertel 6345: 			} else {
1.321     albertel 6346: 		  # either something interesting inside the tag or default
                   6347:                   # uninteresting
1.599     albertel 6348: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 6349: 			}
1.172     www      6350: # end of not-a-package not-a-library import
1.339     albertel 6351: 		    }
1.172     www      6352: # end of not-a-package start tag
1.339     albertel 6353: 		}
1.172     www      6354: # the next is the end of "start tag"
1.339     albertel 6355: 	    }
                   6356: 	}
1.483     albertel 6357: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.737     albertel 6358: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 6359: 	    #no specific packages #how's our extension
                   6360: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 6361: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 6362: 					 \%metathesekeys);
                   6363: 	}
1.599     albertel 6364: 	if (!exists($metaentry{':packages'})) {
1.737     albertel 6365: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 6366: 		#no specific packages well let's get default then
                   6367: 		if ($key!~/^default&/) { next; }
1.488     albertel 6368: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 6369: 					     \%metathesekeys);
                   6370: 	    }
                   6371: 	}
1.338     www      6372: # are there custom rights to evaluate
1.599     albertel 6373: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 6374: 
1.338     www      6375:     #
                   6376:     # Importing a rights file here
1.339     albertel 6377:     #
                   6378: 	    unless ($depthcount) {
1.599     albertel 6379: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 6380: 		my $dir=$filename;
                   6381: 		$dir=~s|[^/]*$||;
                   6382: 		$location=&filelocation($dir,$location);
1.736     albertel 6383: 		my $rights_metadata =
                   6384: 		    &metadata($uri,'keys',$location,'_rights',
                   6385: 			      $depthcount+1);
                   6386: 		foreach my $rights (split(',',$rights_metadata)) {
                   6387: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   6388: 		    $metathesekeys{$rights}=1;
1.339     albertel 6389: 		}
                   6390: 	    }
                   6391: 	}
1.737     albertel 6392: 	# uniqifiy package listing
                   6393: 	my %seen;
                   6394: 	my @uniq_packages =
                   6395: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   6396: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   6397: 
                   6398: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 6399: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   6400: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.699     albertel 6401: 	&do_cache_new('meta',$uri,\%metaentry,60*60);
1.177     www      6402: # this is the end of "was not already recently cached
1.71      www      6403:     }
1.599     albertel 6404:     return $metaentry{':'.$what};
1.261     albertel 6405: }
                   6406: 
1.488     albertel 6407: sub metadata_create_package_def {
1.483     albertel 6408:     my ($uri,$key,$package,$metathesekeys)=@_;
                   6409:     my ($pack,$name,$subp)=split(/\&/,$key);
                   6410:     if ($subp eq 'default') { next; }
                   6411:     
1.599     albertel 6412:     if (defined($metaentry{':packages'})) {
                   6413: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 6414:     } else {
1.599     albertel 6415: 	$metaentry{':packages'}=$package;
1.483     albertel 6416:     }
                   6417:     my $value=$packagetab{$key};
                   6418:     my $unikey;
                   6419:     $unikey='parameter_0_'.$name;
1.599     albertel 6420:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 6421:     $$metathesekeys{$unikey}=1;
1.599     albertel 6422:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6423: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 6424:     }
1.599     albertel 6425:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   6426: 	$metaentry{':'.$unikey}=
                   6427: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 6428:     }
                   6429: }
                   6430: 
1.261     albertel 6431: sub metadata_generate_part0 {
                   6432:     my ($metadata,$metacache,$uri) = @_;
                   6433:     my %allnames;
1.737     albertel 6434:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 6435: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 6436: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   6437: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 6438: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 6439: 	    $allnames{$name}=$part;
                   6440: 	  }
                   6441: 	}
                   6442:     }
                   6443:     foreach my $name (keys(%allnames)) {
                   6444:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 6445:       my $key=":parameter_0_$name";
1.261     albertel 6446:       $$metacache{"$key.part"}='0';
                   6447:       $$metacache{"$key.name"}=$name;
1.428     albertel 6448:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 6449: 					   $allnames{$name}.'_'.$name.
                   6450: 					   '.type'};
1.428     albertel 6451:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 6452: 			     '.display'};
1.644     www      6453:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 6454:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 6455:       $$metacache{"$key.display"}=$olddis;
                   6456:     }
1.71      www      6457: }
                   6458: 
1.764     albertel 6459: # ------------------------------------------------------ Devalidate title cache
                   6460: 
                   6461: sub devalidate_title_cache {
                   6462:     my ($url)=@_;
                   6463:     if (!$env{'request.course.id'}) { return; }
                   6464:     my $symb=&symbread($url);
                   6465:     if (!$symb) { return; }
                   6466:     my $key=$env{'request.course.id'}."\0".$symb;
                   6467:     &devalidate_cache_new('title',$key);
                   6468: }
                   6469: 
1.301     www      6470: # ------------------------------------------------- Get the title of a resource
                   6471: 
                   6472: sub gettitle {
                   6473:     my $urlsymb=shift;
                   6474:     my $symb=&symbread($urlsymb);
1.534     albertel 6475:     if ($symb) {
1.620     albertel 6476: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 6477: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 6478: 	if (defined($cached)) { 
                   6479: 	    return $result;
                   6480: 	}
1.534     albertel 6481: 	my ($map,$resid,$url)=&decode_symb($symb);
                   6482: 	my $title='';
                   6483: 	my %bighash;
1.620     albertel 6484: 	if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.534     albertel 6485: 		&GDBM_READER(),0640)) {
                   6486: 	    my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   6487: 	    $title=$bighash{'title_'.$mapid.'.'.$resid};
                   6488: 	    untie %bighash;
                   6489: 	}
                   6490: 	$title=~s/\&colon\;/\:/gs;
                   6491: 	if ($title) {
1.599     albertel 6492: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 6493: 	}
                   6494: 	$urlsymb=$url;
                   6495:     }
                   6496:     my $title=&metadata($urlsymb,'title');
                   6497:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   6498:     return $title;
1.301     www      6499: }
1.613     albertel 6500: 
1.614     albertel 6501: sub get_slot {
                   6502:     my ($which,$cnum,$cdom)=@_;
                   6503:     if (!$cnum || !$cdom) {
1.790     albertel 6504: 	(undef,my $courseid)=&whichuser();
1.620     albertel 6505: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   6506: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 6507:     }
1.703     albertel 6508:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   6509:     my %slotinfo;
                   6510:     if (exists($remembered{$key})) {
                   6511: 	$slotinfo{$which} = $remembered{$key};
                   6512:     } else {
                   6513: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   6514: 	&Apache::lonhomework::showhash(%slotinfo);
                   6515: 	my ($tmp)=keys(%slotinfo);
                   6516: 	if ($tmp=~/^error:/) { return (); }
                   6517: 	$remembered{$key} = $slotinfo{$which};
                   6518:     }
1.616     albertel 6519:     if (ref($slotinfo{$which}) eq 'HASH') {
                   6520: 	return %{$slotinfo{$which}};
                   6521:     }
                   6522:     return $slotinfo{$which};
1.614     albertel 6523: }
1.31      www      6524: # ------------------------------------------------- Update symbolic store links
                   6525: 
                   6526: sub symblist {
                   6527:     my ($mapname,%newhash)=@_;
1.438     www      6528:     $mapname=&deversion(&declutter($mapname));
1.31      www      6529:     my %hash;
1.620     albertel 6530:     if (($env{'request.course.fn'}) && (%newhash)) {
                   6531:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6532:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 6533: 	    foreach my $url (keys %newhash) {
                   6534: 		next if ($url eq 'last_known'
                   6535: 			 && $env{'form.no_update_last_known'});
                   6536: 		$hash{declutter($url)}=&encode_symb($mapname,
                   6537: 						    $newhash{$url}->[1],
                   6538: 						    $newhash{$url}->[0]);
1.191     harris41 6539:             }
1.31      www      6540:             if (untie(%hash)) {
                   6541: 		return 'ok';
                   6542:             }
                   6543:         }
                   6544:     }
                   6545:     return 'error';
1.212     www      6546: }
                   6547: 
                   6548: # --------------------------------------------------------------- Verify a symb
                   6549: 
                   6550: sub symbverify {
1.510     www      6551:     my ($symb,$thisurl)=@_;
                   6552:     my $thisfn=$thisurl;
1.439     www      6553:     $thisfn=&declutter($thisfn);
1.215     www      6554: # direct jump to resource in page or to a sequence - will construct own symbs
                   6555:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   6556: # check URL part
1.409     www      6557:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      6558: 
1.431     www      6559:     unless ($url eq $thisfn) { return 0; }
1.213     www      6560: 
1.216     www      6561:     $symb=&symbclean($symb);
1.510     www      6562:     $thisurl=&deversion($thisurl);
1.439     www      6563:     $thisfn=&deversion($thisfn);
1.213     www      6564: 
                   6565:     my %bighash;
                   6566:     my $okay=0;
1.431     www      6567: 
1.620     albertel 6568:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6569:                             &GDBM_READER(),0640)) {
1.510     www      6570:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      6571:         unless ($ids) { 
1.510     www      6572:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      6573:         }
                   6574:         if ($ids) {
                   6575: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 6576: 	    foreach my $id (split(/\,/,$ids)) {
                   6577: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      6578:                if (
                   6579:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   6580:    eq $symb) { 
1.620     albertel 6581: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 6582: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 6583: 		       $okay=1; 
                   6584: 		   }
                   6585: 	       }
1.216     www      6586: 	   }
                   6587:         }
1.213     www      6588: 	untie(%bighash);
                   6589:     }
                   6590:     return $okay;
1.31      www      6591: }
                   6592: 
1.210     www      6593: # --------------------------------------------------------------- Clean-up symb
                   6594: 
                   6595: sub symbclean {
                   6596:     my $symb=shift;
1.568     albertel 6597:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      6598: # remove version from map
                   6599:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      6600: 
1.210     www      6601: # remove version from URL
                   6602:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      6603: 
1.507     www      6604: # remove wrapper
                   6605: 
1.510     www      6606:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 6607:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      6608:     return $symb;
1.409     www      6609: }
                   6610: 
                   6611: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 6612: 
                   6613: sub encode_symb {
                   6614:     my ($map,$resid,$url)=@_;
                   6615:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   6616: }
1.409     www      6617: 
                   6618: sub decode_symb {
1.568     albertel 6619:     my $symb=shift;
                   6620:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   6621:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      6622:     return (&fixversion($map),$resid,&fixversion($url));
                   6623: }
                   6624: 
                   6625: sub fixversion {
                   6626:     my $fn=shift;
1.609     banghart 6627:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      6628:     my %bighash;
                   6629:     my $uri=&clutter($fn);
1.620     albertel 6630:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      6631: # is this cached?
1.599     albertel 6632:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      6633:     if (defined($cached)) { return $result; }
                   6634: # unfortunately not cached, or expired
1.620     albertel 6635:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      6636: 	    &GDBM_READER(),0640)) {
                   6637:  	if ($bighash{'version_'.$uri}) {
                   6638:  	    my $version=$bighash{'version_'.$uri};
1.444     www      6639:  	    unless (($version eq 'mostrecent') || 
                   6640: 		    ($version==&getversion($uri))) {
1.440     www      6641:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   6642:  	    }
                   6643:  	}
                   6644:  	untie %bighash;
1.413     www      6645:     }
1.599     albertel 6646:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      6647: }
                   6648: 
                   6649: sub deversion {
                   6650:     my $url=shift;
                   6651:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   6652:     return $url;
1.210     www      6653: }
                   6654: 
1.31      www      6655: # ------------------------------------------------------ Return symb list entry
                   6656: 
                   6657: sub symbread {
1.249     www      6658:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 6659:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 6660:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      6661: # no filename provided? try from environment
1.44      www      6662:     unless ($thisfn) {
1.620     albertel 6663:         if ($env{'request.symb'}) {
                   6664: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 6665: 	}
1.620     albertel 6666: 	$thisfn=$env{'request.filename'};
1.44      www      6667:     }
1.569     albertel 6668:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      6669: # is that filename actually a symb? Verify, clean, and return
                   6670:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 6671: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 6672: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 6673: 	}
1.242     www      6674:     }
1.44      www      6675:     $thisfn=declutter($thisfn);
1.31      www      6676:     my %hash;
1.37      www      6677:     my %bighash;
                   6678:     my $syval='';
1.620     albertel 6679:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  6680:         my $targetfn = $thisfn;
1.609     banghart 6681:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  6682:             $targetfn = 'adm/wrapper/'.$thisfn;
                   6683:         }
1.687     albertel 6684: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   6685: 	    $targetfn=$1;
                   6686: 	}
1.620     albertel 6687:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6688:                       &GDBM_READER(),0640)) {
1.481     raeburn  6689: 	    $syval=$hash{$targetfn};
1.37      www      6690:             untie(%hash);
                   6691:         }
                   6692: # ---------------------------------------------------------- There was an entry
                   6693:         if ($syval) {
1.601     albertel 6694: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 6695: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.601     albertel 6696: 		    #&appenv('request.ambiguous' => $thisfn);
1.620     albertel 6697: 		    #return $env{$cache_str}='';
1.601     albertel 6698: 		#}    
                   6699: 		#$syval.=$1;
                   6700: 	    #}
1.37      www      6701:         } else {
                   6702: # ------------------------------------------------------- Was not in symb table
1.620     albertel 6703:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6704:                             &GDBM_READER(),0640)) {
1.37      www      6705: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      6706:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      6707:               unless ($ids) { 
                   6708:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      6709:               }
                   6710:               unless ($ids) {
                   6711: # alias?
                   6712: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      6713:               }
1.37      www      6714:               if ($ids) {
                   6715: # ------------------------------------------------------------------- Has ID(s)
                   6716:                  my @possibilities=split(/\,/,$ids);
1.39      www      6717:                  if ($#possibilities==0) {
                   6718: # ----------------------------------------------- There is only one possibility
1.37      www      6719: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 6720: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6721: 						    $resid,$thisfn);
1.249     www      6722:                  } elsif (!$donotrecurse) {
1.39      www      6723: # ------------------------------------------ There is more than one possibility
                   6724:                      my $realpossible=0;
1.800     albertel 6725:                      foreach my $id (@possibilities) {
                   6726: 			 my $file=$bighash{'src_'.$id};
1.39      www      6727:                          if (&allowed('bre',$file)) {
1.800     albertel 6728:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      6729:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   6730: 				$realpossible++;
1.626     albertel 6731:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6732: 						    $resid,$thisfn);
1.39      www      6733:                             }
                   6734: 			 }
1.191     harris41 6735:                      }
1.39      www      6736: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      6737:                  } else {
                   6738:                      $syval='';
1.37      www      6739:                  }
                   6740: 	      }
                   6741:               untie(%bighash)
1.481     raeburn  6742:            }
1.31      www      6743:         }
1.62      www      6744:         if ($syval) {
1.620     albertel 6745: 	    return $env{$cache_str}=$syval;
1.62      www      6746:         }
1.31      www      6747:     }
1.44      www      6748:     &appenv('request.ambiguous' => $thisfn);
1.620     albertel 6749:     return $env{$cache_str}='';
1.31      www      6750: }
                   6751: 
                   6752: # ---------------------------------------------------------- Return random seed
                   6753: 
1.32      www      6754: sub numval {
                   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;
1.564     albertel 6763:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      6764:     return int($txt);
1.368     albertel 6765: }
                   6766: 
1.484     albertel 6767: sub numval2 {
                   6768:     my $txt=shift;
                   6769:     $txt=~tr/A-J/0-9/;
                   6770:     $txt=~tr/a-j/0-9/;
                   6771:     $txt=~tr/K-T/0-9/;
                   6772:     $txt=~tr/k-t/0-9/;
                   6773:     $txt=~tr/U-Z/0-5/;
                   6774:     $txt=~tr/u-z/0-5/;
                   6775:     $txt=~s/\D//g;
                   6776:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   6777:     my $total;
                   6778:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 6779:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 6780:     return int($total);
                   6781: }
                   6782: 
1.575     albertel 6783: sub numval3 {
                   6784:     use integer;
                   6785:     my $txt=shift;
                   6786:     $txt=~tr/A-J/0-9/;
                   6787:     $txt=~tr/a-j/0-9/;
                   6788:     $txt=~tr/K-T/0-9/;
                   6789:     $txt=~tr/k-t/0-9/;
                   6790:     $txt=~tr/U-Z/0-5/;
                   6791:     $txt=~tr/u-z/0-5/;
                   6792:     $txt=~s/\D//g;
                   6793:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   6794:     my $total;
                   6795:     foreach my $val (@txts) { $total+=$val; }
                   6796:     if ($_64bit) { $total=(($total<<32)>>32); }
                   6797:     return $total;
                   6798: }
                   6799: 
1.675     albertel 6800: sub digest {
                   6801:     my ($data)=@_;
                   6802:     my $digest=&Digest::MD5::md5($data);
                   6803:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   6804:     my ($e,$f);
                   6805:     {
                   6806:         use integer;
                   6807:         $e=($a+$b);
                   6808:         $f=($c+$d);
                   6809:         if ($_64bit) {
                   6810:             $e=(($e<<32)>>32);
                   6811:             $f=(($f<<32)>>32);
                   6812:         }
                   6813:     }
                   6814:     if (wantarray) {
                   6815: 	return ($e,$f);
                   6816:     } else {
                   6817: 	my $g;
                   6818: 	{
                   6819: 	    use integer;
                   6820: 	    $g=($e+$f);
                   6821: 	    if ($_64bit) {
                   6822: 		$g=(($g<<32)>>32);
                   6823: 	    }
                   6824: 	}
                   6825: 	return $g;
                   6826:     }
                   6827: }
                   6828: 
1.368     albertel 6829: sub latest_rnd_algorithm_id {
1.675     albertel 6830:     return '64bit5';
1.366     albertel 6831: }
1.32      www      6832: 
1.503     albertel 6833: sub get_rand_alg {
                   6834:     my ($courseid)=@_;
1.790     albertel 6835:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 6836:     if ($courseid) {
1.620     albertel 6837: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 6838:     }
                   6839:     return &latest_rnd_algorithm_id();
                   6840: }
                   6841: 
1.562     albertel 6842: sub validCODE {
                   6843:     my ($CODE)=@_;
                   6844:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   6845:     return 0;
                   6846: }
                   6847: 
1.491     albertel 6848: sub getCODE {
1.620     albertel 6849:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 6850:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   6851: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   6852: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 6853: 	return $Apache::lonhomework::history{'resource.CODE'};
                   6854:     }
                   6855:     return undef;
                   6856: }
                   6857: 
1.31      www      6858: sub rndseed {
1.155     albertel 6859:     my ($symb,$courseid,$domain,$username)=@_;
1.366     albertel 6860: 
1.790     albertel 6861:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.155     albertel 6862:     if (!$symb) {
1.366     albertel 6863: 	unless ($symb=$wsymb) { return time; }
                   6864:     }
                   6865:     if (!$courseid) { $courseid=$wcourseid; }
                   6866:     if (!$domain) { $domain=$wdomain; }
                   6867:     if (!$username) { $username=$wusername }
1.503     albertel 6868:     my $which=&get_rand_alg();
1.803     albertel 6869: 
1.491     albertel 6870:     if (defined(&getCODE())) {
1.675     albertel 6871: 	if ($which eq '64bit5') {
                   6872: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   6873: 	} elsif ($which eq '64bit4') {
1.575     albertel 6874: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   6875: 	} else {
                   6876: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   6877: 	}
1.675     albertel 6878:     } elsif ($which eq '64bit5') {
                   6879: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 6880:     } elsif ($which eq '64bit4') {
                   6881: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 6882:     } elsif ($which eq '64bit3') {
                   6883: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 6884:     } elsif ($which eq '64bit2') {
                   6885: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 6886:     } elsif ($which eq '64bit') {
                   6887: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   6888:     }
                   6889:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   6890: }
                   6891: 
                   6892: sub rndseed_32bit {
                   6893:     my ($symb,$courseid,$domain,$username)=@_;
                   6894:     {
                   6895: 	use integer;
                   6896: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   6897: 	my $symbseed=numval($symb) << 22;
                   6898: 	my $namechck=unpack("%32C*",$username) << 17;
                   6899: 	my $nameseed=numval($username) << 12;
                   6900: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   6901: 	my $courseseed=unpack("%32C*",$courseid);
                   6902: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 6903: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6904: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 6905: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 6906: 	return $num;
                   6907:     }
                   6908: }
                   6909: 
                   6910: sub rndseed_64bit {
                   6911:     my ($symb,$courseid,$domain,$username)=@_;
                   6912:     {
                   6913: 	use integer;
                   6914: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   6915: 	my $symbseed=numval($symb) << 10;
                   6916: 	my $namechck=unpack("%32S*",$username);
                   6917: 	
                   6918: 	my $nameseed=numval($username) << 21;
                   6919: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   6920: 	my $courseseed=unpack("%32S*",$courseid);
                   6921: 	
                   6922: 	my $num1=$symbchck+$symbseed+$namechck;
                   6923: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6924: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6925: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 6926: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 6927: 	return "$num1,$num2";
1.155     albertel 6928:     }
1.366     albertel 6929: }
                   6930: 
1.443     albertel 6931: sub rndseed_64bit2 {
                   6932:     my ($symb,$courseid,$domain,$username)=@_;
                   6933:     {
                   6934: 	use integer;
                   6935: 	# strings need to be an even # of cahracters long, it it is odd the
                   6936:         # last characters gets thrown away
                   6937: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6938: 	my $symbseed=numval($symb) << 10;
                   6939: 	my $namechck=unpack("%32S*",$username.' ');
                   6940: 	
                   6941: 	my $nameseed=numval($username) << 21;
1.501     albertel 6942: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6943: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6944: 	
                   6945: 	my $num1=$symbchck+$symbseed+$namechck;
                   6946: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6947: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6948: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 6949: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 6950: 	return "$num1,$num2";
                   6951:     }
                   6952: }
                   6953: 
                   6954: sub rndseed_64bit3 {
                   6955:     my ($symb,$courseid,$domain,$username)=@_;
                   6956:     {
                   6957: 	use integer;
                   6958: 	# strings need to be an even # of cahracters long, it it is odd the
                   6959:         # last characters gets thrown away
                   6960: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6961: 	my $symbseed=numval2($symb) << 10;
                   6962: 	my $namechck=unpack("%32S*",$username.' ');
                   6963: 	
                   6964: 	my $nameseed=numval2($username) << 21;
1.443     albertel 6965: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6966: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6967: 	
                   6968: 	my $num1=$symbchck+$symbseed+$namechck;
                   6969: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6970: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6971: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 6972: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6973: 	
1.503     albertel 6974: 	return "$num1:$num2";
1.443     albertel 6975:     }
                   6976: }
                   6977: 
1.575     albertel 6978: sub rndseed_64bit4 {
                   6979:     my ($symb,$courseid,$domain,$username)=@_;
                   6980:     {
                   6981: 	use integer;
                   6982: 	# strings need to be an even # of cahracters long, it it is odd the
                   6983:         # last characters gets thrown away
                   6984: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6985: 	my $symbseed=numval3($symb) << 10;
                   6986: 	my $namechck=unpack("%32S*",$username.' ');
                   6987: 	
                   6988: 	my $nameseed=numval3($username) << 21;
                   6989: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6990: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6991: 	
                   6992: 	my $num1=$symbchck+$symbseed+$namechck;
                   6993: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6994: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6995: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 6996: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6997: 	
                   6998: 	return "$num1:$num2";
                   6999:     }
                   7000: }
                   7001: 
1.675     albertel 7002: sub rndseed_64bit5 {
                   7003:     my ($symb,$courseid,$domain,$username)=@_;
                   7004:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   7005:     return "$num1:$num2";
                   7006: }
                   7007: 
1.366     albertel 7008: sub rndseed_CODE_64bit {
                   7009:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 7010:     {
1.366     albertel 7011: 	use integer;
1.443     albertel 7012: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 7013: 	my $symbseed=numval2($symb);
1.491     albertel 7014: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   7015: 	my $CODEseed=numval(&getCODE());
1.443     albertel 7016: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 7017: 	my $num1=$symbseed+$CODEchck;
                   7018: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 7019: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   7020: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 7021: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   7022: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 7023: 	return "$num1:$num2";
1.366     albertel 7024:     }
                   7025: }
                   7026: 
1.575     albertel 7027: sub rndseed_CODE_64bit4 {
                   7028:     my ($symb,$courseid,$domain,$username)=@_;
                   7029:     {
                   7030: 	use integer;
                   7031: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   7032: 	my $symbseed=numval3($symb);
                   7033: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   7034: 	my $CODEseed=numval3(&getCODE());
                   7035: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7036: 	my $num1=$symbseed+$CODEchck;
                   7037: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 7038: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   7039: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 7040: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   7041: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   7042: 	return "$num1:$num2";
                   7043:     }
                   7044: }
                   7045: 
1.675     albertel 7046: sub rndseed_CODE_64bit5 {
                   7047:     my ($symb,$courseid,$domain,$username)=@_;
                   7048:     my $code = &getCODE();
                   7049:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   7050:     return "$num1:$num2";
                   7051: }
                   7052: 
1.366     albertel 7053: sub setup_random_from_rndseed {
                   7054:     my ($rndseed)=@_;
1.503     albertel 7055:     if ($rndseed =~/([,:])/) {
                   7056: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 7057: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   7058:     } else {
                   7059: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 7060:     }
1.36      albertel 7061: }
                   7062: 
1.474     albertel 7063: sub latest_receipt_algorithm_id {
                   7064:     return 'receipt2';
                   7065: }
                   7066: 
1.480     www      7067: sub recunique {
                   7068:     my $fucourseid=shift;
                   7069:     my $unique;
1.620     albertel 7070:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   7071: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      7072:     } else {
                   7073: 	$unique=$perlvar{'lonReceipt'};
                   7074:     }
                   7075:     return unpack("%32C*",$unique);
                   7076: }
                   7077: 
                   7078: sub recprefix {
                   7079:     my $fucourseid=shift;
                   7080:     my $prefix;
1.620     albertel 7081:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   7082: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      7083:     } else {
                   7084: 	$prefix=$perlvar{'lonHostID'};
                   7085:     }
                   7086:     return unpack("%32C*",$prefix);
                   7087: }
                   7088: 
1.76      www      7089: sub ireceipt {
1.474     albertel 7090:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.76      www      7091:     my $cuname=unpack("%32C*",$funame);
                   7092:     my $cudom=unpack("%32C*",$fudom);
                   7093:     my $cucourseid=unpack("%32C*",$fucourseid);
                   7094:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      7095:     my $cunique=&recunique($fucourseid);
1.474     albertel 7096:     my $cpart=unpack("%32S*",$part);
1.480     www      7097:     my $return =&recprefix($fucourseid).'-';
1.620     albertel 7098:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   7099: 	$env{'request.state'} eq 'construct') {
1.790     albertel 7100: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 7101: 			       
                   7102: 	$return.= ($cunique%$cuname+
                   7103: 		   $cunique%$cudom+
                   7104: 		   $cusymb%$cuname+
                   7105: 		   $cusymb%$cudom+
                   7106: 		   $cucourseid%$cuname+
                   7107: 		   $cucourseid%$cudom+
                   7108: 		   $cpart%$cuname+
                   7109: 		   $cpart%$cudom);
                   7110:     } else {
                   7111: 	$return.= ($cunique%$cuname+
                   7112: 		   $cunique%$cudom+
                   7113: 		   $cusymb%$cuname+
                   7114: 		   $cusymb%$cudom+
                   7115: 		   $cucourseid%$cuname+
                   7116: 		   $cucourseid%$cudom);
                   7117:     }
                   7118:     return $return;
1.76      www      7119: }
                   7120: 
                   7121: sub receipt {
1.474     albertel 7122:     my ($part)=@_;
1.790     albertel 7123:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 7124:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      7125: }
1.260     ng       7126: 
1.790     albertel 7127: sub whichuser {
                   7128:     my ($passedsymb)=@_;
                   7129:     my ($symb,$courseid,$domain,$name,$publicuser);
                   7130:     if (defined($env{'form.grade_symb'})) {
                   7131: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   7132: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   7133: 	if (!$allowed &&
                   7134: 	    exists($env{'request.course.sec'}) &&
                   7135: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   7136: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   7137: 			      '/'.$env{'request.course.sec'});
                   7138: 	}
                   7139: 	if ($allowed) {
                   7140: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   7141: 	    $courseid=$tmp_courseid;
                   7142: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   7143: 	    ($name)=&get_env_multiple('form.grade_username');
                   7144: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   7145: 	}
                   7146:     }
                   7147:     if (!$passedsymb) {
                   7148: 	$symb=&symbread();
                   7149:     } else {
                   7150: 	$symb=$passedsymb;
                   7151:     }
                   7152:     $courseid=$env{'request.course.id'};
                   7153:     $domain=$env{'user.domain'};
                   7154:     $name=$env{'user.name'};
                   7155:     if ($name eq 'public' && $domain eq 'public') {
                   7156: 	if (!defined($env{'form.username'})) {
                   7157: 	    $env{'form.username'}.=time.rand(10000000);
                   7158: 	}
                   7159: 	$name.=$env{'form.username'};
                   7160:     }
                   7161:     return ($symb,$courseid,$domain,$name,$publicuser);
                   7162: 
                   7163: }
                   7164: 
1.36      albertel 7165: # ------------------------------------------------------------ Serves up a file
1.472     albertel 7166: # returns either the contents of the file or 
                   7167: # -1 if the file doesn't exist
1.481     raeburn  7168: #
                   7169: # if the target is a file that was uploaded via DOCS, 
                   7170: # a check will be made to see if a current copy exists on the local server,
                   7171: # if it does this will be served, otherwise a copy will be retrieved from
                   7172: # the home server for the course and stored in /home/httpd/html/userfiles on
                   7173: # the local server.   
1.472     albertel 7174: 
1.36      albertel 7175: sub getfile {
1.538     albertel 7176:     my ($file) = @_;
1.609     banghart 7177:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 7178:     &repcopy($file);
                   7179:     return &readfile($file);
                   7180: }
                   7181: 
                   7182: sub repcopy_userfile {
                   7183:     my ($file)=@_;
1.609     banghart 7184:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 7185:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 7186:     my ($cdom,$cnum,$filename) = 
1.811     albertel 7187: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 7188:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   7189:     if (-e "$file") {
1.828     www      7190: # we already have a local copy, check it out
1.538     albertel 7191: 	my @fileinfo = stat($file);
1.828     www      7192: 	my $rtncode;
                   7193: 	my $info;
1.538     albertel 7194: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 7195: 	if ($lwpresp ne 'ok') {
1.828     www      7196: # there is no such file anymore, even though we had a local copy
1.482     albertel 7197: 	    if ($rtncode eq '404') {
1.538     albertel 7198: 		unlink($file);
1.482     albertel 7199: 	    }
                   7200: 	    return -1;
                   7201: 	}
                   7202: 	if ($info < $fileinfo[9]) {
1.828     www      7203: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  7204: 	    return 'ok';
1.828     www      7205: 	} else {
                   7206: # the file is outdated, get rid of it
                   7207: 	    unlink($file);
1.482     albertel 7208: 	}
1.828     www      7209:     }
                   7210: # one way or the other, at this point, we don't have the file
                   7211: # construct the correct path for the file
                   7212:     my @parts = ($cdom,$cnum); 
                   7213:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   7214: 	push @parts, split(/\//,$1);
                   7215:     }
                   7216:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   7217:     foreach my $part (@parts) {
                   7218: 	$path .= '/'.$part;
                   7219: 	if (!-e $path) {
                   7220: 	    mkdir($path,0770);
1.482     albertel 7221: 	}
                   7222:     }
1.828     www      7223: # now the path exists for sure
                   7224: # get a user agent
                   7225:     my $ua=new LWP::UserAgent;
                   7226:     my $transferfile=$file.'.in.transfer';
                   7227: # FIXME: this should flock
                   7228:     if (-e $transferfile) { return 'ok'; }
                   7229:     my $request;
                   7230:     $uri=~s/^\///;
1.829     www      7231:     $request=new HTTP::Request('GET','http://'.$hostname{&homeserver($cnum,$cdom)}.'/raw/'.$uri);
1.828     www      7232:     my $response=$ua->request($request,$transferfile);
                   7233: # did it work?
                   7234:     if ($response->is_error()) {
                   7235: 	unlink($transferfile);
                   7236: 	&logthis("Userfile repcopy failed for $uri");
                   7237: 	return -1;
                   7238:     }
                   7239: # worked, rename the transfer file
                   7240:     rename($transferfile,$file);
1.607     raeburn  7241:     return 'ok';
1.481     raeburn  7242: }
                   7243: 
1.517     albertel 7244: sub tokenwrapper {
                   7245:     my $uri=shift;
1.552     albertel 7246:     $uri=~s|^http\://([^/]+)||;
                   7247:     $uri=~s|^/||;
1.620     albertel 7248:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 7249:     my $token=$1;
1.552     albertel 7250:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   7251:     if ($udom && $uname && $file) {
                   7252: 	$file=~s|(\?\.*)*$||;
1.620     albertel 7253:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
1.552     albertel 7254:         return 'http://'.$hostname{ &homeserver($uname,$udom)}.'/'.$uri.
1.517     albertel 7255:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   7256:                                '&tokenissued='.$perlvar{'lonHostID'};
                   7257:     } else {
                   7258:         return '/adm/notfound.html';
                   7259:     }
                   7260: }
                   7261: 
1.828     www      7262: # call with reqtype HEAD: get last modification time
                   7263: # call with reqtype GET: get the file contents
                   7264: # Do not call this with reqtype GET for large files! It loads everything into memory
                   7265: #
1.481     raeburn  7266: sub getuploaded {
                   7267:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   7268:     $uri=~s/^\///;
                   7269:     $uri = 'http://'.$hostname{ &homeserver($cnum,$cdom)}.'/raw/'.$uri;
                   7270:     my $ua=new LWP::UserAgent;
                   7271:     my $request=new HTTP::Request($reqtype,$uri);
                   7272:     my $response=$ua->request($request);
                   7273:     $$rtncode = $response->code;
1.482     albertel 7274:     if (! $response->is_success()) {
                   7275: 	return 'failed';
                   7276:     }      
                   7277:     if ($reqtype eq 'HEAD') {
1.486     www      7278: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 7279:     } elsif ($reqtype eq 'GET') {
                   7280: 	$$info = $response->content;
1.472     albertel 7281:     }
1.482     albertel 7282:     return 'ok';
1.36      albertel 7283: }
                   7284: 
1.481     raeburn  7285: sub readfile {
                   7286:     my $file = shift;
                   7287:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   7288:     my $fh;
                   7289:     open($fh,"<$file");
                   7290:     my $a='';
1.800     albertel 7291:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  7292:     return $a;
                   7293: }
                   7294: 
1.36      albertel 7295: sub filelocation {
1.590     banghart 7296:     my ($dir,$file) = @_;
                   7297:     my $location;
                   7298:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 7299: 
                   7300:     if ($file =~ m-^/adm/-) {
                   7301: 	$file=~s-^/adm/wrapper/-/-;
                   7302: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   7303:     }
1.590     banghart 7304:     if ($file=~m:^/~:) { # is a contruction space reference
                   7305:         $location = $file;
                   7306:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 7307:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 7308: 	# is a correct contruction space reference
                   7309:         $location = $file;
1.609     banghart 7310:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 7311:         my ($udom,$uname,$filename)=
1.811     albertel 7312:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 7313:         my $home=&homeserver($uname,$udom);
                   7314:         my $is_me=0;
                   7315:         my @ids=&current_machine_ids();
                   7316:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   7317:         if ($is_me) {
1.740     www      7318:   	    $location=&propath($udom,$uname).
1.590     banghart 7319:   	      '/userfiles/'.$filename;
                   7320:         } else {
                   7321:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   7322:   	      $udom.'/'.$uname.'/'.$filename;
                   7323:         }
                   7324:     } else {
                   7325:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   7326:         $file=~s:^/res/:/:;
                   7327:         if ( !( $file =~ m:^/:) ) {
                   7328:             $location = $dir. '/'.$file;
                   7329:         } else {
                   7330:             $location = '/home/httpd/html/res'.$file;
                   7331:         }
1.59      albertel 7332:     }
1.590     banghart 7333:     $location=~s://+:/:g; # remove duplicate /
                   7334:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
                   7335:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   7336:     return $location;
1.46      www      7337: }
1.36      albertel 7338: 
1.46      www      7339: sub hreflocation {
                   7340:     my ($dir,$file)=@_;
1.460     albertel 7341:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666     albertel 7342: 	$file=filelocation($dir,$file);
1.700     albertel 7343:     } elsif ($file=~m-^/adm/-) {
                   7344: 	$file=~s-^/adm/wrapper/-/-;
                   7345: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 7346:     }
                   7347:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   7348: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 7349:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   7350: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 7351:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 7352: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 7353: 	    -/uploaded/$1/$2/-x;
1.46      www      7354:     }
1.462     albertel 7355:     return $file;
1.465     albertel 7356: }
                   7357: 
                   7358: sub current_machine_domains {
                   7359:     my $hostname=$hostname{$perlvar{'lonHostID'}};
                   7360:     my @domains;
                   7361:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  7362: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 7363: 	if ($hostname eq $name) {
                   7364: 	    push(@domains,$hostdom{$id});
                   7365: 	}
                   7366:     }
                   7367:     return @domains;
                   7368: }
                   7369: 
                   7370: sub current_machine_ids {
                   7371:     my $hostname=$hostname{$perlvar{'lonHostID'}};
                   7372:     my @ids;
                   7373:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  7374: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 7375: 	if ($hostname eq $name) {
                   7376: 	    push(@ids,$id);
                   7377: 	}
                   7378:     }
                   7379:     return @ids;
1.31      www      7380: }
                   7381: 
1.824     raeburn  7382: sub additional_machine_domains {
                   7383:     my @domains;
                   7384:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   7385:     while( my $line = <$fh>) {
                   7386:         $line =~ s/\s//g;
                   7387:         push(@domains,$line);
                   7388:     }
                   7389:     return @domains;
                   7390: }
                   7391: 
                   7392: sub default_login_domain {
                   7393:     my $domain = $perlvar{'lonDefDomain'};
                   7394:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   7395:     foreach my $posdom (&current_machine_domains(),
                   7396:                         &additional_machine_domains()) {
                   7397:         if (lc($posdom) eq lc($testdomain)) {
                   7398:             $domain=$posdom;
                   7399:             last;
                   7400:         }
                   7401:     }
                   7402:     return $domain;
                   7403: }
                   7404: 
1.31      www      7405: # ------------------------------------------------------------- Declutters URLs
                   7406: 
                   7407: sub declutter {
                   7408:     my $thisfn=shift;
1.569     albertel 7409:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 7410:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      7411:     $thisfn=~s/^\///;
1.697     albertel 7412:     $thisfn=~s|^adm/wrapper/||;
                   7413:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      7414:     $thisfn=~s/^res\///;
1.235     www      7415:     $thisfn=~s/\?.+$//;
1.268     www      7416:     return $thisfn;
                   7417: }
                   7418: 
                   7419: # ------------------------------------------------------------- Clutter up URLs
                   7420: 
                   7421: sub clutter {
                   7422:     my $thisfn='/'.&declutter(shift);
1.609     banghart 7423:     unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) { 
1.270     www      7424:        $thisfn='/res'.$thisfn; 
                   7425:     }
1.694     albertel 7426:     if ($thisfn !~m|/adm|) {
1.695     albertel 7427: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 7428: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 7429: 	} else {
                   7430: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   7431: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 7432: 	    if ($embstyle eq 'ssi'
                   7433: 		|| ($embstyle eq 'hdn')
                   7434: 		|| ($embstyle eq 'rat')
                   7435: 		|| ($embstyle eq 'prv')
                   7436: 		|| ($embstyle eq 'ign')) {
                   7437: 		#do nothing with these
                   7438: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 7439: 		|| ($embstyle eq 'emb')
                   7440: 		|| ($embstyle eq 'wrp')) {
                   7441: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 7442: 	    } elsif ($embstyle eq 'unk'
                   7443: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 7444: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 7445: 	    } else {
1.718     www      7446: #		&logthis("Got a blank emb style");
1.695     albertel 7447: 	    }
1.694     albertel 7448: 	}
                   7449:     }
1.31      www      7450:     return $thisfn;
1.12      www      7451: }
                   7452: 
1.787     albertel 7453: sub clutter_with_no_wrapper {
                   7454:     my $uri = &clutter(shift);
                   7455:     if ($uri =~ m-^/adm/-) {
                   7456: 	$uri =~ s-^/adm/wrapper/-/-;
                   7457: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   7458:     }
                   7459:     return $uri;
                   7460: }
                   7461: 
1.557     albertel 7462: sub freeze_escape {
                   7463:     my ($value)=@_;
                   7464:     if (ref($value)) {
                   7465: 	$value=&nfreeze($value);
                   7466: 	return '__FROZEN__'.&escape($value);
                   7467:     }
                   7468:     return &escape($value);
                   7469: }
                   7470: 
1.11      www      7471: 
1.557     albertel 7472: sub thaw_unescape {
                   7473:     my ($value)=@_;
                   7474:     if ($value =~ /^__FROZEN__/) {
                   7475: 	substr($value,0,10,undef);
                   7476: 	$value=&unescape($value);
                   7477: 	return &thaw($value);
                   7478:     }
                   7479:     return &unescape($value);
                   7480: }
                   7481: 
1.436     albertel 7482: sub correct_line_ends {
                   7483:     my ($result)=@_;
                   7484:     $$result =~s/\r\n/\n/mg;
                   7485:     $$result =~s/\r/\n/mg;
1.415     albertel 7486: }
1.1       albertel 7487: # ================================================================ Main Program
                   7488: 
1.184     www      7489: sub goodbye {
1.204     albertel 7490:    &logthis("Starting Shut down");
1.443     albertel 7491: #not converted to using infrastruture and probably shouldn't be
1.599     albertel 7492:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&freeze(\%badServerCache))));
1.443     albertel 7493: #converted
1.599     albertel 7494: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
                   7495:    &logthis(sprintf("%-20s is %s",'%homecache',length(&freeze(\%homecache))));
                   7496: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&freeze(\%titlecache))));
                   7497: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&freeze(\%courseresdatacache))));
1.425     albertel 7498: #1.1 only
1.599     albertel 7499: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&freeze(\%userresdatacache))));
                   7500: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&freeze(\%getsectioncache))));
                   7501: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&freeze(\%courseresversioncache))));
                   7502: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&freeze(\%resversioncache))));
                   7503:    &logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
                   7504:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   7505:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      7506:    &flushcourselogs();
                   7507:    &logthis("Shutting down");
                   7508: }
                   7509: 
1.179     www      7510: BEGIN {
1.228     harris41 7511: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
1.195     www      7512:     unless ($readit) {
1.217     harris41 7513: {
1.781     raeburn  7514:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   7515:     %perlvar = (%perlvar,%{$configvars});
1.227     harris41 7516: }
1.1       albertel 7517: 
1.327     albertel 7518: # ------------------------------------------------------------ Read domain file
                   7519: {
                   7520:     %domaindescription = ();
                   7521:     %domain_auth_def = ();
                   7522:     %domain_auth_arg_def = ();
1.448     albertel 7523:     my $fh;
                   7524:     if (open($fh,"<".$Apache::lonnet::perlvar{'lonTabDir'}.'/domain.tab')) {
1.800     albertel 7525: 	while (my $line = <$fh>) {
                   7526:            next if ($line =~ /^(\#|\s*$)/);
1.390     matthew  7527: #           next if /^\#/;
1.801     foxr     7528:            chomp $line;
1.403     www      7529:            my ($domain, $domain_description, $def_auth, $def_auth_arg,
1.800     albertel 7530: 	       $def_lang, $city, $longi, $lati, $primary) = split(/:/,$line,9);
1.403     www      7531: 	   $domain_auth_def{$domain}=$def_auth;
1.327     albertel 7532:            $domain_auth_arg_def{$domain}=$def_auth_arg;
1.403     www      7533: 	   $domaindescription{$domain}=$domain_description;
                   7534: 	   $domain_lang_def{$domain}=$def_lang;
                   7535: 	   $domain_city{$domain}=$city;
                   7536: 	   $domain_longi{$domain}=$longi;
                   7537: 	   $domain_lati{$domain}=$lati;
1.685     raeburn  7538:            $domain_primary{$domain}=$primary;
1.403     www      7539: 
1.448     albertel 7540:  #         &logthis("Domain.tab: $domain, $domain_auth_def{$domain}, $domain_auth_arg_def{$domain},$domaindescription{$domain}");
1.327     albertel 7541: #          &logthis("Domain.tab: $domain ".$domaindescription{$domain} );
1.448     albertel 7542: 	}
1.327     albertel 7543:     }
1.448     albertel 7544:     close ($fh);
1.327     albertel 7545: }
                   7546: 
                   7547: 
1.1       albertel 7548: # ------------------------------------------------------------- Read hosts file
                   7549: {
1.448     albertel 7550:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
1.1       albertel 7551: 
                   7552:     while (my $configline=<$config>) {
1.303     matthew  7553:        next if ($configline =~ /^(\#|\s*$)/);
1.154     www      7554:        chomp($configline);
1.595     albertel 7555:        my ($id,$domain,$role,$name)=split(/:/,$configline);
1.597     albertel 7556:        $name=~s/\s//g;
1.595     albertel 7557:        if ($id && $domain && $role && $name) {
1.252     albertel 7558: 	 $hostname{$id}=$name;
                   7559: 	 $hostdom{$id}=$domain;
                   7560: 	 if ($role eq 'library') { $libserv{$id}=$name; }
1.245     www      7561:        }
1.1       albertel 7562:     }
1.448     albertel 7563:     close($config);
1.619     albertel 7564:     # FIXME: dev server don't want this, production servers _do_ want this
1.654     albertel 7565:     #&get_iphost();
1.1       albertel 7566: }
                   7567: 
1.598     albertel 7568: sub get_iphost {
                   7569:     if (%iphost) { return %iphost; }
1.653     albertel 7570:     my %name_to_ip;
1.598     albertel 7571:     foreach my $id (keys(%hostname)) {
                   7572: 	my $name=$hostname{$id};
1.653     albertel 7573: 	my $ip;
                   7574: 	if (!exists($name_to_ip{$name})) {
                   7575: 	    $ip = gethostbyname($name);
                   7576: 	    if (!$ip || length($ip) ne 4) {
1.826     www      7577: 		&logthis("Skipping host $id name $name no IP found");
1.653     albertel 7578: 		next;
                   7579: 	    }
                   7580: 	    $ip=inet_ntoa($ip);
                   7581: 	    $name_to_ip{$name} = $ip;
                   7582: 	} else {
                   7583: 	    $ip = $name_to_ip{$name};
1.598     albertel 7584: 	}
                   7585: 	push(@{$iphost{$ip}},$id);
                   7586:     }
                   7587:     return %iphost;
                   7588: }
                   7589: 
1.1       albertel 7590: # ------------------------------------------------------ Read spare server file
                   7591: {
1.448     albertel 7592:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 7593: 
                   7594:     while (my $configline=<$config>) {
                   7595:        chomp($configline);
1.284     matthew  7596:        if ($configline) {
1.784     albertel 7597: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 7598: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 7599: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 7600:        }
                   7601:     }
1.448     albertel 7602:     close($config);
1.1       albertel 7603: }
1.11      www      7604: # ------------------------------------------------------------ Read permissions
                   7605: {
1.448     albertel 7606:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      7607: 
                   7608:     while (my $configline=<$config>) {
1.448     albertel 7609: 	chomp($configline);
                   7610: 	if ($configline) {
                   7611: 	    my ($role,$perm)=split(/ /,$configline);
                   7612: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   7613: 	}
1.11      www      7614:     }
1.448     albertel 7615:     close($config);
1.11      www      7616: }
                   7617: 
                   7618: # -------------------------------------------- Read plain texts for permissions
                   7619: {
1.448     albertel 7620:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      7621: 
                   7622:     while (my $configline=<$config>) {
1.448     albertel 7623: 	chomp($configline);
                   7624: 	if ($configline) {
1.742     raeburn  7625: 	    my ($short,@plain)=split(/:/,$configline);
                   7626:             %{$prp{$short}} = ();
                   7627: 	    if (@plain > 0) {
                   7628:                 $prp{$short}{'std'} = $plain[0];
                   7629:                 for (my $i=1; $i<@plain; $i++) {
                   7630:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   7631:                 }
                   7632:             }
1.448     albertel 7633: 	}
1.135     www      7634:     }
1.448     albertel 7635:     close($config);
1.135     www      7636: }
                   7637: 
                   7638: # ---------------------------------------------------------- Read package table
                   7639: {
1.448     albertel 7640:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      7641: 
                   7642:     while (my $configline=<$config>) {
1.483     albertel 7643: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 7644: 	chomp($configline);
                   7645: 	my ($short,$plain)=split(/:/,$configline);
                   7646: 	my ($pack,$name)=split(/\&/,$short);
                   7647: 	if ($plain ne '') {
                   7648: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   7649: 	    $packagetab{$short}=$plain; 
                   7650: 	}
1.11      www      7651:     }
1.448     albertel 7652:     close($config);
1.329     matthew  7653: }
                   7654: 
                   7655: # ------------- set up temporary directory
                   7656: {
                   7657:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   7658: 
1.11      www      7659: }
                   7660: 
1.794     albertel 7661: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   7662: 				'compress_threshold'=> 20_000,
                   7663:  			        });
1.185     www      7664: 
1.281     www      7665: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      7666: $dumpcount=0;
1.22      www      7667: 
1.163     harris41 7668: &logtouch();
1.672     albertel 7669: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      7670: $readit=1;
1.564     albertel 7671:     {
                   7672: 	use integer;
                   7673: 	my $test=(2**32)+1;
1.568     albertel 7674: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 7675: 	&logthis(" Detected 64bit platform ($_64bit)");
                   7676:     }
1.195     www      7677: }
1.1       albertel 7678: }
1.179     www      7679: 
1.1       albertel 7680: 1;
1.191     harris41 7681: __END__
                   7682: 
1.243     albertel 7683: =pod
                   7684: 
1.191     harris41 7685: =head1 NAME
                   7686: 
1.243     albertel 7687: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 7688: 
                   7689: =head1 SYNOPSIS
                   7690: 
1.243     albertel 7691: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 7692: 
                   7693:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   7694: 
1.243     albertel 7695: Common parameters:
                   7696: 
                   7697: =over 4
                   7698: 
                   7699: =item *
                   7700: 
                   7701: $uname : an internal username (if $cname expecting a course Id specifically)
                   7702: 
                   7703: =item *
                   7704: 
                   7705: $udom : a domain (if $cdom expecting a course's domain specifically)
                   7706: 
                   7707: =item *
                   7708: 
                   7709: $symb : a resource instance identifier
                   7710: 
                   7711: =item *
                   7712: 
                   7713: $namespace : the name of a .db file that contains the data needed or
                   7714: being set.
                   7715: 
                   7716: =back
                   7717: 
1.394     bowersj2 7718: =head1 OVERVIEW
1.191     harris41 7719: 
1.394     bowersj2 7720: lonnet provides subroutines which interact with the
                   7721: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   7722: about classes, users, and resources.
1.243     albertel 7723: 
                   7724: For many of these objects you can also use this to store data about
                   7725: them or modify them in various ways.
1.191     harris41 7726: 
1.394     bowersj2 7727: =head2 Symbs
1.191     harris41 7728: 
1.394     bowersj2 7729: To identify a specific instance of a resource, LON-CAPA uses symbols
                   7730: or "symbs"X<symb>. These identifiers are built from the URL of the
                   7731: map, the resource number of the resource in the map, and the URL of
                   7732: the resource itself. The latter is somewhat redundant, but might help
                   7733: if maps change.
                   7734: 
                   7735: An example is
                   7736: 
                   7737:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   7738: 
                   7739: The respective map entry is
                   7740: 
                   7741:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   7742:   title="Problem 2">
                   7743:  </resource>
                   7744: 
                   7745: Symbs are used by the random number generator, as well as to store and
                   7746: restore data specific to a certain instance of for example a problem.
                   7747: 
                   7748: =head2 Storing And Retrieving Data
                   7749: 
                   7750: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   7751: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   7752: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   7753: is is the non-critical message twin of cstore. These functions are for
                   7754: handlers to store a perl hash to a user's permanent data space in an
                   7755: easy manner, and to retrieve it again on another call. It is expected
                   7756: that a handler would use this once at the beginning to retrieve data,
                   7757: and then again once at the end to send only the new data back.
                   7758: 
                   7759: The data is stored in the user's data directory on the user's
                   7760: homeserver under the ID of the course.
                   7761: 
                   7762: The hash that is returned by restore will have all of the previous
                   7763: value for all of the elements of the hash.
                   7764: 
                   7765: Example:
                   7766: 
                   7767:  #creating a hash
                   7768:  my %hash;
                   7769:  $hash{'foo'}='bar';
                   7770: 
                   7771:  #storing it
                   7772:  &Apache::lonnet::cstore(\%hash);
                   7773: 
                   7774:  #changing a value
                   7775:  $hash{'foo'}='notbar';
                   7776: 
                   7777:  #adding a new value
                   7778:  $hash{'bar'}='foo';
                   7779:  &Apache::lonnet::cstore(\%hash);
                   7780: 
                   7781:  #retrieving the hash
                   7782:  my %history=&Apache::lonnet::restore();
                   7783: 
                   7784:  #print the hash
                   7785:  foreach my $key (sort(keys(%history))) {
                   7786:    print("\%history{$key} = $history{$key}");
                   7787:  }
                   7788: 
                   7789: Will print out:
1.191     harris41 7790: 
1.394     bowersj2 7791:  %history{1:foo} = bar
                   7792:  %history{1:keys} = foo:timestamp
                   7793:  %history{1:timestamp} = 990455579
                   7794:  %history{2:bar} = foo
                   7795:  %history{2:foo} = notbar
                   7796:  %history{2:keys} = foo:bar:timestamp
                   7797:  %history{2:timestamp} = 990455580
                   7798:  %history{bar} = foo
                   7799:  %history{foo} = notbar
                   7800:  %history{timestamp} = 990455580
                   7801:  %history{version} = 2
                   7802: 
                   7803: Note that the special hash entries C<keys>, C<version> and
                   7804: C<timestamp> were added to the hash. C<version> will be equal to the
                   7805: total number of versions of the data that have been stored. The
                   7806: C<timestamp> attribute will be the UNIX time the hash was
                   7807: stored. C<keys> is available in every historical section to list which
                   7808: keys were added or changed at a specific historical revision of a
                   7809: hash.
                   7810: 
                   7811: B<Warning>: do not store the hash that restore returns directly. This
                   7812: will cause a mess since it will restore the historical keys as if the
                   7813: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 7814: 
1.394     bowersj2 7815: Calling convention:
1.191     harris41 7816: 
1.394     bowersj2 7817:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   7818:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 7819: 
1.394     bowersj2 7820: For more detailed information, see lonnet specific documentation.
1.191     harris41 7821: 
1.394     bowersj2 7822: =head1 RETURN MESSAGES
1.191     harris41 7823: 
1.394     bowersj2 7824: =over 4
1.191     harris41 7825: 
1.394     bowersj2 7826: =item * B<con_lost>: unable to contact remote host
1.191     harris41 7827: 
1.394     bowersj2 7828: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   7829: when the connection is brought back up
1.191     harris41 7830: 
1.394     bowersj2 7831: =item * B<con_failed>: unable to contact remote host and unable to save message
                   7832: for later delivery
1.191     harris41 7833: 
1.394     bowersj2 7834: =item * B<error:>: an error a occured, a description of the error follows the :
1.191     harris41 7835: 
1.394     bowersj2 7836: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 7837: that was requested
1.191     harris41 7838: 
1.243     albertel 7839: =back
1.191     harris41 7840: 
1.243     albertel 7841: =head1 PUBLIC SUBROUTINES
1.191     harris41 7842: 
1.243     albertel 7843: =head2 Session Environment Functions
1.191     harris41 7844: 
1.243     albertel 7845: =over 4
1.191     harris41 7846: 
1.394     bowersj2 7847: =item * 
                   7848: X<appenv()>
                   7849: B<appenv(%hash)>: the value of %hash is written to
                   7850: the user envirnoment file, and will be restored for each access this
1.620     albertel 7851: user makes during this session, also modifies the %env for the current
1.394     bowersj2 7852: process
1.191     harris41 7853: 
                   7854: =item *
1.394     bowersj2 7855: X<delenv()>
                   7856: B<delenv($regexp)>: removes all items from the session
                   7857: environment file that matches the regular expression in $regexp. The
1.620     albertel 7858: values are also delted from the current processes %env.
1.191     harris41 7859: 
1.795     albertel 7860: =item * get_env_multiple($name) 
                   7861: 
                   7862: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   7863: values may be defined and end up as an array ref.
                   7864: 
                   7865: returns an array of values
                   7866: 
1.243     albertel 7867: =back
                   7868: 
                   7869: =head2 User Information
1.191     harris41 7870: 
1.243     albertel 7871: =over 4
1.191     harris41 7872: 
                   7873: =item *
1.394     bowersj2 7874: X<queryauthenticate()>
                   7875: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 7876: authentication scheme
                   7877: 
                   7878: =item *
1.394     bowersj2 7879: X<authenticate()>
                   7880: B<authenticate($uname,$upass,$udom)>: try to
                   7881: authenticate user from domain's lib servers (first use the current
                   7882: one). C<$upass> should be the users password.
1.191     harris41 7883: 
                   7884: =item *
1.394     bowersj2 7885: X<homeserver()>
                   7886: B<homeserver($uname,$udom)>: find the server which has
                   7887: the user's directory and files (there must be only one), this caches
                   7888: the answer, and also caches if there is a borken connection.
1.191     harris41 7889: 
                   7890: =item *
1.394     bowersj2 7891: X<idget()>
                   7892: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   7893: (IDs are a unique resource in a domain, there must be only 1 ID per
                   7894: username, and only 1 username per ID in a specific domain) (returns
                   7895: hash: id=>name,id=>name)
1.191     harris41 7896: 
                   7897: =item *
1.394     bowersj2 7898: X<idrget()>
                   7899: B<idrget($udom,@unames)>: find the IDs behind a list of
                   7900: usernames (returns hash: name=>id,name=>id)
1.191     harris41 7901: 
                   7902: =item *
1.394     bowersj2 7903: X<idput()>
                   7904: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 7905: 
                   7906: =item *
1.394     bowersj2 7907: X<rolesinit()>
                   7908: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 7909: 
                   7910: =item *
1.551     albertel 7911: X<getsection()>
                   7912: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 7913: course $cname, return section name/number or '' for "not in course"
                   7914: and '-1' for "no section"
                   7915: 
                   7916: =item *
1.394     bowersj2 7917: X<userenvironment()>
                   7918: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 7919: passed in @what from the requested user's environment, returns a hash
                   7920: 
                   7921: =back
                   7922: 
                   7923: =head2 User Roles
                   7924: 
                   7925: =over 4
                   7926: 
                   7927: =item *
                   7928: 
1.810     raeburn  7929: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 7930:  F: full access
                   7931:  U,I,K: authentication modes (cxx only)
                   7932:  '': forbidden
                   7933:  1: user needs to choose course
                   7934:  2: browse allowed
1.766     albertel 7935:  A: passphrase authentication needed
1.243     albertel 7936: 
                   7937: =item *
                   7938: 
                   7939: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   7940: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   7941: and course level
                   7942: 
                   7943: =item *
                   7944: 
                   7945: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   7946: explanation of a user role term
                   7947: 
                   7948: =back
                   7949: 
                   7950: =head2 User Modification
                   7951: 
                   7952: =over 4
                   7953: 
                   7954: =item *
                   7955: 
                   7956: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
                   7957: user for the level given by URL.  Optional start and end dates (leave empty
                   7958: string or zero for "no date")
1.191     harris41 7959: 
                   7960: =item *
                   7961: 
1.243     albertel 7962: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   7963: change a users, password, possible return values are: ok,
                   7964: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   7965: refused
1.191     harris41 7966: 
                   7967: =item *
                   7968: 
1.243     albertel 7969: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 7970: 
                   7971: =item *
                   7972: 
1.243     albertel 7973: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
                   7974: modify user
1.191     harris41 7975: 
                   7976: =item *
                   7977: 
1.286     matthew  7978: modifystudent
                   7979: 
                   7980: modify a students enrollment and identification information.
                   7981: The course id is resolved based on the current users environment.  
                   7982: This means the envoking user must be a course coordinator or otherwise
                   7983: associated with a course.
                   7984: 
1.297     matthew  7985: This call is essentially a wrapper for lonnet::modifyuser and
                   7986: lonnet::modify_student_enrollment
1.286     matthew  7987: 
                   7988: Inputs: 
                   7989: 
                   7990: =over 4
                   7991: 
                   7992: =item B<$udom> Students loncapa domain
                   7993: 
                   7994: =item B<$uname> Students loncapa login name
                   7995: 
                   7996: =item B<$uid> Students id/student number
                   7997: 
                   7998: =item B<$umode> Students authentication mode
                   7999: 
                   8000: =item B<$upass> Students password
                   8001: 
                   8002: =item B<$first> Students first name
                   8003: 
                   8004: =item B<$middle> Students middle name
                   8005: 
                   8006: =item B<$last> Students last name
                   8007: 
                   8008: =item B<$gene> Students generation
                   8009: 
                   8010: =item B<$usec> Students section in course
                   8011: 
                   8012: =item B<$end> Unix time of the roles expiration
                   8013: 
                   8014: =item B<$start> Unix time of the roles start date
                   8015: 
                   8016: =item B<$forceid> If defined, allow $uid to be changed
                   8017: 
                   8018: =item B<$desiredhome> server to use as home server for student
                   8019: 
                   8020: =back
1.297     matthew  8021: 
                   8022: =item *
                   8023: 
                   8024: modify_student_enrollment
                   8025: 
                   8026: Change a students enrollment status in a class.  The environment variable
                   8027: 'role.request.course' must be defined for this function to proceed.
                   8028: 
                   8029: Inputs:
                   8030: 
                   8031: =over 4
                   8032: 
                   8033: =item $udom, students domain
                   8034: 
                   8035: =item $uname, students name
                   8036: 
                   8037: =item $uid, students user id
                   8038: 
                   8039: =item $first, students first name
                   8040: 
                   8041: =item $middle
                   8042: 
                   8043: =item $last
                   8044: 
                   8045: =item $gene
                   8046: 
                   8047: =item $usec
                   8048: 
                   8049: =item $end
                   8050: 
                   8051: =item $start
                   8052: 
                   8053: =back
                   8054: 
1.191     harris41 8055: 
                   8056: =item *
                   8057: 
1.243     albertel 8058: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   8059: custom role; give a custom role to a user for the level given by URL.  Specify
                   8060: name and domain of role author, and role name
1.191     harris41 8061: 
                   8062: =item *
                   8063: 
1.243     albertel 8064: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 8065: 
                   8066: =item *
                   8067: 
1.243     albertel 8068: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   8069: 
                   8070: =back
                   8071: 
                   8072: =head2 Course Infomation
                   8073: 
                   8074: =over 4
1.191     harris41 8075: 
                   8076: =item *
                   8077: 
1.631     albertel 8078: coursedescription($courseid) : returns a hash of information about the
                   8079: specified course id, including all environment settings for the
                   8080: course, the description of the course will be in the hash under the
                   8081: key 'description'
1.191     harris41 8082: 
                   8083: =item *
                   8084: 
1.624     albertel 8085: resdata($name,$domain,$type,@which) : request for current parameter
                   8086: setting for a specific $type, where $type is either 'course' or 'user',
                   8087: @what should be a list of parameters to ask about. This routine caches
                   8088: answers for 5 minutes.
1.243     albertel 8089: 
                   8090: =back
                   8091: 
                   8092: =head2 Course Modification
                   8093: 
                   8094: =over 4
1.191     harris41 8095: 
                   8096: =item *
                   8097: 
1.243     albertel 8098: writecoursepref($courseid,%prefs) : write preferences (environment
                   8099: database) for a course
1.191     harris41 8100: 
                   8101: =item *
                   8102: 
1.243     albertel 8103: createcourse($udom,$description,$url) : make/modify course
                   8104: 
                   8105: =back
                   8106: 
                   8107: =head2 Resource Subroutines
                   8108: 
                   8109: =over 4
1.191     harris41 8110: 
                   8111: =item *
                   8112: 
1.243     albertel 8113: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 8114: 
                   8115: =item *
                   8116: 
1.243     albertel 8117: repcopy($filename) : subscribes to the requested file, and attempts to
                   8118: replicate from the owning library server, Might return
1.607     raeburn  8119: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   8120: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 8121: resource. Expects the local filesystem pathname
                   8122: (/home/httpd/html/res/....)
                   8123: 
                   8124: =back
                   8125: 
                   8126: =head2 Resource Information
                   8127: 
                   8128: =over 4
1.191     harris41 8129: 
                   8130: =item *
                   8131: 
1.243     albertel 8132: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   8133: a vairety of different possible values, $varname should be a request
                   8134: string, and the other parameters can be used to specify who and what
                   8135: one is asking about.
                   8136: 
                   8137: Possible values for $varname are environment.lastname (or other item
                   8138: from the envirnment hash), user.name (or someother aspect about the
                   8139: user), resource.0.maxtries (or some other part and parameter of a
                   8140: resource)
1.204     albertel 8141: 
                   8142: =item *
                   8143: 
1.243     albertel 8144: directcondval($number) : get current value of a condition; reads from a state
                   8145: string
1.204     albertel 8146: 
                   8147: =item *
                   8148: 
1.243     albertel 8149: condval($condidx) : value of condition index based on state
1.204     albertel 8150: 
                   8151: =item *
                   8152: 
1.243     albertel 8153: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   8154: resource's metadata, $what should be either a specific key, or either
                   8155: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   8156: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   8157: 
                   8158: this function automatically caches all requests
1.191     harris41 8159: 
                   8160: =item *
                   8161: 
1.243     albertel 8162: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   8163: network of library servers; returns file handle of where SQL and regex results
                   8164: will be stored for query
1.191     harris41 8165: 
                   8166: =item *
                   8167: 
1.243     albertel 8168: symbread($filename) : return symbolic list entry (filename argument optional);
                   8169: returns the data handle
1.191     harris41 8170: 
                   8171: =item *
                   8172: 
1.243     albertel 8173: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 8174: a possible symb for the URL in $thisfn, and if is an encryypted
                   8175: resource that the user accessed using /enc/ returns a 1 on success, 0
                   8176: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 8177: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 8178: 
1.191     harris41 8179: 
                   8180: =item *
                   8181: 
1.243     albertel 8182: symbclean($symb) : removes versions numbers from a symb, returns the
                   8183: cleaned symb
1.191     harris41 8184: 
                   8185: =item *
                   8186: 
1.243     albertel 8187: is_on_map($uri) : checks if the $uri is somewhere on the current
                   8188: course map, user must be in a course for it to work.
1.191     harris41 8189: 
                   8190: =item *
                   8191: 
1.243     albertel 8192: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 8193: 
                   8194: =item *
                   8195: 
1.243     albertel 8196: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   8197: a random seed, all arguments are optional, if they aren't sent it uses the
                   8198: environment to derive them. Note: if symb isn't sent and it can't get one
                   8199: from &symbread it will use the current time as its return value
1.191     harris41 8200: 
                   8201: =item *
                   8202: 
1.243     albertel 8203: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   8204: unfakeable, receipt
1.191     harris41 8205: 
                   8206: =item *
                   8207: 
1.620     albertel 8208: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 8209: 
                   8210: =item *
                   8211: 
1.243     albertel 8212: countacc($url) : count the number of accesses to a given URL
1.191     harris41 8213: 
                   8214: =item *
                   8215: 
1.243     albertel 8216: 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 8217: 
                   8218: =item *
                   8219: 
1.243     albertel 8220: 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 8221: 
                   8222: =item *
                   8223: 
1.243     albertel 8224: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 8225: 
                   8226: =item *
                   8227: 
1.243     albertel 8228: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   8229: forcing spreadsheet to reevaluate the resource scores next time.
                   8230: 
                   8231: =back
                   8232: 
                   8233: =head2 Storing/Retreiving Data
                   8234: 
                   8235: =over 4
1.191     harris41 8236: 
                   8237: =item *
                   8238: 
1.243     albertel 8239: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   8240: for this url; hashref needs to be given and should be a \%hashname; the
                   8241: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 8242: be derived from the env
1.191     harris41 8243: 
                   8244: =item *
                   8245: 
1.243     albertel 8246: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   8247: uses critical subroutine
1.191     harris41 8248: 
                   8249: =item *
                   8250: 
1.243     albertel 8251: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   8252: all args are optional
1.191     harris41 8253: 
                   8254: =item *
                   8255: 
1.717     albertel 8256: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   8257: dumps the complete (or key matching regexp) namespace into a hash
                   8258: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   8259: normally &store()ed into
                   8260: 
                   8261: $range should be either an integer '100' (give me the first 100
                   8262:                                            matching records)
                   8263:               or be  two integers sperated by a - with no spaces
                   8264:                  '30-50' (give me the 30th through the 50th matching
                   8265:                           records)
                   8266: 
                   8267: 
                   8268: =item *
                   8269: 
                   8270: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   8271: replaces a &store() version of data with a replacement set of data
                   8272: for a particular resource in a namespace passed in the $storehash hash 
                   8273: reference
                   8274: 
                   8275: =item *
                   8276: 
1.243     albertel 8277: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   8278: works very similar to store/cstore, but all data is stored in a
                   8279: temporary location and can be reset using tmpreset, $storehash should
                   8280: be a hash reference, returns nothing on success
1.191     harris41 8281: 
                   8282: =item *
                   8283: 
1.243     albertel 8284: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   8285: similar to restore, but all data is stored in a temporary location and
                   8286: can be reset using tmpreset. Returns a hash of values on success,
                   8287: error string otherwise.
1.191     harris41 8288: 
                   8289: =item *
                   8290: 
1.243     albertel 8291: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   8292: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 8293: 
                   8294: =item *
                   8295: 
1.243     albertel 8296: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   8297: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 8298: 
                   8299: =item *
                   8300: 
1.243     albertel 8301: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   8302: namesp ($udom and $uname are optional)
1.191     harris41 8303: 
                   8304: =item *
                   8305: 
1.702     albertel 8306: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 8307: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 8308: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  8309: 
1.702     albertel 8310: $range should be either an integer '100' (give me the first 100
                   8311:                                            matching records)
                   8312:               or be  two integers sperated by a - with no spaces
                   8313:                  '30-50' (give me the 30th through the 50th matching
                   8314:                           records)
1.449     matthew  8315: =item *
                   8316: 
                   8317: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   8318: $store can be a scalar, an array reference, or if the amount to be 
                   8319: incremented is > 1, a hash reference.
                   8320: 
                   8321: ($udom and $uname are optional)
1.191     harris41 8322: 
                   8323: =item *
                   8324: 
1.243     albertel 8325: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   8326: ($udom and $uname are optional)
1.191     harris41 8327: 
                   8328: =item *
                   8329: 
1.243     albertel 8330: cput($namespace,$storehash,$udom,$uname) : critical put
                   8331: ($udom and $uname are optional)
1.191     harris41 8332: 
                   8333: =item *
                   8334: 
1.748     albertel 8335: newput($namespace,$storehash,$udom,$uname) :
                   8336: 
                   8337: Attempts to store the items in the $storehash, but only if they don't
                   8338: currently exist, if this succeeds you can be certain that you have 
                   8339: successfully created a new key value pair in the $namespace db.
                   8340: 
                   8341: 
                   8342: Args:
                   8343:  $namespace: name of database to store values to
                   8344:  $storehash: hashref to store to the db
                   8345:  $udom: (optional) domain of user containing the db
                   8346:  $uname: (optional) name of user caontaining the db
                   8347: 
                   8348: Returns:
                   8349:  'ok' -> succeeded in storing all keys of $storehash
                   8350:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   8351:                         least <key> already existed in the db (other
                   8352:                         requested keys may also already exist)
                   8353:  'error: <msg>' -> unable to tie the DB or other erorr occured
                   8354:  'con_lost' -> unable to contact request server
                   8355:  'refused' -> action was not allowed by remote machine
                   8356: 
                   8357: 
                   8358: =item *
                   8359: 
1.243     albertel 8360: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   8361: reference filled in from namesp (encrypts the return communication)
                   8362: ($udom and $uname are optional)
1.191     harris41 8363: 
                   8364: =item *
                   8365: 
1.243     albertel 8366: log($udom,$name,$home,$message) : write to permanent log for user; use
                   8367: critical subroutine
                   8368: 
1.806     raeburn  8369: =item *
                   8370: 
                   8371: get_dom($namespace,$storearr,$udomain) : returns hash with keys from array
                   8372: reference filled in from namespace found in domain level on primary domain server ($udomain is optional)
                   8373: 
                   8374: =item *
                   8375: 
                   8376: put_dom($namespace,$storehash,$udomain) :  stores hash in namespace at domain level on primary domain server ($udomain is optional)
                   8377: 
1.243     albertel 8378: =back
                   8379: 
                   8380: =head2 Network Status Functions
                   8381: 
                   8382: =over 4
1.191     harris41 8383: 
                   8384: =item *
                   8385: 
                   8386: dirlist($uri) : return directory list based on URI
                   8387: 
                   8388: =item *
                   8389: 
1.243     albertel 8390: spareserver() : find server with least workload from spare.tab
                   8391: 
                   8392: =back
                   8393: 
                   8394: =head2 Apache Request
                   8395: 
                   8396: =over 4
1.191     harris41 8397: 
                   8398: =item *
                   8399: 
1.243     albertel 8400: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   8401: localhost, posts hash
                   8402: 
                   8403: =back
                   8404: 
                   8405: =head2 Data to String to Data
                   8406: 
                   8407: =over 4
1.191     harris41 8408: 
                   8409: =item *
                   8410: 
1.243     albertel 8411: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   8412: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 8413: 
                   8414: =item *
                   8415: 
1.243     albertel 8416: hashref2str($hashref) : convert a hashref into a string complete with
                   8417: escaping and '=' and '&' separators, supports elements that are
                   8418: arrayrefs and hashrefs
1.191     harris41 8419: 
                   8420: =item *
                   8421: 
1.243     albertel 8422: arrayref2str($arrayref) : convert an arrayref into a string complete
                   8423: with escaping and '&' separators, supports elements that are arrayrefs
                   8424: and hashrefs
1.191     harris41 8425: 
                   8426: =item *
                   8427: 
1.243     albertel 8428: str2hash($string) : convert string to hash using unescaping and
                   8429: splitting on '=' and '&', supports elements that are arrayrefs and
                   8430: hashrefs
1.191     harris41 8431: 
                   8432: =item *
                   8433: 
1.243     albertel 8434: str2array($string) : convert string to hash using unescaping and
                   8435: splitting on '&', supports elements that are arrayrefs and hashrefs
                   8436: 
                   8437: =back
                   8438: 
                   8439: =head2 Logging Routines
                   8440: 
                   8441: =over 4
                   8442: 
                   8443: These routines allow one to make log messages in the lonnet.log and
                   8444: lonnet.perm logfiles.
1.191     harris41 8445: 
                   8446: =item *
                   8447: 
1.243     albertel 8448: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 8449: 
                   8450: =item *
                   8451: 
1.243     albertel 8452: logthis() : append message to the normal lonnet.log file, it gets
                   8453: preiodically rolled over and deleted.
1.191     harris41 8454: 
                   8455: =item *
                   8456: 
1.243     albertel 8457: logperm() : append a permanent message to lonnet.perm.log, this log
                   8458: file never gets deleted by any automated portion of the system, only
                   8459: messages of critical importance should go in here.
                   8460: 
                   8461: =back
                   8462: 
                   8463: =head2 General File Helper Routines
                   8464: 
                   8465: =over 4
1.191     harris41 8466: 
                   8467: =item *
                   8468: 
1.481     raeburn  8469: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   8470: (a) files in /uploaded
                   8471:   (i) If a local copy of the file exists - 
                   8472:       compares modification date of local copy with last-modified date for 
                   8473:       definitive version stored on home server for course. If local copy is 
                   8474:       stale, requests a new version from the home server and stores it. 
                   8475:       If the original has been removed from the home server, then local copy 
                   8476:       is unlinked.
                   8477:   (ii) If local copy does not exist -
                   8478:       requests the file from the home server and stores it. 
                   8479:   
                   8480:   If $caller is 'uploadrep':  
                   8481:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   8482:     for request for files originally uploaded via DOCS. 
                   8483:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   8484:   
                   8485:   Otherwise:
                   8486:      This indicates a call from the content generation phase of the request.
                   8487:      -  returns the entire contents of the file or -1.
                   8488:      
                   8489: (b) files in /res
                   8490:    - returns the entire contents of a file or -1; 
                   8491:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 8492: 
1.712     albertel 8493: 
                   8494: =item *
                   8495: 
                   8496: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   8497:                   reference
                   8498: 
                   8499: returns either a stat() list of data about the file or an empty list
                   8500: if the file doesn't exist or couldn't find out about it (connection
                   8501: problems or user unknown)
                   8502: 
1.191     harris41 8503: =item *
                   8504: 
1.243     albertel 8505: filelocation($dir,$file) : returns file system location of a file
                   8506: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   8507: directory that relative $file lookups are to looked in ($dir of /a/dir
                   8508: and a file of ../bob will become /a/bob)
1.191     harris41 8509: 
                   8510: =item *
                   8511: 
                   8512: hreflocation($dir,$file) : returns file system location or a URL; same as
                   8513: filelocation except for hrefs
                   8514: 
                   8515: =item *
                   8516: 
                   8517: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   8518: 
1.243     albertel 8519: =back
                   8520: 
1.608     albertel 8521: =head2 Usererfile file routines (/uploaded*)
                   8522: 
                   8523: =over 4
                   8524: 
                   8525: =item *
                   8526: 
                   8527: userfileupload(): main rotine for putting a file in a user or course's
                   8528:                   filespace, arguments are,
                   8529: 
1.620     albertel 8530:  formname - required - this is the name of the element in $env where the
1.608     albertel 8531:            filename, and the contents of the file to create/modifed exist
1.620     albertel 8532:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   8533:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 8534:  coursedoc - if true, store the file in the course of the active role
                   8535:              of the current user
                   8536:  subdir - required - subdirectory to put the file in under ../userfiles/
                   8537:          if undefined, it will be placed in "unknown"
                   8538: 
                   8539:  (This routine calls clean_filename() to remove any dangerous
                   8540:  characters from the filename, and then calls finuserfileupload() to
                   8541:  complete the transaction)
                   8542: 
                   8543:  returns either the url of the uploaded file (/uploaded/....) if successful
                   8544:  and /adm/notfound.html if unsuccessful
                   8545: 
                   8546: =item *
                   8547: 
                   8548: clean_filename(): routine for cleaing a filename up for storage in
                   8549:                  userfile space, argument is:
                   8550: 
                   8551:  filename - proposed filename
                   8552: 
                   8553: returns: the new clean filename
                   8554: 
                   8555: =item *
                   8556: 
                   8557: finishuserfileupload(): routine that creaes and sends the file to
                   8558: userspace, probably shouldn't be called directly
                   8559: 
                   8560:   docuname: username or courseid of destination for the file
                   8561:   docudom: domain of user/course of destination for the file
                   8562:   formname: same as for userfileupload()
                   8563:   fname: filename (inculding subdirectories) for the file
                   8564: 
                   8565:  returns either the url of the uploaded file (/uploaded/....) if successful
                   8566:  and /adm/notfound.html if unsuccessful
                   8567: 
                   8568: =item *
                   8569: 
                   8570: renameuserfile(): renames an existing userfile to a new name
                   8571: 
                   8572:   Args:
                   8573:    docuname: username or courseid of destination for the file
                   8574:    docudom: domain of user/course of destination for the file
                   8575:    old: current file name (including any subdirs under userfiles)
                   8576:    new: desired file name (including any subdirs under userfiles)
                   8577: 
                   8578: =item *
                   8579: 
                   8580: mkdiruserfile(): creates a directory is a userfiles dir
                   8581: 
                   8582:   Args:
                   8583:    docuname: username or courseid of destination for the file
                   8584:    docudom: domain of user/course of destination for the file
                   8585:    dir: dir to create (including any subdirs under userfiles)
                   8586: 
                   8587: =item *
                   8588: 
                   8589: removeuserfile(): removes a file that exists in userfiles
                   8590: 
                   8591:   Args:
                   8592:    docuname: username or courseid of destination for the file
                   8593:    docudom: domain of user/course of destination for the file
                   8594:    fname: filname to delete (including any subdirs under userfiles)
                   8595: 
                   8596: =item *
                   8597: 
                   8598: removeuploadedurl(): convience function for removeuserfile()
                   8599: 
                   8600:   Args:
                   8601:    url:  a full /uploaded/... url to delete
                   8602: 
1.747     albertel 8603: =item * 
                   8604: 
                   8605: get_portfile_permissions():
                   8606:   Args:
                   8607:     domain: domain of user or course contain the portfolio files
                   8608:     user: name of user or num of course contain the portfolio files
                   8609:   Returns:
                   8610:     hashref of a dump of the proper file_permissions.db
                   8611:    
                   8612: 
                   8613: =item * 
                   8614: 
                   8615: get_access_controls():
                   8616: 
                   8617: Args:
                   8618:   current_permissions: the hash ref returned from get_portfile_permissions()
                   8619:   group: (optional) the group you want the files associated with
                   8620:   file: (optional) the file you want access info on
                   8621: 
                   8622: Returns:
1.749     raeburn  8623:     a hash (keys are file names) of hashes containing
                   8624:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   8625:         values are XML containing access control settings (see below) 
1.747     albertel 8626: 
                   8627: Internal notes:
                   8628: 
1.749     raeburn  8629:  access controls are stored in file_permissions.db as key=value pairs.
                   8630:     key -> path to file/file_name\0uniqueID:scope_end_start
                   8631:         where scope -> public,guest,course,group,domains or users.
                   8632:               end -> UNIX time for end of access (0 -> no end date)
                   8633:               start -> UNIX time for start of access
                   8634: 
                   8635:     value -> XML description of access control
                   8636:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   8637:             <start></start>
                   8638:             <end></end>
                   8639: 
                   8640:             <password></password>  for scope type = guest
                   8641: 
                   8642:             <domain></domain>     for scope type = course or group
                   8643:             <number></number>
                   8644:             <roles id="">
                   8645:              <role></role>
                   8646:              <access></access>
                   8647:              <section></section>
                   8648:              <group></group>
                   8649:             </roles>
                   8650: 
                   8651:             <dom></dom>         for scope type = domains
                   8652: 
                   8653:             <users>             for scope type = users
                   8654:              <user>
                   8655:               <uname></uname>
                   8656:               <udom></udom>
                   8657:              </user>
                   8658:             </users>
                   8659:            </scope> 
                   8660:               
                   8661:  Access data is also aggregated for each file in an additional key=value pair:
                   8662:  key -> path to file/file_name\0accesscontrol 
                   8663:  value -> reference to hash
                   8664:           hash contains key = value pairs
                   8665:           where key = uniqueID:scope_end_start
                   8666:                 value = UNIX time record was last updated
                   8667: 
                   8668:           Used to improve speed of look-ups of access controls for each file.  
                   8669:  
                   8670:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   8671: 
                   8672: modify_access_controls():
                   8673: 
                   8674: Modifies access controls for a portfolio file
                   8675: Args
                   8676: 1. file name
                   8677: 2. reference to hash of required changes,
                   8678: 3. domain
                   8679: 4. username
                   8680:   where domain,username are the domain of the portfolio owner 
                   8681:   (either a user or a course) 
                   8682: 
                   8683: Returns:
                   8684: 1. result of additions or updates ('ok' or 'error', with error message). 
                   8685: 2. result of deletions ('ok' or 'error', with error message).
                   8686: 3. reference to hash of any new or updated access controls.
                   8687: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   8688:    key = integer (inbound ID)
                   8689:    value = uniqueID  
1.747     albertel 8690: 
1.608     albertel 8691: =back
                   8692: 
1.243     albertel 8693: =head2 HTTP Helper Routines
                   8694: 
                   8695: =over 4
                   8696: 
1.191     harris41 8697: =item *
                   8698: 
                   8699: escape() : unpack non-word characters into CGI-compatible hex codes
                   8700: 
                   8701: =item *
                   8702: 
                   8703: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   8704: 
1.243     albertel 8705: =back
                   8706: 
                   8707: =head1 PRIVATE SUBROUTINES
                   8708: 
                   8709: =head2 Underlying communication routines (Shouldn't call)
                   8710: 
                   8711: =over 4
                   8712: 
                   8713: =item *
                   8714: 
                   8715: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   8716: 
                   8717: =item *
                   8718: 
                   8719: reply() : uses subreply to send a message to remote machine, logs all failures
                   8720: 
                   8721: =item *
                   8722: 
                   8723: critical() : passes a critical message to another server; if cannot
                   8724: get through then place message in connection buffer directory and
                   8725: returns con_delayed, if incapable of saving message, returns
                   8726: con_failed
                   8727: 
                   8728: =item *
                   8729: 
                   8730: reconlonc() : tries to reconnect lonc client processes.
                   8731: 
                   8732: =back
                   8733: 
                   8734: =head2 Resource Access Logging
                   8735: 
                   8736: =over 4
                   8737: 
                   8738: =item *
                   8739: 
                   8740: flushcourselogs() : flush (save) buffer logs and access logs
                   8741: 
                   8742: =item *
                   8743: 
                   8744: courselog($what) : save message for course in hash
                   8745: 
                   8746: =item *
                   8747: 
                   8748: courseacclog($what) : save message for course using &courselog().  Perform
                   8749: special processing for specific resource types (problems, exams, quizzes, etc).
                   8750: 
1.191     harris41 8751: =item *
                   8752: 
                   8753: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   8754: as a PerlChildExitHandler
1.243     albertel 8755: 
                   8756: =back
                   8757: 
                   8758: =head2 Other
                   8759: 
                   8760: =over 4
                   8761: 
                   8762: =item *
                   8763: 
                   8764: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 8765: 
                   8766: =back
                   8767: 
                   8768: =cut

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