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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.831   ! albertel    4: # $Id: lonnet.pm,v 1.830 2007/01/25 21:09:24 albertel Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.1       albertel   30: package Apache::lonnet;
                     31: 
                     32: use strict;
1.8       www        33: use LWP::UserAgent();
1.15      www        34: use HTTP::Headers;
1.486     www        35: use HTTP::Date;
                     36: # use Date::Parse;
1.11      www        37: use vars 
1.599     albertel   38: qw(%perlvar %hostname %badServerCache %iphost %spareid %hostdom 
                     39:    %libserv %pr %prp $memcache %packagetab 
1.662     raeburn    40:    %courselogs %accesshash %userrolehash %domainrolehash $processmarker $dumpcount 
1.741     raeburn    41:    %coursedombuf %coursenumbuf %coursehombuf %coursedescrbuf %courseinstcodebuf %courseownerbuf %coursetypebuf
1.599     albertel   42:    %domaindescription %domain_auth_def %domain_auth_arg_def 
1.685     raeburn    43:    %domain_lang_def %domain_city %domain_longi %domain_lati %domain_primary
                     44:    $tmpdir $_64bit %env);
1.403     www        45: 
1.1       albertel   46: use IO::Socket;
1.31      www        47: use GDBM_File;
1.208     albertel   48: use HTML::LCParser;
1.637     raeburn    49: use HTML::Parser;
1.88      www        50: use Fcntl qw(:flock);
1.557     albertel   51: use Storable qw(lock_store lock_nstore lock_retrieve freeze thaw nfreeze);
1.539     albertel   52: use Time::HiRes qw( gettimeofday tv_interval );
1.599     albertel   53: use Cache::Memcached;
1.676     albertel   54: use Digest::MD5;
1.790     albertel   55: use Math::Random;
1.807     albertel   56: use LONCAPA qw(:DEFAULT :match);
1.740     www        57: use LONCAPA::Configuration;
1.676     albertel   58: 
1.195     www        59: my $readit;
1.550     foxr       60: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel   61: 
1.619     albertel   62: require Exporter;
                     63: 
                     64: our @ISA = qw (Exporter);
                     65: our @EXPORT = qw(%env);
                     66: 
1.449     matthew    67: =pod
                     68: 
                     69: =head1 Package Variables
                     70: 
                     71: These are largely undocumented, so if you decipher one please note it here.
                     72: 
                     73: =over 4
                     74: 
                     75: =item $processmarker
                     76: 
                     77: Contains the time this process was started and this servers host id.
                     78: 
                     79: =item $dumpcount
                     80: 
                     81: Counts the number of times a message log flush has been attempted (regardless
                     82: of success) by this process.  Used as part of the filename when messages are
                     83: delayed.
                     84: 
                     85: =back
                     86: 
                     87: =cut
                     88: 
                     89: 
1.1       albertel   90: # --------------------------------------------------------------------- Logging
1.729     www        91: {
                     92:     my $logid;
                     93:     sub instructor_log {
                     94: 	my ($hash_name,$storehash,$delflag,$uname,$udom)=@_;
                     95: 	$logid++;
                     96: 	my $id=time().'00000'.$$.'00000'.$logid;
                     97: 	return &Apache::lonnet::put('nohist_'.$hash_name,
1.730     www        98: 				    { $id => {
                     99: 					'exe_uname' => $env{'user.name'},
                    100: 					'exe_udom'  => $env{'user.domain'},
                    101: 					'exe_time'  => time(),
                    102: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    103: 					'delflag'   => $delflag,
                    104: 					'logentry'  => $storehash,
                    105: 					'uname'     => $uname,
                    106: 					'udom'      => $udom,
                    107: 				    }
                    108: 				  },
1.729     www       109: 				    $env{'course.'.$env{'request.course.id'}.'.domain'},
                    110: 				    $env{'course.'.$env{'request.course.id'}.'.num'}
                    111: 				    );
                    112:     }
                    113: }
1.1       albertel  114: 
1.163     harris41  115: sub logtouch {
                    116:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  117:     unless (-e "$execdir/logs/lonnet.log") {	
                    118: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  119: 	close $fh;
                    120:     }
                    121:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    122:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    123: }
                    124: 
1.1       albertel  125: sub logthis {
                    126:     my $message=shift;
                    127:     my $execdir=$perlvar{'lonDaemons'};
                    128:     my $now=time;
                    129:     my $local=localtime($now);
1.448     albertel  130:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
                    131: 	print $fh "$local ($$): $message\n";
                    132: 	close($fh);
                    133:     }
1.1       albertel  134:     return 1;
                    135: }
                    136: 
                    137: sub logperm {
                    138:     my $message=shift;
                    139:     my $execdir=$perlvar{'lonDaemons'};
                    140:     my $now=time;
                    141:     my $local=localtime($now);
1.448     albertel  142:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    143: 	print $fh "$now:$message:$local\n";
                    144: 	close($fh);
                    145:     }
1.1       albertel  146:     return 1;
                    147: }
                    148: 
                    149: # -------------------------------------------------- Non-critical communication
                    150: sub subreply {
                    151:     my ($cmd,$server)=@_;
1.704     albertel  152:     my $peerfile="$perlvar{'lonSockDir'}/".$hostname{$server};
1.549     foxr      153:     #
                    154:     #  With loncnew process trimming, there's a timing hole between lonc server
                    155:     #  process exit and the master server picking up the listen on the AF_UNIX
                    156:     #  socket.  In that time interval, a lock file will exist:
                    157: 
                    158:     my $lockfile=$peerfile.".lock";
                    159:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    160: 	sleep(1);
                    161:     }
                    162:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      163:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      164:     #
1.550     foxr      165:     #   We'll give the connection a few tries before abandoning it.  If
                    166:     #   connection is not possible, we'll con_lost back to the client.
                    167:     #   
                    168:     my $client;
                    169:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    170: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    171: 				      Type    => SOCK_STREAM,
                    172: 				      Timeout => 10);
                    173: 	if($client) {
                    174: 	    last;		# Connected!
                    175: 	}
                    176: 	sleep(1);		# Try again later if failed connection.
                    177:     }
                    178:     my $answer;
                    179:     if ($client) {
1.704     albertel  180: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      181: 	$answer=<$client>;
                    182: 	if (!$answer) { $answer="con_lost"; }
                    183: 	chomp($answer);
                    184:     } else {
                    185: 	$answer = 'con_lost';	# Failed connection.
                    186:     }
1.1       albertel  187:     return $answer;
                    188: }
                    189: 
                    190: sub reply {
                    191:     my ($cmd,$server)=@_;
1.205     www       192:     unless (defined($hostname{$server})) { return 'no_such_host'; }
1.1       albertel  193:     my $answer=subreply($cmd,$server);
1.65      www       194:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  195:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       196:                 " $cmd to $server returned $answer</font>");
                    197:     }
1.1       albertel  198:     return $answer;
                    199: }
                    200: 
                    201: # ----------------------------------------------------------- Send USR1 to lonc
                    202: 
                    203: sub reconlonc {
                    204:     my $peerfile=shift;
                    205:     &logthis("Trying to reconnect for $peerfile");
                    206:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  207:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  208: 	my $loncpid=<$fh>;
                    209:         chomp($loncpid);
                    210:         if (kill 0 => $loncpid) {
                    211: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    212:             kill USR1 => $loncpid;
                    213:             sleep 1;
                    214:             if (-e "$peerfile") { return; }
                    215:             &logthis("$peerfile still not there, give it another try");
                    216:             sleep 5;
                    217:             if (-e "$peerfile") { return; }
1.12      www       218:             &logthis(
1.672     albertel  219:   "<font color=\"blue\">WARNING: $peerfile still not there, giving up</font>");
1.1       albertel  220:         } else {
1.12      www       221: 	    &logthis(
1.672     albertel  222:                "<font color=\"blue\">WARNING:".
1.12      www       223:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  224:         }
                    225:     } else {
1.672     albertel  226:      &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  227:     }
                    228: }
                    229: 
                    230: # ------------------------------------------------------ Critical communication
1.12      www       231: 
1.1       albertel  232: sub critical {
                    233:     my ($cmd,$server)=@_;
1.89      www       234:     unless ($hostname{$server}) {
1.672     albertel  235:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       236:                " Critical message to unknown server ($server)</font>");
                    237:         return 'no_such_host';
                    238:     }
1.1       albertel  239:     my $answer=reply($cmd,$server);
                    240:     if ($answer eq 'con_lost') {
                    241: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  242: 	my $answer=reply($cmd,$server);
1.1       albertel  243:         if ($answer eq 'con_lost') {
                    244:             my $now=time;
                    245:             my $middlename=$cmd;
1.5       www       246:             $middlename=substr($middlename,0,16);
1.1       albertel  247:             $middlename=~s/\W//g;
                    248:             my $dfilename=
1.305     www       249:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    250:             $dumpcount++;
1.1       albertel  251:             {
1.448     albertel  252: 		my $dfh;
                    253: 		if (open($dfh,">$dfilename")) {
                    254: 		    print $dfh "$cmd\n"; 
                    255: 		    close($dfh);
                    256: 		}
1.1       albertel  257:             }
                    258:             sleep 2;
                    259:             my $wcmd='';
                    260:             {
1.448     albertel  261: 		my $dfh;
                    262: 		if (open($dfh,"<$dfilename")) {
                    263: 		    $wcmd=<$dfh>; 
                    264: 		    close($dfh);
                    265: 		}
1.1       albertel  266:             }
                    267:             chomp($wcmd);
1.7       www       268:             if ($wcmd eq $cmd) {
1.672     albertel  269: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       270:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  271:                 &logperm("D:$server:$cmd");
                    272: 	        return 'con_delayed';
                    273:             } else {
1.672     albertel  274:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       275:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  276:                 &logperm("F:$server:$cmd");
                    277:                 return 'con_failed';
                    278:             }
                    279:         }
                    280:     }
                    281:     return $answer;
1.405     albertel  282: }
                    283: 
1.755     albertel  284: # ------------------------------------------- check if return value is an error
                    285: 
                    286: sub error {
                    287:     my ($result) = @_;
1.756     albertel  288:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  289: 	if ($2 == 2) { return undef; }
                    290: 	return $1;
                    291:     }
                    292:     return undef;
                    293: }
                    294: 
1.783     albertel  295: sub convert_and_load_session_env {
                    296:     my ($lonidsdir,$handle)=@_;
                    297:     my @profile;
                    298:     {
                    299: 	open(my $idf,"$lonidsdir/$handle.id");
                    300: 	flock($idf,LOCK_SH);
                    301: 	@profile=<$idf>;
                    302: 	close($idf);
                    303:     }
                    304:     my %temp_env;
                    305:     foreach my $line (@profile) {
1.786     albertel  306: 	if ($line !~ m/=/) {
                    307: 	    return 0;
                    308: 	}
1.783     albertel  309: 	chomp($line);
                    310: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    311: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    312:     }
                    313:     unlink("$lonidsdir/$handle.id");
                    314:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    315: 	    0640)) {
                    316: 	%disk_env = %temp_env;
                    317: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    318: 	untie(%disk_env);
                    319:     }
1.786     albertel  320:     return 1;
1.783     albertel  321: }
                    322: 
1.374     www       323: # ------------------------------------------- Transfer profile into environment
1.780     albertel  324: my $env_loaded;
                    325: sub transfer_profile_to_env {
1.788     albertel  326:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    327:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       328: 
1.720     albertel  329:     if (!defined($lonidsdir)) {
                    330: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    331:     }
                    332:     if (!defined($handle)) {
                    333:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    334:     }
                    335: 
1.786     albertel  336:     my $convert;
                    337:     {
                    338:     	open(my $idf,"$lonidsdir/$handle.id");
                    339: 	flock($idf,LOCK_SH);
                    340: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    341: 		&GDBM_READER(),0640)) {
                    342: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    343: 	    untie(%disk_env);
                    344: 	} else {
                    345: 	    $convert = 1;
                    346: 	}
                    347:     }
                    348:     if ($convert) {
                    349: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    350: 	    &logthis("Failed to load session, or convert session.");
                    351: 	}
1.374     www       352:     }
1.783     albertel  353: 
1.786     albertel  354:     my %remove;
1.783     albertel  355:     while ( my $envname = each(%env) ) {
1.433     matthew   356:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    357:             if ($time < time-300) {
1.783     albertel  358:                 $remove{$key}++;
1.433     matthew   359:             }
                    360:         }
                    361:     }
1.783     albertel  362: 
1.619     albertel  363:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  364:     $env_loaded=1;
1.783     albertel  365:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   366:         &delenv($expired_key);
1.374     www       367:     }
1.1       albertel  368: }
                    369: 
1.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 {
1.831   ! albertel 1454:     my ($fname,$args)=@_;
1.315     www      1455: # Replace Windows backslashes by forward slashes
1.257     www      1456:     $fname=~s/\\/\//g;
1.831   ! albertel 1457:     if (!$args->{'keep_path'}) {
        !          1458:         # Get rid of everything but the actual filename
        !          1459: 	$fname=~s/^.*\/([^\/]+)$/$1/;
        !          1460:     }
1.315     www      1461: # Replace spaces by underscores
                   1462:     $fname=~s/\s+/\_/g;
                   1463: # Replace all other weird characters by nothing
1.831   ! albertel 1464:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 1465: # Replace all .\d. sequences with _\d. so they no longer look like version
                   1466: # numbers
                   1467:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 1468:     return $fname;
                   1469: }
                   1470: 
1.608     albertel 1471: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 1472: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 1473: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 1474: #        $coursedoc - if true up to the current course
                   1475: #                     if false
                   1476: #        $subdir - directory in userfile to store the file into
                   1477: #        $parser, $allfiles, $codebase - unknown
                   1478: #
                   1479: # output: url of file in userspace, or error: <message> 
                   1480: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 1481: 
                   1482: 
1.531     albertel 1483: sub userfileupload {
1.719     banghart 1484:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,$destudom)=@_;
1.531     albertel 1485:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 1486:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 1487:     $fname=&clean_filename($fname);
1.315     www      1488: # See if there is anything left
1.257     www      1489:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 1490:     chop($env{'form.'.$formname});
1.523     raeburn  1491:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   1492:         my $now = time;
                   1493:         my $filepath = 'tmp/helprequests/'.$now;
                   1494:         my @parts=split(/\//,$filepath);
                   1495:         my $fullpath = $perlvar{'lonDaemons'};
                   1496:         for (my $i=0;$i<@parts;$i++) {
                   1497:             $fullpath .= '/'.$parts[$i];
                   1498:             if ((-e $fullpath)!=1) {
                   1499:                 mkdir($fullpath,0777);
                   1500:             }
                   1501:         }
                   1502:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 1503:         print $fh $env{'form.'.$formname};
1.523     raeburn  1504:         close($fh);
1.741     raeburn  1505:         return $fullpath.'/'.$fname;
                   1506:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   1507:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   1508:                        '_'.$env{'user.domain'}.'/pending';
                   1509:         my @parts=split(/\//,$filepath);
                   1510:         my $fullpath = $perlvar{'lonDaemons'};
                   1511:         for (my $i=0;$i<@parts;$i++) {
                   1512:             $fullpath .= '/'.$parts[$i];
                   1513:             if ((-e $fullpath)!=1) {
                   1514:                 mkdir($fullpath,0777);
                   1515:             }
                   1516:         }
                   1517:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   1518:         print $fh $env{'form.'.$formname};
                   1519:         close($fh);
                   1520:         return $fullpath.'/'.$fname;
1.523     raeburn  1521:     }
1.719     banghart 1522:     
1.258     www      1523: # Create the directory if not present
1.493     albertel 1524:     $fname="$subdir/$fname";
1.259     www      1525:     if ($coursedoc) {
1.638     albertel 1526: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1527: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  1528:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 1529:             return &finishuserfileupload($docuname,$docudom,
                   1530: 					 $formname,$fname,$parser,$allfiles,
                   1531: 					 $codebase);
1.481     raeburn  1532:         } else {
1.620     albertel 1533:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 1534:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   1535: 				       $fname,$formname,$parser,
                   1536: 				       $allfiles,$codebase);
1.481     raeburn  1537:         }
1.719     banghart 1538:     } elsif (defined($destuname)) {
                   1539:         my $docuname=$destuname;
                   1540:         my $docudom=$destudom;
                   1541: 	return &finishuserfileupload($docuname,$docudom,$formname,
                   1542: 				     $fname,$parser,$allfiles,$codebase);
                   1543:         
1.259     www      1544:     } else {
1.638     albertel 1545:         my $docuname=$env{'user.name'};
                   1546:         my $docudom=$env{'user.domain'};
1.714     raeburn  1547:         if (exists($env{'form.group'})) {
                   1548:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1549:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1550:         }
1.638     albertel 1551: 	return &finishuserfileupload($docuname,$docudom,$formname,
                   1552: 				     $fname,$parser,$allfiles,$codebase);
1.259     www      1553:     }
1.271     www      1554: }
                   1555: 
                   1556: sub finishuserfileupload {
1.638     albertel 1557:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase) = @_;
1.477     raeburn  1558:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      1559:     my $filepath=$perlvar{'lonDocRoot'};
1.494     albertel 1560:     my ($fnamepath,$file);
                   1561:     $file=$fname;
                   1562:     if ($fname=~m|/|) {
                   1563:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   1564: 	$path.=$fnamepath.'/';
                   1565:     }
1.259     www      1566:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      1567:     my $count;
                   1568:     for ($count=4;$count<=$#parts;$count++) {
                   1569:         $filepath.="/$parts[$count]";
                   1570:         if ((-e $filepath)!=1) {
                   1571: 	    mkdir($filepath,0777);
                   1572:         }
                   1573:     }
                   1574: # Save the file
                   1575:     {
1.701     albertel 1576: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   1577: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   1578: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   1579: 	    return '/adm/notfound.html';
                   1580: 	}
                   1581: 	if (!print FH ($env{'form.'.$formname})) {
                   1582: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   1583: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   1584: 	    return '/adm/notfound.html';
                   1585: 	}
1.570     albertel 1586: 	close(FH);
1.258     www      1587:     }
1.637     raeburn  1588:     if ($parser eq 'parse') {
1.638     albertel 1589:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
                   1590: 						   $codebase);
1.637     raeburn  1591:         unless ($parse_result eq 'ok') {
1.638     albertel 1592:             &logthis('Failed to parse '.$filepath.$file.
                   1593: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  1594:         }
                   1595:     }
1.259     www      1596: # Notify homeserver to grep it
                   1597: #
1.638     albertel 1598:     my $docuhome=&homeserver($docuname,$docudom);
1.494     albertel 1599:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      1600:     if ($fetchresult eq 'ok') {
1.259     www      1601: #
1.258     www      1602: # Return the URL to it
1.494     albertel 1603:         return '/uploaded/'.$path.$file;
1.263     www      1604:     } else {
1.494     albertel 1605:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   1606: 		 ': '.$fetchresult);
1.263     www      1607:         return '/adm/notfound.html';
                   1608:     }    
1.493     albertel 1609: }
                   1610: 
1.637     raeburn  1611: sub extract_embedded_items {
1.648     raeburn  1612:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
1.637     raeburn  1613:     my @state = ();
                   1614:     my %javafiles = (
                   1615:                       codebase => '',
                   1616:                       code => '',
                   1617:                       archive => ''
                   1618:                     );
                   1619:     my %mediafiles = (
                   1620:                       src => '',
                   1621:                       movie => '',
                   1622:                      );
1.648     raeburn  1623:     my $p;
                   1624:     if ($content) {
                   1625:         $p = HTML::LCParser->new($content);
                   1626:     } else {
                   1627:         $p = HTML::LCParser->new($filepath.'/'.$file);
                   1628:     }
1.641     albertel 1629:     while (my $t=$p->get_token()) {
1.640     albertel 1630: 	if ($t->[0] eq 'S') {
                   1631: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
                   1632: 	    push (@state, $tagname);
1.648     raeburn  1633:             if (lc($tagname) eq 'allow') {
                   1634:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   1635:             }
1.640     albertel 1636: 	    if (lc($tagname) eq 'img') {
                   1637: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   1638: 	    }
1.645     raeburn  1639:             if (lc($tagname) eq 'script') {
                   1640:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   1641:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   1642:                 } else {
                   1643:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   1644:                 }
                   1645:             }
                   1646:             if (lc($tagname) eq 'link') {
                   1647:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   1648:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   1649:                 }
                   1650:             }
1.640     albertel 1651: 	    if (lc($tagname) eq 'object' ||
                   1652: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   1653: 		foreach my $item (keys(%javafiles)) {
                   1654: 		    $javafiles{$item} = '';
                   1655: 		}
                   1656: 	    }
                   1657: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   1658: 		my $name = lc($attr->{'name'});
                   1659: 		foreach my $item (keys(%javafiles)) {
                   1660: 		    if ($name eq $item) {
                   1661: 			$javafiles{$item} = $attr->{'value'};
                   1662: 			last;
                   1663: 		    }
                   1664: 		}
                   1665: 		foreach my $item (keys(%mediafiles)) {
                   1666: 		    if ($name eq $item) {
                   1667: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   1668: 			last;
                   1669: 		    }
                   1670: 		}
                   1671: 	    }
                   1672: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   1673: 		foreach my $item (keys(%javafiles)) {
                   1674: 		    if ($attr->{$item}) {
                   1675: 			$javafiles{$item} = $attr->{$item};
                   1676: 			last;
                   1677: 		    }
                   1678: 		}
                   1679: 		foreach my $item (keys(%mediafiles)) {
                   1680: 		    if ($attr->{$item}) {
                   1681: 			&add_filetype($allfiles,$attr->{$item},$item);
                   1682: 			last;
                   1683: 		    }
                   1684: 		}
                   1685: 	    }
                   1686: 	} elsif ($t->[0] eq 'E') {
                   1687: 	    my ($tagname) = ($t->[1]);
                   1688: 	    if ($javafiles{'codebase'} ne '') {
                   1689: 		$javafiles{'codebase'} .= '/';
                   1690: 	    }  
                   1691: 	    if (lc($tagname) eq 'applet' ||
                   1692: 		lc($tagname) eq 'object' ||
                   1693: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   1694: 		) {
                   1695: 		foreach my $item (keys(%javafiles)) {
                   1696: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   1697: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   1698: 			&add_filetype($allfiles,$file,$item);
                   1699: 		    }
                   1700: 		}
                   1701: 	    } 
                   1702: 	    pop @state;
                   1703: 	}
                   1704:     }
1.637     raeburn  1705:     return 'ok';
                   1706: }
                   1707: 
1.639     albertel 1708: sub add_filetype {
                   1709:     my ($allfiles,$file,$type)=@_;
                   1710:     if (exists($allfiles->{$file})) {
                   1711: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   1712: 	    push(@{$allfiles->{$file}}, &escape($type));
                   1713: 	}
                   1714:     } else {
                   1715: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  1716:     }
                   1717: }
                   1718: 
1.493     albertel 1719: sub removeuploadedurl {
                   1720:     my ($url)=@_;
                   1721:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613     albertel 1722:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 1723: }
                   1724: 
                   1725: sub removeuserfile {
                   1726:     my ($docuname,$docudom,$fname)=@_;
                   1727:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  1728:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
                   1729:     if ($result eq 'ok') {
                   1730:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   1731:             my $metafile = $fname.'.meta';
                   1732:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 1733: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
                   1734:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  1735:             my $sqlresult = 
1.823     albertel 1736:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  1737:                                         'portfolio_metadata',$group,
                   1738:                                         'delete');
1.798     raeburn  1739:         }
                   1740:     }
                   1741:     return $result;
1.257     www      1742: }
1.15      www      1743: 
1.530     albertel 1744: sub mkdiruserfile {
                   1745:     my ($docuname,$docudom,$dir)=@_;
                   1746:     my $home=&homeserver($docuname,$docudom);
                   1747:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   1748: }
                   1749: 
1.531     albertel 1750: sub renameuserfile {
                   1751:     my ($docuname,$docudom,$old,$new)=@_;
                   1752:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  1753:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   1754:                         &escape("$old").':'.&escape("$new"),$home);
                   1755:     if ($result eq 'ok') {
                   1756:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   1757:             my $oldmeta = $old.'.meta';
                   1758:             my $newmeta = $new.'.meta';
                   1759:             my $metaresult = 
                   1760:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 1761: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   1762:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  1763:             my $sqlresult = 
1.823     albertel 1764:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  1765:                                         'portfolio_metadata',$group,
                   1766:                                         'delete');
1.798     raeburn  1767:         }
                   1768:     }
                   1769:     return $result;
1.531     albertel 1770: }
                   1771: 
1.14      www      1772: # ------------------------------------------------------------------------- Log
                   1773: 
                   1774: sub log {
                   1775:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      1776:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      1777: }
                   1778: 
                   1779: # ------------------------------------------------------------------ Course Log
1.352     www      1780: #
                   1781: # This routine flushes several buffers of non-mission-critical nature
                   1782: #
1.157     www      1783: 
                   1784: sub flushcourselogs {
1.352     www      1785:     &logthis('Flushing log buffers');
                   1786: #
                   1787: # course logs
                   1788: # This is a log of all transactions in a course, which can be used
                   1789: # for data mining purposes
                   1790: #
                   1791: # It also collects the courseid database, which lists last transaction
                   1792: # times and course titles for all courseids
                   1793: #
                   1794:     my %courseidbuffer=();
1.800     albertel 1795:     foreach my $crsid (keys %courselogs) {
1.352     www      1796:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      1797: 		          &escape($courselogs{$crsid}),
                   1798: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      1799: 	    delete $courselogs{$crsid};
                   1800:         } else {
                   1801:             &logthis('Failed to flush log buffer for '.$crsid);
                   1802:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 1803:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      1804:                         " exceeded maximum size, deleting.</font>");
                   1805:                delete $courselogs{$crsid};
                   1806:             }
1.352     www      1807:         }
                   1808:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
                   1809:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
1.516     raeburn  1810: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  1811:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.352     www      1812:         } else {
                   1813:            $courseidbuffer{$coursehombuf{$crsid}}=
1.516     raeburn  1814: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  1815:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.571     raeburn  1816:         }
1.191     harris41 1817:     }
1.352     www      1818: #
                   1819: # Write course id database (reverse lookup) to homeserver of courses 
                   1820: # Is used in pickcourse
                   1821: #
1.800     albertel 1822:     foreach my $crsid (keys(%courseidbuffer)) {
                   1823:         &courseidput($hostdom{$crsid},$courseidbuffer{$crsid},$crsid);
1.352     www      1824:     }
                   1825: #
                   1826: # File accesses
                   1827: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   1828: #
1.449     matthew  1829:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  1830:         if ($entry =~ /___count$/) {
                   1831:             my ($dom,$name);
1.807     albertel 1832:             ($dom,$name,undef)=
1.811     albertel 1833: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  1834:             if (! defined($dom) || $dom eq '' || 
                   1835:                 ! defined($name) || $name eq '') {
1.620     albertel 1836:                 my $cid = $env{'request.course.id'};
                   1837:                 $dom  = $env{'request.'.$cid.'.domain'};
                   1838:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  1839:             }
1.450     matthew  1840:             my $value = $accesshash{$entry};
                   1841:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   1842:             my %temphash=($url => $value);
1.449     matthew  1843:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   1844:             if ($result eq 'ok') {
                   1845:                 delete $accesshash{$entry};
                   1846:             } elsif ($result eq 'unknown_cmd') {
                   1847:                 # Target server has old code running on it.
1.450     matthew  1848:                 my %temphash=($entry => $value);
1.449     matthew  1849:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1850:                     delete $accesshash{$entry};
                   1851:                 }
                   1852:             }
                   1853:         } else {
1.811     albertel 1854:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  1855:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  1856:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1857:                 delete $accesshash{$entry};
                   1858:             }
1.185     www      1859:         }
1.191     harris41 1860:     }
1.352     www      1861: #
                   1862: # Roles
                   1863: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   1864: #
1.800     albertel 1865:     foreach my $entry (keys(%userrolehash)) {
1.351     www      1866:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      1867: 	    split(/\:/,$entry);
                   1868:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      1869:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      1870:                 $rudom,$runame) eq 'ok') {
                   1871: 	    delete $userrolehash{$entry};
                   1872:         }
                   1873:     }
1.662     raeburn  1874: #
                   1875: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   1876: #
                   1877:     my %domrolebuffer = ();
                   1878:     foreach my $entry (keys %domainrolehash) {
                   1879:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split/:/,$entry;
                   1880:         if ($domrolebuffer{$rudom}) {
                   1881:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   1882:                       '='.&escape($domainrolehash{$entry});
                   1883:         } else {
                   1884:             $domrolebuffer{$rudom}.=&escape($entry).
                   1885:                       '='.&escape($domainrolehash{$entry});
                   1886:         }
                   1887:         delete $domainrolehash{$entry};
                   1888:     }
                   1889:     foreach my $dom (keys(%domrolebuffer)) {
                   1890:         foreach my $tryserver (keys %libserv) {
                   1891:             if ($hostdom{$tryserver} eq $dom) {
                   1892:                 unless (&reply('domroleput:'.$dom.':'.
                   1893:                   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   1894:                     &logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   1895:                 }
                   1896:             }
                   1897:         }
                   1898:     }
1.186     www      1899:     $dumpcount++;
1.157     www      1900: }
                   1901: 
                   1902: sub courselog {
                   1903:     my $what=shift;
1.158     www      1904:     $what=time.':'.$what;
1.620     albertel 1905:     unless ($env{'request.course.id'}) { return ''; }
                   1906:     $coursedombuf{$env{'request.course.id'}}=
                   1907:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   1908:     $coursenumbuf{$env{'request.course.id'}}=
                   1909:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   1910:     $coursehombuf{$env{'request.course.id'}}=
                   1911:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   1912:     $coursedescrbuf{$env{'request.course.id'}}=
                   1913:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   1914:     $courseinstcodebuf{$env{'request.course.id'}}=
                   1915:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   1916:     $courseownerbuf{$env{'request.course.id'}}=
                   1917:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  1918:     $coursetypebuf{$env{'request.course.id'}}=
                   1919:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 1920:     if (defined $courselogs{$env{'request.course.id'}}) {
                   1921: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      1922:     } else {
1.620     albertel 1923: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      1924:     }
1.620     albertel 1925:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      1926: 	&flushcourselogs();
                   1927:     }
1.158     www      1928: }
                   1929: 
                   1930: sub courseacclog {
                   1931:     my $fnsymb=shift;
1.620     albertel 1932:     unless ($env{'request.course.id'}) { return ''; }
                   1933:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 1934:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      1935:         $what.=':POST';
1.583     matthew  1936:         # FIXME: Probably ought to escape things....
1.800     albertel 1937: 	foreach my $key (keys(%env)) {
                   1938:             if ($key=~/^form\.(.*)/) {
                   1939: 		$what.=':'.$1.'='.$env{$key};
1.158     www      1940:             }
1.191     harris41 1941:         }
1.583     matthew  1942:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   1943:         # FIXME: We should not be depending on a form parameter that someone
                   1944:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 1945:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  1946:             $what.= ':POST';
                   1947:             # FIXME: Probably ought to escape things....
                   1948:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   1949:                                  'crsdiscuss') {
1.620     albertel 1950:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  1951:             }
                   1952:         }
1.158     www      1953:     }
                   1954:     &courselog($what);
1.149     www      1955: }
                   1956: 
1.185     www      1957: sub countacc {
                   1958:     my $url=&declutter(shift);
1.458     matthew  1959:     return if (! defined($url) || $url eq '');
1.620     albertel 1960:     unless ($env{'request.course.id'}) { return ''; }
                   1961:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      1962:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  1963:     $accesshash{$key}++;
1.185     www      1964: }
1.349     www      1965: 
1.361     www      1966: sub linklog {
                   1967:     my ($from,$to)=@_;
                   1968:     $from=&declutter($from);
                   1969:     $to=&declutter($to);
                   1970:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   1971:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   1972: }
                   1973:   
1.349     www      1974: sub userrolelog {
                   1975:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  1976:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  1977:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  1978:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   1979:         ($trole=~/^ta/)) {
1.350     www      1980:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   1981:        $userrolehash
                   1982:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      1983:                     =$tend.':'.$tstart;
1.662     raeburn  1984:     }
                   1985:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   1986:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   1987:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   1988:         ($trole=~/^sc/)) {
                   1989:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   1990:        $domainrolehash
                   1991:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   1992:                     = $tend.':'.$tstart;
                   1993:     }
1.351     www      1994: }
                   1995: 
                   1996: sub get_course_adv_roles {
                   1997:     my $cid=shift;
1.620     albertel 1998:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      1999:     my %coursehash=&coursedescription($cid);
1.470     www      2000:     my %nothide=();
1.800     albertel 2001:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2002: 	$nothide{join(':',split(/[\@\:]/,$user))}=1;
1.470     www      2003:     }
1.351     www      2004:     my %returnhash=();
                   2005:     my %dumphash=
                   2006:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   2007:     my $now=time;
1.800     albertel 2008:     foreach my $entry (keys %dumphash) {
                   2009: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      2010:         if (($tstart) && ($tstart<0)) { next; }
                   2011:         if (($tend) && ($tend<$now)) { next; }
                   2012:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 2013:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 2014: 	if ($username eq '' || $domain eq '') { next; }
1.470     www      2015: 	if ((&privileged($username,$domain)) && 
                   2016: 	    (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 2017: 	if ($role eq 'cr') { next; }
1.351     www      2018:         my $key=&plaintext($role);
                   2019:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
                   2020:         if ($returnhash{$key}) {
                   2021: 	    $returnhash{$key}.=','.$username.':'.$domain;
                   2022:         } else {
                   2023:             $returnhash{$key}=$username.':'.$domain;
                   2024:         }
1.400     www      2025:      }
                   2026:     return %returnhash;
                   2027: }
                   2028: 
                   2029: sub get_my_roles {
                   2030:     my ($uname,$udom)=@_;
1.620     albertel 2031:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   2032:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.400     www      2033:     my %dumphash=
                   2034:             &dump('nohist_userroles',$udom,$uname);
                   2035:     my %returnhash=();
                   2036:     my $now=time;
1.800     albertel 2037:     foreach my $entry (keys(%dumphash)) {
                   2038: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.400     www      2039:         if (($tstart) && ($tstart<0)) { next; }
                   2040:         if (($tend) && ($tend<$now)) { next; }
                   2041:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 2042:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.400     www      2043: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
1.373     www      2044:      }
                   2045:     return %returnhash;
1.399     www      2046: }
                   2047: 
                   2048: # ----------------------------------------------------- Frontpage Announcements
                   2049: #
                   2050: #
                   2051: 
                   2052: sub postannounce {
                   2053:     my ($server,$text)=@_;
                   2054:     unless (&allowed('psa',$hostdom{$server})) { return 'refused'; }
                   2055:     unless ($text=~/\w/) { $text=''; }
                   2056:     return &reply('setannounce:'.&escape($text),$server);
                   2057: }
                   2058: 
                   2059: sub getannounce {
1.448     albertel 2060: 
                   2061:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      2062: 	my $announcement='';
1.800     albertel 2063: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 2064: 	close($fh);
1.399     www      2065: 	if ($announcement=~/\w/) { 
                   2066: 	    return 
                   2067:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 2068:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      2069: 	} else {
                   2070: 	    return '';
                   2071: 	}
                   2072:     } else {
                   2073: 	return '';
                   2074:     }
1.351     www      2075: }
1.353     www      2076: 
                   2077: # ---------------------------------------------------------- Course ID routines
                   2078: # Deal with domain's nohist_courseid.db files
                   2079: #
                   2080: 
                   2081: sub courseidput {
                   2082:     my ($domain,$what,$coursehome)=@_;
                   2083:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   2084: }
                   2085: 
                   2086: sub courseiddump {
1.791     raeburn  2087:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok)=@_;
1.353     www      2088:     my %returnhash=();
1.355     www      2089:     unless ($domfilter) { $domfilter=''; }
1.353     www      2090:     foreach my $tryserver (keys %libserv) {
1.511     raeburn  2091:         if ( ($hostidflag == 1 && grep/^$tryserver$/,@{$hostidref}) || (!defined($hostidflag)) ) {
1.506     raeburn  2092: 	    if ((!$domfilter) || ($hostdom{$tryserver} eq $domfilter)) {
1.800     albertel 2093: 	        foreach my $line (
1.506     raeburn  2094:                  split(/\&/,&reply('courseiddump:'.$hostdom{$tryserver}.':'.
1.571     raeburn  2095: 			       $sincefilter.':'.&escape($descfilter).':'.
1.791     raeburn  2096:                                &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter).':'.&escape($typefilter).':'.&escape($regexp_ok),
1.354     www      2097:                                $tryserver))) {
1.800     albertel 2098: 		    my ($key,$value)=split(/\=/,$line,2);
1.506     raeburn  2099:                     if (($key) && ($value)) {
1.516     raeburn  2100: 		        $returnhash{&unescape($key)}=$value;
1.506     raeburn  2101:                     }
1.353     www      2102:                 }
                   2103:             }
                   2104:         }
                   2105:     }
                   2106:     return %returnhash;
                   2107: }
                   2108: 
1.658     raeburn  2109: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  2110: 
                   2111: sub dcmailput {
1.685     raeburn  2112:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  2113:     my $status = &Apache::lonnet::critical(
1.740     www      2114:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   2115:        &escape($message),$server);
1.662     raeburn  2116:     return $status;
                   2117: }
                   2118: 
1.658     raeburn  2119: sub dcmaildump {
                   2120:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  2121:     my %returnhash=();
                   2122:     if (exists($domain_primary{$dom})) {
                   2123:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   2124:                                                          &escape($enddate).':';
                   2125: 	my @esc_senders=map { &escape($_)} @$senders;
                   2126: 	$cmd.=&escape(join('&',@esc_senders));
1.800     albertel 2127: 	foreach my $line (split(/\&/,&reply($cmd,$domain_primary{$dom}))) {
                   2128:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  2129:             if (($key) && ($value)) {
                   2130:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  2131:             }
                   2132:         }
                   2133:     }
                   2134:     return %returnhash;
                   2135: }
1.662     raeburn  2136: # ---------------------------------------------------------- Domain roles
                   2137: 
                   2138: sub get_domain_roles {
                   2139:     my ($dom,$roles,$startdate,$enddate)=@_;
                   2140:     if (undef($startdate) || $startdate eq '') {
                   2141:         $startdate = '.';
                   2142:     }
                   2143:     if (undef($enddate) || $enddate eq '') {
                   2144:         $enddate = '.';
                   2145:     }
                   2146:     my $rolelist = join(':',@{$roles});
                   2147:     my %personnel = ();
                   2148:     foreach my $tryserver (keys(%libserv)) {
                   2149:         if ($hostdom{$tryserver} eq $dom) {
                   2150:             %{$personnel{$tryserver}}=();
1.800     albertel 2151:             foreach my $line (
1.662     raeburn  2152:                 split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   2153:                    &escape($startdate).':'.&escape($enddate).':'.
                   2154:                    &escape($rolelist), $tryserver))) {
1.800     albertel 2155:                 my ($key,$value) = split(/\=/,$line,2);
1.662     raeburn  2156:                 if (($key) && ($value)) {
                   2157:                     $personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   2158:                 }
                   2159:             }
                   2160:         }
                   2161:     }
                   2162:     return %personnel;
                   2163: }
1.658     raeburn  2164: 
1.149     www      2165: # ----------------------------------------------------------- Check out an item
                   2166: 
1.504     albertel 2167: sub get_first_access {
                   2168:     my ($type,$argsymb)=@_;
1.790     albertel 2169:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2170:     if ($argsymb) { $symb=$argsymb; }
                   2171:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2172:     if ($type eq 'map') {
                   2173: 	$res=&symbread($map);
                   2174:     } else {
                   2175: 	$res=$symb;
                   2176:     }
                   2177:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   2178:     return $times{"$courseid\0$res"};
1.504     albertel 2179: }
                   2180: 
                   2181: sub set_first_access {
                   2182:     my ($type)=@_;
1.790     albertel 2183:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2184:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2185:     if ($type eq 'map') {
                   2186: 	$res=&symbread($map);
                   2187:     } else {
                   2188: 	$res=$symb;
                   2189:     }
                   2190:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 2191:     if (!$firstaccess) {
1.588     albertel 2192: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 2193:     }
                   2194:     return 'already_set';
1.504     albertel 2195: }
                   2196: 
1.149     www      2197: sub checkout {
                   2198:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   2199:     my $now=time;
                   2200:     my $lonhost=$perlvar{'lonHostID'};
                   2201:     my $infostr=&escape(
1.234     www      2202:                  'CHECKOUTTOKEN&'.
1.149     www      2203:                  $tuname.'&'.
                   2204:                  $tudom.'&'.
                   2205:                  $tcrsid.'&'.
                   2206:                  $symb.'&'.
                   2207: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   2208:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      2209:     if ($token=~/^error\:/) { 
1.672     albertel 2210:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2211:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2212:                  "</font>");
                   2213:         return ''; 
                   2214:     }
                   2215: 
1.149     www      2216:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   2217:     $token=~tr/a-z/A-Z/;
                   2218: 
1.153     www      2219:     my %infohash=('resource.0.outtoken' => $token,
                   2220:                   'resource.0.checkouttime' => $now,
                   2221:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      2222: 
                   2223:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2224:        return '';
1.151     www      2225:     } else {
1.672     albertel 2226:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2227:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2228:                  "</font>");
1.149     www      2229:     }    
                   2230: 
                   2231:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2232:                          &escape('Checkout '.$infostr.' - '.
                   2233:                                                  $token)) ne 'ok') {
                   2234: 	return '';
1.151     www      2235:     } else {
1.672     albertel 2236:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2237:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2238:                  "</font>");
1.149     www      2239:     }
1.151     www      2240:     return $token;
1.149     www      2241: }
                   2242: 
                   2243: # ------------------------------------------------------------ Check in an item
                   2244: 
                   2245: sub checkin {
                   2246:     my $token=shift;
1.150     www      2247:     my $now=time;
                   2248:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   2249:     $lonhost=~tr/A-Z/a-z/;
1.595     albertel 2250:     my $dtoken=$ta.'_'.$hostname{$lonhost}.'_'.$tb;
1.150     www      2251:     $dtoken=~s/\W/\_/g;
1.234     www      2252:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      2253:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   2254: 
1.154     www      2255:     unless (($tuname) && ($tudom)) {
                   2256:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   2257:         return '';
                   2258:     }
                   2259:     
                   2260:     unless (&allowed('mgr',$tcrsid)) {
                   2261:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 2262:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      2263:         return '';
                   2264:     }
                   2265: 
1.153     www      2266:     my %infohash=('resource.0.intoken' => $token,
                   2267:                   'resource.0.checkintime' => $now,
                   2268:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      2269: 
                   2270:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2271:        return '';
                   2272:     }    
                   2273: 
                   2274:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2275:                          &escape('Checkin - '.$token)) ne 'ok') {
                   2276: 	return '';
                   2277:     }
                   2278: 
                   2279:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      2280: }
                   2281: 
                   2282: # --------------------------------------------- Set Expire Date for Spreadsheet
                   2283: 
                   2284: sub expirespread {
                   2285:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 2286:     my $cid=$env{'request.course.id'}; 
1.110     www      2287:     if ($cid) {
                   2288:        my $now=time;
                   2289:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 2290:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   2291:                             $env{'course.'.$cid.'.num'}.
1.110     www      2292: 	        	    ':nohist_expirationdates:'.
                   2293:                             &escape($key).'='.$now,
1.620     albertel 2294:                             $env{'course.'.$cid.'.home'})
1.110     www      2295:     }
                   2296:     return 'ok';
1.14      www      2297: }
                   2298: 
1.109     www      2299: # ----------------------------------------------------- Devalidate Spreadsheets
                   2300: 
                   2301: sub devalidate {
1.325     www      2302:     my ($symb,$uname,$udom)=@_;
1.620     albertel 2303:     my $cid=$env{'request.course.id'}; 
1.109     www      2304:     if ($cid) {
1.391     matthew  2305:         # delete the stored spreadsheets for
                   2306:         # - the student level sheet of this user in course's homespace
                   2307:         # - the assessment level sheet for this resource 
                   2308:         #   for this user in user's homespace
1.553     albertel 2309: 	# - current conditional state info
1.325     www      2310: 	my $key=$uname.':'.$udom.':';
1.109     www      2311:         my $status=
1.299     matthew  2312: 	    &del('nohist_calculatedsheets',
1.391     matthew  2313: 		 [$key.'studentcalc:'],
1.620     albertel 2314: 		 $env{'course.'.$cid.'.domain'},
                   2315: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 2316: 		.' '.
                   2317: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  2318: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      2319:         unless ($status eq 'ok ok') {
                   2320:            &logthis('Could not devalidate spreadsheet '.
1.325     www      2321:                     $uname.' at '.$udom.' for '.
1.109     www      2322: 		    $symb.': '.$status);
1.133     albertel 2323:         }
1.553     albertel 2324: 	&delenv('user.state.'.$cid);
1.109     www      2325:     }
                   2326: }
                   2327: 
1.265     albertel 2328: sub get_scalar {
                   2329:     my ($string,$end) = @_;
                   2330:     my $value;
                   2331:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   2332: 	$value = $1;
                   2333:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   2334: 	$value = $1;
                   2335:     }
                   2336:     return &unescape($value);
                   2337: }
                   2338: 
                   2339: sub array2str {
                   2340:   my (@array) = @_;
                   2341:   my $result=&arrayref2str(\@array);
                   2342:   $result=~s/^__ARRAY_REF__//;
                   2343:   $result=~s/__END_ARRAY_REF__$//;
                   2344:   return $result;
                   2345: }
                   2346: 
1.204     albertel 2347: sub arrayref2str {
                   2348:   my ($arrayref) = @_;
1.265     albertel 2349:   my $result='__ARRAY_REF__';
1.204     albertel 2350:   foreach my $elem (@$arrayref) {
1.265     albertel 2351:     if(ref($elem) eq 'ARRAY') {
                   2352:       $result.=&arrayref2str($elem).'&';
                   2353:     } elsif(ref($elem) eq 'HASH') {
                   2354:       $result.=&hashref2str($elem).'&';
                   2355:     } elsif(ref($elem)) {
                   2356:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 2357:     } else {
                   2358:       $result.=&escape($elem).'&';
                   2359:     }
                   2360:   }
                   2361:   $result=~s/\&$//;
1.265     albertel 2362:   $result .= '__END_ARRAY_REF__';
1.204     albertel 2363:   return $result;
                   2364: }
                   2365: 
1.168     albertel 2366: sub hash2str {
1.204     albertel 2367:   my (%hash) = @_;
                   2368:   my $result=&hashref2str(\%hash);
1.265     albertel 2369:   $result=~s/^__HASH_REF__//;
                   2370:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 2371:   return $result;
                   2372: }
                   2373: 
                   2374: sub hashref2str {
                   2375:   my ($hashref)=@_;
1.265     albertel 2376:   my $result='__HASH_REF__';
1.800     albertel 2377:   foreach my $key (sort(keys(%$hashref))) {
                   2378:     if (ref($key) eq 'ARRAY') {
                   2379:       $result.=&arrayref2str($key).'=';
                   2380:     } elsif (ref($key) eq 'HASH') {
                   2381:       $result.=&hashref2str($key).'=';
                   2382:     } elsif (ref($key)) {
1.265     albertel 2383:       $result.='=';
1.800     albertel 2384:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 2385:     } else {
1.800     albertel 2386: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 2387:     }
                   2388: 
1.800     albertel 2389:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   2390:       $result.=&arrayref2str($hashref->{$key}).'&';
                   2391:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   2392:       $result.=&hashref2str($hashref->{$key}).'&';
                   2393:     } elsif(ref($hashref->{$key})) {
1.265     albertel 2394:        $result.='&';
1.800     albertel 2395:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 2396:     } else {
1.800     albertel 2397:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 2398:     }
                   2399:   }
1.168     albertel 2400:   $result=~s/\&$//;
1.265     albertel 2401:   $result .= '__END_HASH_REF__';
1.168     albertel 2402:   return $result;
                   2403: }
                   2404: 
                   2405: sub str2hash {
1.265     albertel 2406:     my ($string)=@_;
                   2407:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   2408:     return %$hash;
                   2409: }
                   2410: 
                   2411: sub str2hashref {
1.168     albertel 2412:   my ($string) = @_;
1.265     albertel 2413: 
                   2414:   my %hash;
                   2415: 
                   2416:   if($string !~ /^__HASH_REF__/) {
                   2417:       if (! ($string eq '' || !defined($string))) {
                   2418: 	  $hash{'error'}='Not hash reference';
                   2419:       }
                   2420:       return (\%hash, $string);
                   2421:   }
                   2422: 
                   2423:   $string =~ s/^__HASH_REF__//;
                   2424: 
                   2425:   while($string !~ /^__END_HASH_REF__/) {
                   2426:       #key
                   2427:       my $key='';
                   2428:       if($string =~ /^__HASH_REF__/) {
                   2429:           ($key, $string)=&str2hashref($string);
                   2430:           if(defined($key->{'error'})) {
                   2431:               $hash{'error'}='Bad data';
                   2432:               return (\%hash, $string);
                   2433:           }
                   2434:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2435:           ($key, $string)=&str2arrayref($string);
                   2436:           if($key->[0] eq 'Array reference error') {
                   2437:               $hash{'error'}='Bad data';
                   2438:               return (\%hash, $string);
                   2439:           }
                   2440:       } else {
                   2441:           $string =~ s/^(.*?)=//;
1.267     albertel 2442: 	  $key=&unescape($1);
1.265     albertel 2443:       }
                   2444:       $string =~ s/^=//;
                   2445: 
                   2446:       #value
                   2447:       my $value='';
                   2448:       if($string =~ /^__HASH_REF__/) {
                   2449:           ($value, $string)=&str2hashref($string);
                   2450:           if(defined($value->{'error'})) {
                   2451:               $hash{'error'}='Bad data';
                   2452:               return (\%hash, $string);
                   2453:           }
                   2454:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2455:           ($value, $string)=&str2arrayref($string);
                   2456:           if($value->[0] eq 'Array reference error') {
                   2457:               $hash{'error'}='Bad data';
                   2458:               return (\%hash, $string);
                   2459:           }
                   2460:       } else {
                   2461: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   2462:       }
                   2463:       $string =~ s/^&//;
                   2464: 
                   2465:       $hash{$key}=$value;
1.204     albertel 2466:   }
1.265     albertel 2467: 
                   2468:   $string =~ s/^__END_HASH_REF__//;
                   2469: 
                   2470:   return (\%hash, $string);
1.204     albertel 2471: }
                   2472: 
                   2473: sub str2array {
1.265     albertel 2474:     my ($string)=@_;
                   2475:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   2476:     return @$array;
                   2477: }
                   2478: 
                   2479: sub str2arrayref {
1.204     albertel 2480:   my ($string) = @_;
1.265     albertel 2481:   my @array;
                   2482: 
                   2483:   if($string !~ /^__ARRAY_REF__/) {
                   2484:       if (! ($string eq '' || !defined($string))) {
                   2485: 	  $array[0]='Array reference error';
                   2486:       }
                   2487:       return (\@array, $string);
                   2488:   }
                   2489: 
                   2490:   $string =~ s/^__ARRAY_REF__//;
                   2491: 
                   2492:   while($string !~ /^__END_ARRAY_REF__/) {
                   2493:       my $value='';
                   2494:       if($string =~ /^__HASH_REF__/) {
                   2495:           ($value, $string)=&str2hashref($string);
                   2496:           if(defined($value->{'error'})) {
                   2497:               $array[0] ='Array reference error';
                   2498:               return (\@array, $string);
                   2499:           }
                   2500:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2501:           ($value, $string)=&str2arrayref($string);
                   2502:           if($value->[0] eq 'Array reference error') {
                   2503:               $array[0] ='Array reference error';
                   2504:               return (\@array, $string);
                   2505:           }
                   2506:       } else {
                   2507: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   2508:       }
                   2509:       $string =~ s/^&//;
                   2510: 
                   2511:       push(@array, $value);
1.191     harris41 2512:   }
1.265     albertel 2513: 
                   2514:   $string =~ s/^__END_ARRAY_REF__//;
                   2515: 
                   2516:   return (\@array, $string);
1.168     albertel 2517: }
                   2518: 
1.167     albertel 2519: # -------------------------------------------------------------------Temp Store
                   2520: 
1.168     albertel 2521: sub tmpreset {
                   2522:   my ($symb,$namespace,$domain,$stuname) = @_;
                   2523:   if (!$symb) {
                   2524:     $symb=&symbread();
1.620     albertel 2525:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2526:   }
                   2527:   $symb=escape($symb);
                   2528: 
1.620     albertel 2529:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 2530:   $namespace=~s/\//\_/g;
                   2531:   $namespace=~s/\W//g;
                   2532: 
1.620     albertel 2533:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2534:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2535:   if ($domain eq 'public' && $stuname eq 'public') {
                   2536:       $stuname=$ENV{'REMOTE_ADDR'};
                   2537:   }
1.168     albertel 2538:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2539:   my %hash;
                   2540:   if (tie(%hash,'GDBM_File',
                   2541: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2542: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2543:     foreach my $key (keys %hash) {
1.180     albertel 2544:       if ($key=~ /:$symb/) {
1.168     albertel 2545: 	delete($hash{$key});
                   2546:       }
                   2547:     }
                   2548:   }
                   2549: }
                   2550: 
1.167     albertel 2551: sub tmpstore {
1.168     albertel 2552:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2553: 
                   2554:   if (!$symb) {
                   2555:     $symb=&symbread();
1.620     albertel 2556:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2557:   }
                   2558:   $symb=escape($symb);
                   2559: 
                   2560:   if (!$namespace) {
                   2561:     # I don't think we would ever want to store this for a course.
                   2562:     # it seems this will only be used if we don't have a course.
1.620     albertel 2563:     #$namespace=$env{'request.course.id'};
1.168     albertel 2564:     #if (!$namespace) {
1.620     albertel 2565:       $namespace=$env{'request.state'};
1.168     albertel 2566:     #}
                   2567:   }
                   2568:   $namespace=~s/\//\_/g;
                   2569:   $namespace=~s/\W//g;
1.620     albertel 2570:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2571:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2572:   if ($domain eq 'public' && $stuname eq 'public') {
                   2573:       $stuname=$ENV{'REMOTE_ADDR'};
                   2574:   }
1.168     albertel 2575:   my $now=time;
                   2576:   my %hash;
                   2577:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2578:   if (tie(%hash,'GDBM_File',
                   2579: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2580: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2581:     $hash{"version:$symb"}++;
                   2582:     my $version=$hash{"version:$symb"};
                   2583:     my $allkeys=''; 
                   2584:     foreach my $key (keys(%$storehash)) {
                   2585:       $allkeys.=$key.':';
1.591     albertel 2586:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 2587:     }
                   2588:     $hash{"$version:$symb:timestamp"}=$now;
                   2589:     $allkeys.='timestamp';
                   2590:     $hash{"$version:keys:$symb"}=$allkeys;
                   2591:     if (untie(%hash)) {
                   2592:       return 'ok';
                   2593:     } else {
                   2594:       return "error:$!";
                   2595:     }
                   2596:   } else {
                   2597:     return "error:$!";
                   2598:   }
                   2599: }
1.167     albertel 2600: 
1.168     albertel 2601: # -----------------------------------------------------------------Temp Restore
1.167     albertel 2602: 
1.168     albertel 2603: sub tmprestore {
                   2604:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 2605: 
1.168     albertel 2606:   if (!$symb) {
                   2607:     $symb=&symbread();
1.620     albertel 2608:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2609:   }
                   2610:   $symb=escape($symb);
                   2611: 
1.620     albertel 2612:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 2613: 
1.620     albertel 2614:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2615:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2616:   if ($domain eq 'public' && $stuname eq 'public') {
                   2617:       $stuname=$ENV{'REMOTE_ADDR'};
                   2618:   }
1.168     albertel 2619:   my %returnhash;
                   2620:   $namespace=~s/\//\_/g;
                   2621:   $namespace=~s/\W//g;
                   2622:   my %hash;
                   2623:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2624:   if (tie(%hash,'GDBM_File',
                   2625: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2626: 	  &GDBM_READER(),0640)) {
1.168     albertel 2627:     my $version=$hash{"version:$symb"};
                   2628:     $returnhash{'version'}=$version;
                   2629:     my $scope;
                   2630:     for ($scope=1;$scope<=$version;$scope++) {
                   2631:       my $vkeys=$hash{"$scope:keys:$symb"};
                   2632:       my @keys=split(/:/,$vkeys);
                   2633:       my $key;
                   2634:       $returnhash{"$scope:keys"}=$vkeys;
                   2635:       foreach $key (@keys) {
1.591     albertel 2636: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   2637: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 2638:       }
                   2639:     }
1.168     albertel 2640:     if (!(untie(%hash))) {
                   2641:       return "error:$!";
                   2642:     }
                   2643:   } else {
                   2644:     return "error:$!";
                   2645:   }
                   2646:   return %returnhash;
1.167     albertel 2647: }
                   2648: 
1.9       www      2649: # ----------------------------------------------------------------------- Store
                   2650: 
                   2651: sub store {
1.124     www      2652:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2653:     my $home='';
                   2654: 
1.168     albertel 2655:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2656: 
1.213     www      2657:     $symb=&symbclean($symb);
1.122     albertel 2658:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2659: 
1.620     albertel 2660:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2661:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2662: 
                   2663:     &devalidate($symb,$stuname,$domain);
1.109     www      2664: 
                   2665:     $symb=escape($symb);
1.187     www      2666:     if (!$namespace) { 
1.620     albertel 2667:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2668:           return ''; 
                   2669:        } 
                   2670:     }
1.620     albertel 2671:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2672: 
                   2673:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2674:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   2675: 
1.12      www      2676:     my $namevalue='';
1.800     albertel 2677:     foreach my $key (keys(%$storehash)) {
                   2678:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 2679:     }
1.12      www      2680:     $namevalue=~s/\&$//;
1.187     www      2681:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      2682:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      2683: }
                   2684: 
1.47      www      2685: # -------------------------------------------------------------- Critical Store
                   2686: 
                   2687: sub cstore {
1.124     www      2688:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2689:     my $home='';
                   2690: 
1.168     albertel 2691:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2692: 
1.213     www      2693:     $symb=&symbclean($symb);
1.122     albertel 2694:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2695: 
1.620     albertel 2696:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2697:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2698: 
                   2699:     &devalidate($symb,$stuname,$domain);
1.109     www      2700: 
                   2701:     $symb=escape($symb);
1.187     www      2702:     if (!$namespace) { 
1.620     albertel 2703:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2704:           return ''; 
                   2705:        } 
                   2706:     }
1.620     albertel 2707:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2708: 
                   2709:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2710:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 2711: 
1.47      www      2712:     my $namevalue='';
1.800     albertel 2713:     foreach my $key (keys(%$storehash)) {
                   2714:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 2715:     }
1.47      www      2716:     $namevalue=~s/\&$//;
1.187     www      2717:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      2718:     return critical
                   2719:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      2720: }
                   2721: 
1.9       www      2722: # --------------------------------------------------------------------- Restore
                   2723: 
                   2724: sub restore {
1.124     www      2725:     my ($symb,$namespace,$domain,$stuname) = @_;
                   2726:     my $home='';
                   2727: 
1.168     albertel 2728:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2729: 
1.122     albertel 2730:     if (!$symb) {
                   2731:       unless ($symb=escape(&symbread())) { return ''; }
                   2732:     } else {
1.213     www      2733:       $symb=&escape(&symbclean($symb));
1.122     albertel 2734:     }
1.188     www      2735:     if (!$namespace) { 
1.620     albertel 2736:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      2737:           return ''; 
                   2738:        } 
                   2739:     }
1.620     albertel 2740:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2741:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   2742:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 2743:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   2744: 
1.12      www      2745:     my %returnhash=();
1.800     albertel 2746:     foreach my $line (split(/\&/,$answer)) {
                   2747: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 2748:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 2749:     }
1.75      www      2750:     my $version;
                   2751:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 2752:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   2753:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 2754:        }
1.75      www      2755:     }
1.13      www      2756:     return %returnhash;
1.34      www      2757: }
                   2758: 
                   2759: # ---------------------------------------------------------- Course Description
                   2760: 
                   2761: sub coursedescription {
1.731     albertel 2762:     my ($courseid,$args)=@_;
1.34      www      2763:     $courseid=~s/^\///;
1.49      www      2764:     $courseid=~s/\_/\//g;
1.34      www      2765:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 2766:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 2767:     my $normalid=$cdomain.'_'.$cnum;
                   2768:     # need to always cache even if we get errors otherwise we keep 
                   2769:     # trying and trying and trying to get the course description.
                   2770:     my %envhash=();
                   2771:     my %returnhash=();
1.731     albertel 2772:     
                   2773:     my $expiretime=600;
                   2774:     if ($env{'request.course.id'} eq $normalid) {
                   2775: 	$expiretime=120;
                   2776:     }
                   2777: 
                   2778:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   2779:     if (!$args->{'freshen_cache'}
                   2780: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   2781: 	foreach my $key (keys(%env)) {
                   2782: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   2783: 	    my ($setting) = $1;
                   2784: 	    $returnhash{$setting} = $env{$key};
                   2785: 	}
                   2786: 	return %returnhash;
                   2787:     }
                   2788: 
                   2789:     # get the data agin
                   2790:     if (!$args->{'one_time'}) {
                   2791: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   2792:     }
1.811     albertel 2793: 
1.34      www      2794:     if ($chome ne 'no_host') {
1.302     albertel 2795:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 2796:        if (!exists($returnhash{'con_lost'})) {
                   2797:            $returnhash{'home'}= $chome;
                   2798: 	   $returnhash{'domain'} = $cdomain;
                   2799: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  2800:            if (!defined($returnhash{'type'})) {
                   2801:                $returnhash{'type'} = 'Course';
                   2802:            }
1.130     albertel 2803:            while (my ($name,$value) = each %returnhash) {
1.53      www      2804:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 2805:            }
1.270     www      2806:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      2807:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 2808: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      2809:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   2810:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   2811:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      2812:        }
                   2813:     }
1.731     albertel 2814:     if (!$args->{'one_time'}) {
                   2815: 	&appenv(%envhash);
                   2816:     }
1.302     albertel 2817:     return %returnhash;
1.461     www      2818: }
                   2819: 
                   2820: # -------------------------------------------------See if a user is privileged
                   2821: 
                   2822: sub privileged {
                   2823:     my ($username,$domain)=@_;
                   2824:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   2825: 			&homeserver($username,$domain));
                   2826:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   2827:     my $now=time;
                   2828:     if ($rolesdump ne '') {
1.800     albertel 2829:         foreach my $entry (split(/&/,$rolesdump)) {
                   2830: 	    if ($entry!~/^rolesdef_/) {
                   2831: 		my ($area,$role)=split(/=/,$entry);
1.461     www      2832: 		$area=~s/\_\w\w$//;
                   2833: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   2834: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   2835: 		    my $active=1;
                   2836: 		    if ($tend) {
                   2837: 			if ($tend<$now) { $active=0; }
                   2838: 		    }
                   2839: 		    if ($tstart) {
                   2840: 			if ($tstart>$now) { $active=0; }
                   2841: 		    }
                   2842: 		    if ($active) { return 1; }
                   2843: 		}
                   2844: 	    }
                   2845: 	}
                   2846:     }
                   2847:     return 0;
1.9       www      2848: }
1.1       albertel 2849: 
1.103     harris41 2850: # -------------------------------------------------------- Get user privileges
1.11      www      2851: 
                   2852: sub rolesinit {
                   2853:     my ($domain,$username,$authhost)=@_;
                   2854:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12      www      2855:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11      www      2856:     my %allroles=();
1.678     raeburn  2857:     my %allgroups=();   
1.11      www      2858:     my $now=time;
1.743     albertel 2859:     my %userroles = ('user.login.time' => $now);
1.678     raeburn  2860:     my $group_privs;
1.11      www      2861: 
                   2862:     if ($rolesdump ne '') {
1.800     albertel 2863:         foreach my $entry (split(/&/,$rolesdump)) {
                   2864: 	  if ($entry!~/^rolesdef_/) {
                   2865:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 2866: 	    $area=~s/\_\w\w$//;
1.678     raeburn  2867:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 2868: 	    if ($role=~/^cr/) { 
1.807     albertel 2869: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   2870: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 2871: 		    ($tend,$tstart)=split('_',$trest);
                   2872: 		} else {
                   2873: 		    $trole=$role;
                   2874: 		}
1.678     raeburn  2875:             } elsif ($role =~ m|^gr/|) {
                   2876:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   2877:                 ($trole,$group_privs) = split(/\//,$trole);
                   2878:                 $group_privs = &unescape($group_privs);
1.587     albertel 2879: 	    } else {
                   2880: 		($trole,$tend,$tstart)=split(/_/,$role);
                   2881: 	    }
1.743     albertel 2882: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   2883: 					 $username);
                   2884: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  2885:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   2886:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      2887:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 2888: 		my $spec=$trole.'.'.$area;
                   2889: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   2890: 		if ($trole =~ /^cr\//) {
1.567     raeburn  2891:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  2892:                 } elsif ($trole eq 'gr') {
                   2893:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 2894: 		} else {
1.567     raeburn  2895:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 2896: 		}
1.12      www      2897:             }
1.662     raeburn  2898:           }
1.191     harris41 2899:         }
1.743     albertel 2900:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   2901:         $userroles{'user.adv'}    = $adv;
                   2902: 	$userroles{'user.author'} = $author;
1.620     albertel 2903:         $env{'user.adv'}=$adv;
1.11      www      2904:     }
1.743     albertel 2905:     return \%userroles;  
1.11      www      2906: }
                   2907: 
1.567     raeburn  2908: sub set_arearole {
                   2909:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   2910: # log the associated role with the area
                   2911:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 2912:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  2913: }
                   2914: 
                   2915: sub custom_roleprivs {
                   2916:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   2917:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   2918:     my $homsvr=homeserver($rauthor,$rdomain);
                   2919:     if ($hostname{$homsvr} ne '') {
                   2920:         my ($rdummy,$roledef)=
                   2921:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   2922:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   2923:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   2924:             if (defined($syspriv)) {
                   2925:                 $$allroles{'cm./'}.=':'.$syspriv;
                   2926:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   2927:             }
                   2928:             if ($tdomain ne '') {
                   2929:                 if (defined($dompriv)) {
                   2930:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   2931:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   2932:                 }
                   2933:                 if (($trest ne '') && (defined($coursepriv))) {
                   2934:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   2935:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   2936:                 }
                   2937:             }
                   2938:         }
                   2939:     }
                   2940: }
                   2941: 
1.678     raeburn  2942: sub group_roleprivs {
                   2943:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   2944:     my $access = 1;
                   2945:     my $now = time;
                   2946:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   2947:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   2948:     if ($access) {
1.811     albertel 2949:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  2950:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   2951:     }
                   2952: }
1.567     raeburn  2953: 
                   2954: sub standard_roleprivs {
                   2955:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   2956:     if (defined($pr{$trole.':s'})) {
                   2957:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   2958:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   2959:     }
                   2960:     if ($tdomain ne '') {
                   2961:         if (defined($pr{$trole.':d'})) {
                   2962:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   2963:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   2964:         }
                   2965:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   2966:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   2967:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   2968:         }
                   2969:     }
                   2970: }
                   2971: 
                   2972: sub set_userprivs {
1.678     raeburn  2973:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  2974:     my $author=0;
                   2975:     my $adv=0;
1.678     raeburn  2976:     my %grouproles = ();
                   2977:     if (keys(%{$allgroups}) > 0) {
                   2978:         foreach my $role (keys %{$allroles}) {
1.681     raeburn  2979:             my ($trole,$area,$sec,$extendedarea);
1.811     albertel 2980:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)-) {
1.678     raeburn  2981:                 $trole = $1;
                   2982:                 $area = $2;
1.681     raeburn  2983:                 $sec = $3;
                   2984:                 $extendedarea = $area.$sec;
                   2985:                 if (exists($$allgroups{$area})) {
                   2986:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   2987:                         my $spec = $trole.'.'.$extendedarea;
                   2988:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   2989:                                                 $$allgroups{$area}{$group};
1.678     raeburn  2990:                     }
                   2991:                 }
                   2992:             }
                   2993:         }
                   2994:     }
1.800     albertel 2995:     foreach my $group (keys(%grouproles)) {
                   2996:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  2997:     }
1.800     albertel 2998:     foreach my $role (keys(%{$allroles})) {
                   2999:         my %thesepriv;
                   3000:         if (($role=~/^au/) || ($role=~/^ca/)) { $author=1; }
                   3001:         foreach my $item (split(/:/,$$allroles{$role})) {
                   3002:             if ($item ne '') {
                   3003:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  3004:                 if ($restrictions eq '') {
                   3005:                     $thesepriv{$privilege}='F';
                   3006:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   3007:                     $thesepriv{$privilege}.=$restrictions;
                   3008:                 }
                   3009:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   3010:             }
                   3011:         }
                   3012:         my $thesestr='';
1.800     albertel 3013:         foreach my $priv (keys(%thesepriv)) {
                   3014: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   3015: 	}
                   3016:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  3017:     }
                   3018:     return ($author,$adv);
                   3019: }
                   3020: 
1.12      www      3021: # --------------------------------------------------------------- get interface
                   3022: 
                   3023: sub get {
1.131     albertel 3024:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3025:    my $items='';
1.800     albertel 3026:    foreach my $item (@$storearr) {
                   3027:        $items.=&escape($item).'&';
1.191     harris41 3028:    }
1.12      www      3029:    $items=~s/\&$//;
1.620     albertel 3030:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3031:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 3032:    my $uhome=&homeserver($uname,$udomain);
                   3033: 
1.133     albertel 3034:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3035:    my @pairs=split(/\&/,$rep);
1.273     albertel 3036:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   3037:      return @pairs;
                   3038:    }
1.15      www      3039:    my %returnhash=();
1.42      www      3040:    my $i=0;
1.800     albertel 3041:    foreach my $item (@$storearr) {
                   3042:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3043:       $i++;
1.191     harris41 3044:    }
1.15      www      3045:    return %returnhash;
1.27      www      3046: }
                   3047: 
                   3048: # --------------------------------------------------------------- del interface
                   3049: 
                   3050: sub del {
1.133     albertel 3051:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      3052:    my $items='';
1.800     albertel 3053:    foreach my $item (@$storearr) {
                   3054:        $items.=&escape($item).'&';
1.191     harris41 3055:    }
1.27      www      3056:    $items=~s/\&$//;
1.620     albertel 3057:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3058:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3059:    my $uhome=&homeserver($uname,$udomain);
                   3060: 
                   3061:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3062: }
                   3063: 
                   3064: # -------------------------------------------------------------- dump interface
                   3065: 
                   3066: sub dump {
1.755     albertel 3067:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   3068:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3069:     if (!$uname) { $uname=$env{'user.name'}; }
                   3070:     my $uhome=&homeserver($uname,$udomain);
                   3071:     if ($regexp) {
                   3072: 	$regexp=&escape($regexp);
                   3073:     } else {
                   3074: 	$regexp='.';
                   3075:     }
                   3076:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3077:     my @pairs=split(/\&/,$rep);
                   3078:     my %returnhash=();
                   3079:     foreach my $item (@pairs) {
                   3080: 	my ($key,$value)=split(/=/,$item,2);
                   3081: 	$key = &unescape($key);
                   3082: 	next if ($key =~ /^error: 2 /);
                   3083: 	$returnhash{$key}=&thaw_unescape($value);
                   3084:     }
                   3085:     return %returnhash;
1.407     www      3086: }
                   3087: 
1.717     albertel 3088: # --------------------------------------------------------- dumpstore interface
                   3089: 
                   3090: sub dumpstore {
                   3091:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 3092:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3093:    if (!$uname) { $uname=$env{'user.name'}; }
                   3094:    my $uhome=&homeserver($uname,$udomain);
                   3095:    if ($regexp) {
                   3096:        $regexp=&escape($regexp);
                   3097:    } else {
                   3098:        $regexp='.';
                   3099:    }
                   3100:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3101:    my @pairs=split(/\&/,$rep);
                   3102:    my %returnhash=();
                   3103:    foreach my $item (@pairs) {
                   3104:        my ($key,$value)=split(/=/,$item,2);
                   3105:        next if ($key =~ /^error: 2 /);
                   3106:        $returnhash{$key}=&thaw_unescape($value);
                   3107:    }
                   3108:    return %returnhash;
1.717     albertel 3109: }
                   3110: 
1.407     www      3111: # -------------------------------------------------------------- keys interface
                   3112: 
                   3113: sub getkeys {
                   3114:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 3115:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3116:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      3117:    my $uhome=&homeserver($uname,$udomain);
                   3118:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   3119:    my @keyarray=();
1.800     albertel 3120:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  3121:       next if ($key =~ /^error: 2 /);
1.800     albertel 3122:       push(@keyarray,&unescape($key));
1.407     www      3123:    }
                   3124:    return @keyarray;
1.318     matthew  3125: }
                   3126: 
1.319     matthew  3127: # --------------------------------------------------------------- currentdump
                   3128: sub currentdump {
1.328     matthew  3129:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 3130:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   3131:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   3132:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  3133:    my $uhome = &homeserver($sname,$sdom);
                   3134:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  3135:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  3136:    #
1.318     matthew  3137:    my %returnhash=();
1.319     matthew  3138:    #
                   3139:    if ($rep eq "unknown_cmd") { 
                   3140:        # an old lond will not know currentdump
                   3141:        # Do a dump and make it look like a currentdump
1.822     albertel 3142:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  3143:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   3144:        my %hash = @tmp;
                   3145:        @tmp=();
1.424     matthew  3146:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  3147:    } else {
                   3148:        my @pairs=split(/\&/,$rep);
1.800     albertel 3149:        foreach my $pair (@pairs) {
                   3150:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  3151:            my ($symb,$param) = split(/:/,$key);
                   3152:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 3153:                                                         &thaw_unescape($value);
1.319     matthew  3154:        }
1.191     harris41 3155:    }
1.12      www      3156:    return %returnhash;
1.424     matthew  3157: }
                   3158: 
                   3159: sub convert_dump_to_currentdump{
                   3160:     my %hash = %{shift()};
                   3161:     my %returnhash;
                   3162:     # Code ripped from lond, essentially.  The only difference
                   3163:     # here is the unescaping done by lonnet::dump().  Conceivably
                   3164:     # we might run in to problems with parameter names =~ /^v\./
                   3165:     while (my ($key,$value) = each(%hash)) {
                   3166:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 3167: 	$symb  = &unescape($symb);
                   3168: 	$param = &unescape($param);
1.424     matthew  3169:         next if ($v eq 'version' || $symb eq 'keys');
                   3170:         next if (exists($returnhash{$symb}) &&
                   3171:                  exists($returnhash{$symb}->{$param}) &&
                   3172:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   3173:         $returnhash{$symb}->{$param}=$value;
                   3174:         $returnhash{$symb}->{'v.'.$param}=$v;
                   3175:     }
                   3176:     #
                   3177:     # Remove all of the keys in the hashes which keep track of
                   3178:     # the version of the parameter.
                   3179:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   3180:         # use a foreach because we are going to delete from the hash.
                   3181:         foreach my $key (keys(%$param_hash)) {
                   3182:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   3183:         }
                   3184:     }
                   3185:     return \%returnhash;
1.12      www      3186: }
                   3187: 
1.627     albertel 3188: # ------------------------------------------------------ critical inc interface
                   3189: 
                   3190: sub cinc {
                   3191:     return &inc(@_,'critical');
                   3192: }
                   3193: 
1.449     matthew  3194: # --------------------------------------------------------------- inc interface
                   3195: 
                   3196: sub inc {
1.627     albertel 3197:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 3198:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3199:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  3200:     my $uhome=&homeserver($uname,$udomain);
                   3201:     my $items='';
                   3202:     if (! ref($store)) {
                   3203:         # got a single value, so use that instead
                   3204:         $items = &escape($store).'=&';
                   3205:     } elsif (ref($store) eq 'SCALAR') {
                   3206:         $items = &escape($$store).'=&';        
                   3207:     } elsif (ref($store) eq 'ARRAY') {
                   3208:         $items = join('=&',map {&escape($_);} @{$store});
                   3209:     } elsif (ref($store) eq 'HASH') {
                   3210:         while (my($key,$value) = each(%{$store})) {
                   3211:             $items.= &escape($key).'='.&escape($value).'&';
                   3212:         }
                   3213:     }
                   3214:     $items=~s/\&$//;
1.627     albertel 3215:     if ($critical) {
                   3216: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3217:     } else {
                   3218: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3219:     }
1.449     matthew  3220: }
                   3221: 
1.12      www      3222: # --------------------------------------------------------------- put interface
                   3223: 
                   3224: sub put {
1.134     albertel 3225:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3226:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3227:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3228:    my $uhome=&homeserver($uname,$udomain);
1.12      www      3229:    my $items='';
1.800     albertel 3230:    foreach my $item (keys(%$storehash)) {
                   3231:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3232:    }
1.12      www      3233:    $items=~s/\&$//;
1.134     albertel 3234:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      3235: }
                   3236: 
1.631     albertel 3237: # ------------------------------------------------------------ newput interface
                   3238: 
                   3239: sub newput {
                   3240:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   3241:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3242:    if (!$uname) { $uname=$env{'user.name'}; }
                   3243:    my $uhome=&homeserver($uname,$udomain);
                   3244:    my $items='';
                   3245:    foreach my $key (keys(%$storehash)) {
                   3246:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   3247:    }
                   3248:    $items=~s/\&$//;
                   3249:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   3250: }
                   3251: 
                   3252: # ---------------------------------------------------------  putstore interface
                   3253: 
1.524     raeburn  3254: sub putstore {
1.715     albertel 3255:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 3256:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3257:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  3258:    my $uhome=&homeserver($uname,$udomain);
                   3259:    my $items='';
1.715     albertel 3260:    foreach my $key (keys(%$storehash)) {
                   3261:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  3262:    }
1.715     albertel 3263:    $items=~s/\&$//;
1.716     albertel 3264:    my $esc_symb=&escape($symb);
                   3265:    my $esc_v=&escape($version);
1.715     albertel 3266:    my $reply =
1.716     albertel 3267:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 3268: 	      $uhome);
                   3269:    if ($reply eq 'unknown_cmd') {
1.716     albertel 3270:        # gfall back to way things use to be done
1.715     albertel 3271:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   3272: 			    $uname);
1.524     raeburn  3273:    }
1.715     albertel 3274:    return $reply;
                   3275: }
                   3276: 
                   3277: sub old_putstore {
1.716     albertel 3278:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   3279:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3280:     if (!$uname) { $uname=$env{'user.name'}; }
                   3281:     my $uhome=&homeserver($uname,$udomain);
                   3282:     my %newstorehash;
1.800     albertel 3283:     foreach my $item (keys(%$storehash)) {
                   3284: 	my $key = $version.':'.&escape($symb).':'.$item;
                   3285: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 3286:     }
                   3287:     my $items='';
                   3288:     my %allitems = ();
1.800     albertel 3289:     foreach my $item (keys(%newstorehash)) {
                   3290: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 3291: 	    my $key = $1.':keys:'.$2;
                   3292: 	    $allitems{$key} .= $3.':';
                   3293: 	}
1.800     albertel 3294: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 3295:     }
1.800     albertel 3296:     foreach my $item (keys(%allitems)) {
                   3297: 	$allitems{$item} =~ s/\:$//;
                   3298: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 3299:     }
                   3300:     $items=~s/\&$//;
                   3301:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  3302: }
                   3303: 
1.47      www      3304: # ------------------------------------------------------ critical put interface
                   3305: 
                   3306: sub cput {
1.134     albertel 3307:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3308:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3309:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3310:    my $uhome=&homeserver($uname,$udomain);
1.47      www      3311:    my $items='';
1.800     albertel 3312:    foreach my $item (keys(%$storehash)) {
                   3313:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3314:    }
1.47      www      3315:    $items=~s/\&$//;
1.134     albertel 3316:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3317: }
                   3318: 
                   3319: # -------------------------------------------------------------- eget interface
                   3320: 
                   3321: sub eget {
1.133     albertel 3322:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3323:    my $items='';
1.800     albertel 3324:    foreach my $item (@$storearr) {
                   3325:        $items.=&escape($item).'&';
1.191     harris41 3326:    }
1.12      www      3327:    $items=~s/\&$//;
1.620     albertel 3328:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3329:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3330:    my $uhome=&homeserver($uname,$udomain);
                   3331:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3332:    my @pairs=split(/\&/,$rep);
                   3333:    my %returnhash=();
1.42      www      3334:    my $i=0;
1.800     albertel 3335:    foreach my $item (@$storearr) {
                   3336:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3337:       $i++;
1.191     harris41 3338:    }
1.12      www      3339:    return %returnhash;
                   3340: }
                   3341: 
1.667     albertel 3342: # ------------------------------------------------------------ tmpput interface
                   3343: sub tmpput {
1.802     raeburn  3344:     my ($storehash,$server,$context)=@_;
1.667     albertel 3345:     my $items='';
1.800     albertel 3346:     foreach my $item (keys(%$storehash)) {
                   3347: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 3348:     }
                   3349:     $items=~s/\&$//;
1.802     raeburn  3350:     if (defined($context)) {
                   3351:         $items .= ':'.&escape($context);
                   3352:     }
1.667     albertel 3353:     return &reply("tmpput:$items",$server);
                   3354: }
                   3355: 
                   3356: # ------------------------------------------------------------ tmpget interface
                   3357: sub tmpget {
1.688     albertel 3358:     my ($token,$server)=@_;
                   3359:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3360:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 3361:     my %returnhash;
                   3362:     foreach my $item (split(/\&/,$rep)) {
                   3363: 	my ($key,$value)=split(/=/,$item);
                   3364: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   3365:     }
                   3366:     return %returnhash;
                   3367: }
                   3368: 
1.688     albertel 3369: # ------------------------------------------------------------ tmpget interface
                   3370: sub tmpdel {
                   3371:     my ($token,$server)=@_;
                   3372:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3373:     return &reply("tmpdel:$token",$server);
                   3374: }
                   3375: 
1.765     albertel 3376: # -------------------------------------------------- portfolio access checking
                   3377: 
                   3378: sub portfolio_access {
1.766     albertel 3379:     my ($requrl) = @_;
1.765     albertel 3380:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   3381:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  3382:     if ($result) {
                   3383:         my %setters;
                   3384:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3385:             my ($startblock,$endblock) =
                   3386:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   3387:             if ($startblock && $endblock) {
                   3388:                 return 'B';
                   3389:             }
                   3390:         } else {
                   3391:             my ($startblock,$endblock) =
                   3392:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   3393:             if ($startblock && $endblock) {
                   3394:                 return 'B';
                   3395:             }
                   3396:         }
                   3397:     }
1.765     albertel 3398:     if ($result eq 'ok') {
1.766     albertel 3399:        return 'F';
1.765     albertel 3400:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 3401:        return 'A';
1.765     albertel 3402:     }
1.766     albertel 3403:     return '';
1.765     albertel 3404: }
                   3405: 
                   3406: sub get_portfolio_access {
1.767     albertel 3407:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   3408: 
                   3409:     if (!ref($access_hash)) {
                   3410: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   3411: 	my %access_controls = &get_access_controls($current_perms,$group,
                   3412: 						   $file_name);
                   3413: 	$access_hash = $access_controls{$file_name};
                   3414:     }
                   3415: 
1.765     albertel 3416:     my ($public,$guest,@domains,@users,@courses,@groups);
                   3417:     my $now = time;
                   3418:     if (ref($access_hash) eq 'HASH') {
                   3419:         foreach my $key (keys(%{$access_hash})) {
                   3420:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   3421:             if ($start > $now) {
                   3422:                 next;
                   3423:             }
                   3424:             if ($end && $end<$now) {
                   3425:                 next;
                   3426:             }
                   3427:             if ($scope eq 'public') {
                   3428:                 $public = $key;
                   3429:                 last;
                   3430:             } elsif ($scope eq 'guest') {
                   3431:                 $guest = $key;
                   3432:             } elsif ($scope eq 'domains') {
                   3433:                 push(@domains,$key);
                   3434:             } elsif ($scope eq 'users') {
                   3435:                 push(@users,$key);
                   3436:             } elsif ($scope eq 'course') {
                   3437:                 push(@courses,$key);
                   3438:             } elsif ($scope eq 'group') {
                   3439:                 push(@groups,$key);
                   3440:             }
                   3441:         }
                   3442:         if ($public) {
                   3443:             return 'ok';
                   3444:         }
                   3445:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3446:             if ($guest) {
                   3447:                 return $guest;
                   3448:             }
                   3449:         } else {
                   3450:             if (@domains > 0) {
                   3451:                 foreach my $domkey (@domains) {
                   3452:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   3453:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   3454:                             return 'ok';
                   3455:                         }
                   3456:                     }
                   3457:                 }
                   3458:             }
                   3459:             if (@users > 0) {
                   3460:                 foreach my $userkey (@users) {
                   3461:                     if (exists($access_hash->{$userkey}{'users'}{$env{'user.name'}.':'.$env{'user.domain'}})) {
                   3462:                         return 'ok';
                   3463:                     }
                   3464:                 }
                   3465:             }
                   3466:             my %roleshash;
                   3467:             my @courses_and_groups = @courses;
                   3468:             push(@courses_and_groups,@groups); 
                   3469:             if (@courses_and_groups > 0) {
                   3470:                 my (%allgroups,%allroles); 
                   3471:                 my ($start,$end,$role,$sec,$group);
                   3472:                 foreach my $envkey (%env) {
1.811     albertel 3473:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 3474:                         my $cid = $2.'_'.$3; 
                   3475:                         if ($1 eq 'gr') {
                   3476:                             $group = $4;
                   3477:                             $allgroups{$cid}{$group} = $env{$envkey};
                   3478:                         } else {
                   3479:                             if ($4 eq '') {
                   3480:                                 $sec = 'none';
                   3481:                             } else {
                   3482:                                 $sec = $4;
                   3483:                             }
                   3484:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3485:                         }
1.811     albertel 3486:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 3487:                         my $cid = $2.'_'.$3;
                   3488:                         if ($4 eq '') {
                   3489:                             $sec = 'none';
                   3490:                         } else {
                   3491:                             $sec = $4;
                   3492:                         }
                   3493:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3494:                     }
                   3495:                 }
                   3496:                 if (keys(%allroles) == 0) {
                   3497:                     return;
                   3498:                 }
                   3499:                 foreach my $key (@courses_and_groups) {
                   3500:                     my %content = %{$$access_hash{$key}};
                   3501:                     my $cnum = $content{'number'};
                   3502:                     my $cdom = $content{'domain'};
                   3503:                     my $cid = $cdom.'_'.$cnum;
                   3504:                     if (!exists($allroles{$cid})) {
                   3505:                         next;
                   3506:                     }    
                   3507:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   3508:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   3509:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   3510:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   3511:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   3512:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   3513:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   3514:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   3515:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   3516:                                         if (grep/^all$/,@sections) {
                   3517:                                             return 'ok';
                   3518:                                         } else {
                   3519:                                             if (grep/^$sec$/,@sections) {
                   3520:                                                 return 'ok';
                   3521:                                             }
                   3522:                                         }
                   3523:                                     }
                   3524:                                 }
                   3525:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   3526:                                     if (grep/^none$/,@groups) {
                   3527:                                         return 'ok';
                   3528:                                     }
                   3529:                                 } else {
                   3530:                                     if (grep/^all$/,@groups) {
                   3531:                                         return 'ok';
                   3532:                                     } 
                   3533:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   3534:                                         if (grep/^$group$/,@groups) {
                   3535:                                             return 'ok';
                   3536:                                         }
                   3537:                                     }
                   3538:                                 } 
                   3539:                             }
                   3540:                         }
                   3541:                     }
                   3542:                 }
                   3543:             }
                   3544:             if ($guest) {
                   3545:                 return $guest;
                   3546:             }
                   3547:         }
                   3548:     }
                   3549:     return;
                   3550: }
                   3551: 
                   3552: sub course_group_datechecker {
                   3553:     my ($dates,$now,$status) = @_;
                   3554:     my ($start,$end) = split(/\./,$dates);
                   3555:     if (!$start && !$end) {
                   3556:         return 'ok';
                   3557:     }
                   3558:     if (grep/^active$/,@{$status}) {
                   3559:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   3560:             return 'ok';
                   3561:         }
                   3562:     }
                   3563:     if (grep/^previous$/,@{$status}) {
                   3564:         if ($end > $now ) {
                   3565:             return 'ok';
                   3566:         }
                   3567:     }
                   3568:     if (grep/^future$/,@{$status}) {
                   3569:         if ($start > $now) {
                   3570:             return 'ok';
                   3571:         }
                   3572:     }
                   3573:     return; 
                   3574: }
                   3575: 
                   3576: sub parse_portfolio_url {
                   3577:     my ($url) = @_;
                   3578: 
                   3579:     my ($type,$udom,$unum,$group,$file_name);
                   3580:     
1.823     albertel 3581:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 3582: 	$type = 1;
                   3583:         $udom = $1;
                   3584:         $unum = $2;
                   3585:         $file_name = $3;
1.823     albertel 3586:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 3587: 	$type = 2;
                   3588:         $udom = $1;
                   3589:         $unum = $2;
                   3590:         $group = $3;
                   3591:         $file_name = $3.'/'.$4;
                   3592:     }
                   3593:     if (wantarray) {
                   3594: 	return ($type,$udom,$unum,$file_name,$group);
                   3595:     }
                   3596:     return $type;
                   3597: }
                   3598: 
                   3599: sub is_portfolio_url {
                   3600:     my ($url) = @_;
                   3601:     return scalar(&parse_portfolio_url($url));
                   3602: }
                   3603: 
1.798     raeburn  3604: sub is_portfolio_file {
                   3605:     my ($file) = @_;
1.820     raeburn  3606:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  3607:         return 1;
                   3608:     }
                   3609:     return;
                   3610: }
                   3611: 
                   3612: 
1.341     www      3613: # ---------------------------------------------- Custom access rule evaluation
                   3614: 
                   3615: sub customaccess {
                   3616:     my ($priv,$uri)=@_;
1.807     albertel 3617:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      3618:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 3619:     $udom = &LONCAPA::clean_domain($udom);
                   3620:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      3621:     my $access=0;
1.800     albertel 3622:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
                   3623: 	my ($effect,$realm,$role)=split(/\:/,$right);
1.343     www      3624:         if ($role) {
                   3625: 	   if ($role ne $urole) { next; }
                   3626:         }
1.800     albertel 3627:         foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   3628:             my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
1.343     www      3629:             if ($tdom) {
                   3630: 		if ($tdom ne $udom) { next; }
                   3631:             }
                   3632:             if ($tcrs) {
                   3633: 		if ($tcrs ne $ucrs) { next; }
                   3634:             }
                   3635:             if ($tsec) {
                   3636: 		if ($tsec ne $usec) { next; }
                   3637:             }
                   3638:             $access=($effect eq 'allow');
                   3639:             last;
1.342     www      3640:         }
1.402     bowersj2 3641: 	if ($realm eq '' && $role eq '') {
                   3642:             $access=($effect eq 'allow');
                   3643: 	}
1.341     www      3644:     }
                   3645:     return $access;
                   3646: }
                   3647: 
1.103     harris41 3648: # ------------------------------------------------- Check for a user privilege
1.12      www      3649: 
                   3650: sub allowed {
1.810     raeburn  3651:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 3652:     my $ver_orguri=$uri;
1.439     www      3653:     $uri=&deversion($uri);
1.152     www      3654:     my $orguri=$uri;
1.52      www      3655:     $uri=&declutter($uri);
1.809     raeburn  3656: 
1.810     raeburn  3657:     if ($priv eq 'evb') {
                   3658: # Evade communication block restrictions for specified role in a course
                   3659:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   3660:             return $1;
                   3661:         } else {
                   3662:             return;
                   3663:         }
                   3664:     }
                   3665: 
1.620     albertel 3666:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      3667: # Free bre access to adm and meta resources
1.775     albertel 3668:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 3669: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   3670: 	&& ($priv eq 'bre')) {
1.14      www      3671: 	return 'F';
1.159     www      3672:     }
                   3673: 
1.545     banghart 3674: # Free bre access to user's own portfolio contents
1.714     raeburn  3675:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  3676:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  3677: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  3678:         my %setters;
                   3679:         my ($startblock,$endblock) = 
                   3680:             &Apache::loncommon::blockcheck(\%setters,'port');
                   3681:         if ($startblock && $endblock) {
                   3682:             return 'B';
                   3683:         } else {
                   3684:             return 'F';
                   3685:         }
1.545     banghart 3686:     }
                   3687: 
1.762     raeburn  3688: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  3689:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   3690:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   3691:         if (exists($env{'request.course.id'})) {
                   3692:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3693:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3694:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   3695:                 my $courseprivid=$env{'request.course.id'};
                   3696:                 $courseprivid=~s/\_/\//;
                   3697:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   3698:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   3699:                     return $1; 
1.762     raeburn  3700:                 } else {
                   3701:                     if ($env{'request.course.sec'}) {
                   3702:                         $courseprivid.='/'.$env{'request.course.sec'};
                   3703:                     }
                   3704:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   3705:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   3706:                         return $2;
                   3707:                     }
1.714     raeburn  3708:                 }
                   3709:             }
                   3710:         }
                   3711:     }
                   3712: 
1.159     www      3713: # Free bre to public access
                   3714: 
                   3715:     if ($priv eq 'bre') {
1.238     www      3716:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 3717: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      3718:            return 'F'; 
                   3719:         }
1.238     www      3720:         if ($copyright eq 'priv') {
                   3721:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3722: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      3723: 		return '';
                   3724:             }
                   3725:         }
                   3726:         if ($copyright eq 'domain') {
                   3727:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3728: 	    unless (($env{'user.domain'} eq $1) ||
                   3729:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      3730: 		return '';
                   3731:             }
1.262     matthew  3732:         }
1.620     albertel 3733:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  3734:             # Library role, so allow browsing of resources in this domain.
                   3735:             return 'F';
1.238     www      3736:         }
1.341     www      3737:         if ($copyright eq 'custom') {
                   3738: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   3739:         }
1.14      www      3740:     }
1.264     matthew  3741:     # Domain coordinator is trying to create a course
1.620     albertel 3742:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  3743:         # uri is the requested domain in this case.
                   3744:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  3745:         # a role of dc for the domain in question.
1.620     albertel 3746:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  3747:     }
1.29      www      3748: 
1.52      www      3749:     my $thisallowed='';
                   3750:     my $statecond=0;
                   3751:     my $courseprivid='';
                   3752: 
                   3753: # Course
                   3754: 
1.620     albertel 3755:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3756:        $thisallowed.=$1;
                   3757:     }
1.29      www      3758: 
1.52      www      3759: # Domain
                   3760: 
1.620     albertel 3761:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 3762:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3763:        $thisallowed.=$1;
                   3764:     }
1.52      www      3765: 
                   3766: # Course: uri itself is a course
1.66      www      3767:     my $courseuri=$uri;
                   3768:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      3769:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      3770: 
1.620     albertel 3771:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 3772:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3773:        $thisallowed.=$1;
                   3774:     }
1.29      www      3775: 
1.665     albertel 3776: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 3777: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 3778:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 3779: 	$thisallowed='';
1.671     raeburn  3780:         my ($match)=&is_on_map($uri);
                   3781:         if ($match) {
                   3782:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   3783:                   =~/\Q$priv\E\&([^\:]*)/) {
                   3784:                 $thisallowed.=$1;
                   3785:             }
                   3786:         } else {
1.705     albertel 3787:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  3788:             if ($refuri) {
                   3789:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  3790:                     $thisallowed='F';
1.671     raeburn  3791:                 } else {
                   3792:                     $refuri=&declutter($refuri);
                   3793:                     my ($match) = &is_on_map($refuri);
                   3794:                     if ($match) {
                   3795:                         $thisallowed='F';
                   3796:                     }
1.669     raeburn  3797:                 }
1.671     raeburn  3798:             }
                   3799:         }
1.314     www      3800:     }
1.492     albertel 3801: 
1.766     albertel 3802:     if ($priv eq 'bre'
                   3803: 	&& $thisallowed ne 'F' 
                   3804: 	&& $thisallowed ne '2'
                   3805: 	&& &is_portfolio_url($uri)) {
                   3806: 	$thisallowed = &portfolio_access($uri);
                   3807:     }
                   3808:     
1.52      www      3809: # Full access at system, domain or course-wide level? Exit.
1.29      www      3810: 
                   3811:     if ($thisallowed=~/F/) {
                   3812: 	return 'F';
                   3813:     }
                   3814: 
1.52      www      3815: # If this is generating or modifying users, exit with special codes
1.29      www      3816: 
1.643     www      3817:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   3818: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 3819: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      3820: # no author name given, so this just checks on the general right to make a co-author in this domain
                   3821: 	    unless ($auname) { return $thisallowed; }
                   3822: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 3823: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   3824: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   3825: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   3826: 	}
1.52      www      3827: 	return $thisallowed;
                   3828:     }
                   3829: #
1.103     harris41 3830: # Gathered so far: system, domain and course wide privileges
1.52      www      3831: #
                   3832: # Course: See if uri or referer is an individual resource that is part of 
                   3833: # the course
                   3834: 
1.620     albertel 3835:     if ($env{'request.course.id'}) {
1.232     www      3836: 
1.620     albertel 3837:        $courseprivid=$env{'request.course.id'};
                   3838:        if ($env{'request.course.sec'}) {
                   3839:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      3840:        }
                   3841:        $courseprivid=~s/\_/\//;
                   3842:        my $checkreferer=1;
1.232     www      3843:        my ($match,$cond)=&is_on_map($uri);
                   3844:        if ($match) {
                   3845:            $statecond=$cond;
1.620     albertel 3846:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 3847:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3848:                $thisallowed.=$1;
                   3849:                $checkreferer=0;
                   3850:            }
1.29      www      3851:        }
1.83      www      3852:        
1.148     www      3853:        if ($checkreferer) {
1.620     albertel 3854: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      3855:             unless ($refuri) {
1.800     albertel 3856:                 foreach my $key (keys(%env)) {
                   3857: 		    if ($key=~/^httpref\..*\*/) {
                   3858: 			my $pattern=$key;
1.156     www      3859:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      3860:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   3861:                         $pattern=~s/\//\\\//g;
1.152     www      3862:                         if ($orguri=~/$pattern/) {
1.800     albertel 3863: 			    $refuri=$env{$key};
1.148     www      3864:                         }
                   3865:                     }
1.191     harris41 3866:                 }
1.148     www      3867:             }
1.232     www      3868: 
1.148     www      3869:          if ($refuri) { 
1.152     www      3870: 	  $refuri=&declutter($refuri);
1.232     www      3871:           my ($match,$cond)=&is_on_map($refuri);
                   3872:             if ($match) {
                   3873:               my $refstatecond=$cond;
1.620     albertel 3874:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 3875:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3876:                   $thisallowed.=$1;
1.53      www      3877:                   $uri=$refuri;
                   3878:                   $statecond=$refstatecond;
1.52      www      3879:               }
                   3880:           }
1.148     www      3881:         }
1.29      www      3882:        }
1.52      www      3883:    }
1.29      www      3884: 
1.52      www      3885: #
1.103     harris41 3886: # Gathered now: all privileges that could apply, and condition number
1.52      www      3887: # 
                   3888: #
                   3889: # Full or no access?
                   3890: #
1.29      www      3891: 
1.52      www      3892:     if ($thisallowed=~/F/) {
                   3893: 	return 'F';
                   3894:     }
1.29      www      3895: 
1.52      www      3896:     unless ($thisallowed) {
                   3897:         return '';
                   3898:     }
1.29      www      3899: 
1.52      www      3900: # Restrictions exist, deal with them
                   3901: #
                   3902: #   C:according to course preferences
                   3903: #   R:according to resource settings
                   3904: #   L:unless locked
                   3905: #   X:according to user session state
                   3906: #
                   3907: 
                   3908: # Possibly locked functionality, check all courses
1.54      www      3909: # Locks might take effect only after 10 minutes cache expiration for other
                   3910: # courses, and 2 minutes for current course
1.52      www      3911: 
                   3912:     my $envkey;
                   3913:     if ($thisallowed=~/L/) {
1.620     albertel 3914:         foreach $envkey (keys %env) {
1.54      www      3915:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   3916:                my $courseid=$2;
                   3917:                my $roleid=$1.'.'.$2;
1.92      www      3918:                $courseid=~s/^\///;
1.54      www      3919:                my $expiretime=600;
1.620     albertel 3920:                if ($env{'request.role'} eq $roleid) {
1.54      www      3921: 		  $expiretime=120;
                   3922:                }
                   3923: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   3924:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 3925:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 3926: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      3927:                }
1.620     albertel 3928:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   3929:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   3930: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   3931:                        &log($env{'user.domain'},$env{'user.name'},
                   3932:                             $env{'user.home'},
1.57      www      3933:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      3934:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 3935:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      3936: 		       return '';
                   3937:                    }
                   3938:                }
1.620     albertel 3939:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   3940:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   3941: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   3942:                        &log($env{'user.domain'},$env{'user.name'},
                   3943:                             $env{'user.home'},
1.57      www      3944:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      3945:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 3946:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      3947: 		       return '';
                   3948:                    }
                   3949:                }
                   3950: 	   }
1.29      www      3951:        }
1.52      www      3952:     }
                   3953:    
                   3954: #
                   3955: # Rest of the restrictions depend on selected course
                   3956: #
                   3957: 
1.620     albertel 3958:     unless ($env{'request.course.id'}) {
1.766     albertel 3959: 	if ($thisallowed eq 'A') {
                   3960: 	    return 'A';
1.814     raeburn  3961:         } elsif ($thisallowed eq 'B') {
                   3962:             return 'B';
1.766     albertel 3963: 	} else {
                   3964: 	    return '1';
                   3965: 	}
1.52      www      3966:     }
1.29      www      3967: 
1.52      www      3968: #
                   3969: # Now user is definitely in a course
                   3970: #
1.53      www      3971: 
                   3972: 
                   3973: # Course preferences
                   3974: 
                   3975:    if ($thisallowed=~/C/) {
1.620     albertel 3976:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   3977:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   3978:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 3979: 	   =~/\Q$rolecode\E/) {
1.689     albertel 3980: 	   if ($priv ne 'pch') { 
                   3981: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   3982: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   3983: 			$env{'request.course.id'});
                   3984: 	   }
1.237     www      3985:            return '';
                   3986:        }
                   3987: 
1.620     albertel 3988:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 3989: 	   =~/\Q$unamedom\E/) {
1.689     albertel 3990: 	   if ($priv ne 'pch') { 
                   3991: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   3992: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   3993: 			$env{'request.course.id'});
                   3994: 	   }
1.54      www      3995:            return '';
                   3996:        }
1.53      www      3997:    }
                   3998: 
                   3999: # Resource preferences
                   4000: 
                   4001:    if ($thisallowed=~/R/) {
1.620     albertel 4002:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 4003:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 4004: 	   if ($priv ne 'pch') { 
                   4005: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4006: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   4007: 	   }
                   4008: 	   return '';
1.54      www      4009:        }
1.53      www      4010:    }
1.30      www      4011: 
1.246     www      4012: # Restricted by state or randomout?
1.30      www      4013: 
1.52      www      4014:    if ($thisallowed=~/X/) {
1.620     albertel 4015:       if ($env{'acc.randomout'}) {
1.579     albertel 4016: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 4017:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      4018:             return ''; 
                   4019:          }
1.247     www      4020:       }
                   4021:       if (&condval($statecond)) {
1.52      www      4022: 	 return '2';
                   4023:       } else {
                   4024:          return '';
                   4025:       }
                   4026:    }
1.30      www      4027: 
1.766     albertel 4028:     if ($thisallowed eq 'A') {
                   4029: 	return 'A';
1.814     raeburn  4030:     } elsif ($thisallowed eq 'B') {
                   4031:         return 'B';
1.766     albertel 4032:     }
1.52      www      4033:    return 'F';
1.232     www      4034: }
                   4035: 
1.710     albertel 4036: sub split_uri_for_cond {
                   4037:     my $uri=&deversion(&declutter(shift));
                   4038:     my @uriparts=split(/\//,$uri);
                   4039:     my $filename=pop(@uriparts);
                   4040:     my $pathname=join('/',@uriparts);
                   4041:     return ($pathname,$filename);
                   4042: }
1.232     www      4043: # --------------------------------------------------- Is a resource on the map?
                   4044: 
                   4045: sub is_on_map {
1.710     albertel 4046:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 4047:     #Trying to find the conditional for the file
1.620     albertel 4048:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 4049: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      4050:     if ($match) {
1.289     bowersj2 4051: 	return (1,$1);
                   4052:     } else {
1.434     www      4053: 	return (0,0);
1.289     bowersj2 4054:     }
1.12      www      4055: }
                   4056: 
1.427     www      4057: # --------------------------------------------------------- Get symb from alias
                   4058: 
                   4059: sub get_symb_from_alias {
                   4060:     my $symb=shift;
                   4061:     my ($map,$resid,$url)=&decode_symb($symb);
                   4062: # Already is a symb
                   4063:     if ($url) { return $symb; }
                   4064: # Must be an alias
                   4065:     my $aliassymb='';
                   4066:     my %bighash;
1.620     albertel 4067:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      4068:                             &GDBM_READER(),0640)) {
                   4069:         my $rid=$bighash{'mapalias_'.$symb};
                   4070: 	if ($rid) {
                   4071: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 4072: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   4073: 				    $resid,$bighash{'src_'.$rid});
1.427     www      4074: 	}
                   4075:         untie %bighash;
                   4076:     }
                   4077:     return $aliassymb;
                   4078: }
                   4079: 
1.12      www      4080: # ----------------------------------------------------------------- Define Role
                   4081: 
                   4082: sub definerole {
                   4083:   if (allowed('mcr','/')) {
                   4084:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 4085:     foreach my $role (split(':',$sysrole)) {
                   4086: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4087:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   4088:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   4089: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4090:                return "refused:s:$crole&$cqual"; 
                   4091:             }
                   4092:         }
1.191     harris41 4093:     }
1.800     albertel 4094:     foreach my $role (split(':',$domrole)) {
                   4095: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4096:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   4097:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   4098: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      4099:                return "refused:d:$crole&$cqual"; 
                   4100:             }
                   4101:         }
1.191     harris41 4102:     }
1.800     albertel 4103:     foreach my $role (split(':',$courole)) {
                   4104: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4105:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   4106:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   4107: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4108:                return "refused:c:$crole&$cqual"; 
                   4109:             }
                   4110:         }
1.191     harris41 4111:     }
1.620     albertel 4112:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   4113:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4114: 	        "rolesdef_$rolename=".
                   4115:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 4116:     return reply($command,$env{'user.home'});
1.12      www      4117:   } else {
                   4118:     return 'refused';
                   4119:   }
1.105     harris41 4120: }
                   4121: 
                   4122: # ---------------- Make a metadata query against the network of library servers
                   4123: 
                   4124: sub metadata_query {
1.244     matthew  4125:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 4126:     my %rhash;
1.244     matthew  4127:     my @server_list = (defined($server_array) ? @$server_array
                   4128:                                               : keys(%libserv) );
                   4129:     for my $server (@server_list) {
1.118     harris41 4130: 	unless ($custom or $customshow) {
                   4131: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   4132: 	    $rhash{$server}=$reply;
                   4133: 	}
                   4134: 	else {
                   4135: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   4136: 			     &escape($custom).':'.&escape($customshow),
                   4137: 			     $server);
                   4138: 	    $rhash{$server}=$reply;
                   4139: 	}
1.112     harris41 4140:     }
1.118     harris41 4141:     return \%rhash;
1.240     www      4142: }
                   4143: 
                   4144: # ----------------------------------------- Send log queries and wait for reply
                   4145: 
                   4146: sub log_query {
                   4147:     my ($uname,$udom,$query,%filters)=@_;
                   4148:     my $uhome=&homeserver($uname,$udom);
                   4149:     if ($uhome eq 'no_host') { return 'error: no_host'; }
                   4150:     my $uhost=$hostname{$uhome};
1.800     albertel 4151:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      4152:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   4153:                        $uhome);
1.479     albertel 4154:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      4155:     return get_query_reply($queryid);
                   4156: }
                   4157: 
1.818     raeburn  4158: # -------------------------- Update MySQL table for portfolio file
                   4159: 
                   4160: sub update_portfolio_table {
1.821     raeburn  4161:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.818     raeburn  4162:     my $homeserver = &homeserver($uname,$udom);
                   4163:     my $queryid=
1.821     raeburn  4164:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   4165:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  4166:     my $reply = &get_query_reply($queryid);
                   4167:     return $reply;
                   4168: }
                   4169: 
1.508     raeburn  4170: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  4171: 
                   4172: sub fetch_enrollment_query {
1.511     raeburn  4173:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  4174:     my $homeserver;
1.547     raeburn  4175:     my $maxtries = 1;
1.508     raeburn  4176:     if ($context eq 'automated') {
                   4177:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  4178:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  4179:     } else {
                   4180:         $homeserver = &homeserver($cnum,$dom);
                   4181:     }
1.506     raeburn  4182:     my $host=$hostname{$homeserver};
                   4183:     my $cmd = '';
1.800     albertel 4184:     foreach my $affiliate (keys %{$affiliatesref}) {
                   4185:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  4186:     }
                   4187:     $cmd =~ s/%%$//;
                   4188:     $cmd = &escape($cmd);
                   4189:     my $query = 'fetchenrollment';
1.620     albertel 4190:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  4191:     unless ($queryid=~/^\Q$host\E\_/) { 
                   4192:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   4193:         return 'error: '.$queryid;
                   4194:     }
1.506     raeburn  4195:     my $reply = &get_query_reply($queryid);
1.547     raeburn  4196:     my $tries = 1;
                   4197:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4198:         $reply = &get_query_reply($queryid);
                   4199:         $tries ++;
                   4200:     }
1.526     raeburn  4201:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 4202:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  4203:     } else {
1.515     raeburn  4204:         my @responses = split/:/,$reply;
                   4205:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 4206:             foreach my $line (@responses) {
                   4207:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  4208:                 $$replyref{$key} = $value;
                   4209:             }
                   4210:         } else {
1.506     raeburn  4211:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 4212:             foreach my $line (@responses) {
                   4213:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  4214:                 $$replyref{$key} = $value;
                   4215:                 if ($value > 0) {
1.800     albertel 4216:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   4217:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  4218:                         my $destname = $pathname.'/'.$filename;
                   4219:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  4220:                         if ($xml_classlist =~ /^error/) {
                   4221:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   4222:                         } else {
1.506     raeburn  4223:                             if ( open(FILE,">$destname") ) {
                   4224:                                 print FILE &unescape($xml_classlist);
                   4225:                                 close(FILE);
1.526     raeburn  4226:                             } else {
                   4227:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  4228:                             }
                   4229:                         }
                   4230:                     }
                   4231:                 }
                   4232:             }
                   4233:         }
                   4234:         return 'ok';
                   4235:     }
                   4236:     return 'error';
                   4237: }
                   4238: 
1.242     www      4239: sub get_query_reply {
                   4240:     my $queryid=shift;
1.240     www      4241:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   4242:     my $reply='';
                   4243:     for (1..100) {
                   4244: 	sleep 2;
                   4245:         if (-e $replyfile.'.end') {
1.448     albertel 4246: 	    if (open(my $fh,$replyfile)) {
1.240     www      4247:                $reply.=<$fh>;
1.448     albertel 4248:                close($fh);
1.240     www      4249: 	   } else { return 'error: reply_file_error'; }
1.242     www      4250:            return &unescape($reply);
                   4251: 	}
1.240     www      4252:     }
1.242     www      4253:     return 'timeout:'.$queryid;
1.240     www      4254: }
                   4255: 
                   4256: sub courselog_query {
1.241     www      4257: #
                   4258: # possible filters:
                   4259: # url: url or symb
                   4260: # username
                   4261: # domain
                   4262: # action: view, submit, grade
                   4263: # start: timestamp
                   4264: # end: timestamp
                   4265: #
1.240     www      4266:     my (%filters)=@_;
1.620     albertel 4267:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      4268:     if ($filters{'url'}) {
                   4269: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   4270:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   4271:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   4272:     }
1.620     albertel 4273:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4274:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      4275:     return &log_query($cname,$cdom,'courselog',%filters);
                   4276: }
                   4277: 
                   4278: sub userlog_query {
                   4279:     my ($uname,$udom,%filters)=@_;
                   4280:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      4281: }
                   4282: 
1.506     raeburn  4283: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   4284: 
                   4285: sub auto_run {
1.508     raeburn  4286:     my ($cnum,$cdom) = @_;
                   4287:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4288:     my $response = &reply('autorun:'.$cdom,$homeserver);
1.506     raeburn  4289:     return $response;
                   4290: }
1.776     albertel 4291: 
1.506     raeburn  4292: sub auto_get_sections {
1.508     raeburn  4293:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   4294:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  4295:     my @secs = ();
1.511     raeburn  4296:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  4297:     unless ($response eq 'refused') {
                   4298:         @secs = split/:/,$response;
                   4299:     }
                   4300:     return @secs;
                   4301: }
1.776     albertel 4302: 
1.506     raeburn  4303: sub auto_new_course {
1.508     raeburn  4304:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   4305:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  4306:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  4307:     return $response;
                   4308: }
1.776     albertel 4309: 
1.506     raeburn  4310: sub auto_validate_courseID {
1.508     raeburn  4311:     my ($cnum,$cdom,$inst_course_id) = @_;
                   4312:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4313:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  4314:     return $response;
                   4315: }
1.776     albertel 4316: 
1.506     raeburn  4317: sub auto_create_password {
1.508     raeburn  4318:     my ($cnum,$cdom,$authparam) = @_;
                   4319:     my $homeserver = &homeserver($cnum,$cdom); 
1.506     raeburn  4320:     my $create_passwd = 0;
                   4321:     my $authchk = '';
1.511     raeburn  4322:     my $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
1.506     raeburn  4323:     if ($response eq 'refused') {
                   4324:         $authchk = 'refused';
                   4325:     } else {
                   4326:         ($authparam,$create_passwd,$authchk) = split/:/,$response;
                   4327:     }
                   4328:     return ($authparam,$create_passwd,$authchk);
                   4329: }
                   4330: 
1.706     raeburn  4331: sub auto_photo_permission {
                   4332:     my ($cnum,$cdom,$students) = @_;
                   4333:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 4334:     my ($outcome,$perm_reqd,$conditions) = 
                   4335: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 4336:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4337: 	return (undef,undef);
                   4338:     }
1.706     raeburn  4339:     return ($outcome,$perm_reqd,$conditions);
                   4340: }
                   4341: 
                   4342: sub auto_checkphotos {
                   4343:     my ($uname,$udom,$pid) = @_;
                   4344:     my $homeserver = &homeserver($uname,$udom);
                   4345:     my ($result,$resulttype);
                   4346:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 4347: 				   &escape($uname).':'.&escape($pid),
                   4348: 				   $homeserver));
1.709     albertel 4349:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4350: 	return (undef,undef);
                   4351:     }
1.706     raeburn  4352:     if ($outcome) {
                   4353:         ($result,$resulttype) = split(/:/,$outcome);
                   4354:     } 
                   4355:     return ($result,$resulttype);
                   4356: }
                   4357: 
                   4358: sub auto_photochoice {
                   4359:     my ($cnum,$cdom) = @_;
                   4360:     my $homeserver = &homeserver($cnum,$cdom);
                   4361:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 4362: 						       &escape($cdom),
                   4363: 						       $homeserver)));
1.709     albertel 4364:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4365: 	return (undef,undef);
                   4366:     }
1.706     raeburn  4367:     return ($update,$comment);
                   4368: }
                   4369: 
                   4370: sub auto_photoupdate {
                   4371:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   4372:     my $homeserver = &homeserver($cnum,$dom);
                   4373:     my $host=$hostname{$homeserver};
                   4374:     my $cmd = '';
                   4375:     my $maxtries = 1;
1.800     albertel 4376:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   4377:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  4378:     }
                   4379:     $cmd =~ s/%%$//;
                   4380:     $cmd = &escape($cmd);
                   4381:     my $query = 'institutionalphotos';
                   4382:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   4383:     unless ($queryid=~/^\Q$host\E\_/) {
                   4384:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   4385:         return 'error: '.$queryid;
                   4386:     }
                   4387:     my $reply = &get_query_reply($queryid);
                   4388:     my $tries = 1;
                   4389:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4390:         $reply = &get_query_reply($queryid);
                   4391:         $tries ++;
                   4392:     }
                   4393:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   4394:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   4395:     } else {
                   4396:         my @responses = split(/:/,$reply);
                   4397:         my $outcome = shift(@responses); 
                   4398:         foreach my $item (@responses) {
                   4399:             my ($key,$value) = split(/=/,$item);
                   4400:             $$photo{$key} = $value;
                   4401:         }
                   4402:         return $outcome;
                   4403:     }
                   4404:     return 'error';
                   4405: }
                   4406: 
1.521     raeburn  4407: sub auto_instcode_format {
1.793     albertel 4408:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   4409: 	$cat_order) = @_;
1.521     raeburn  4410:     my $courses = '';
1.772     raeburn  4411:     my @homeservers;
1.521     raeburn  4412:     if ($caller eq 'global') {
1.793     albertel 4413:         foreach my $tryserver (keys(%libserv)) {
1.584     raeburn  4414:             if ($hostdom{$tryserver} eq $codedom) {
1.793     albertel 4415:                 if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
1.772     raeburn  4416:                     push(@homeservers,$tryserver);
                   4417:                 }
1.584     raeburn  4418:             }
                   4419:         }
1.521     raeburn  4420:     } else {
1.772     raeburn  4421:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  4422:     }
1.793     albertel 4423:     foreach my $code (keys(%{$instcodes})) {
                   4424:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  4425:     }
                   4426:     chop($courses);
1.772     raeburn  4427:     my $ok_response = 0;
                   4428:     my $response;
                   4429:     while (@homeservers > 0 && $ok_response == 0) {
                   4430:         my $server = shift(@homeservers); 
                   4431:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   4432:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   4433:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.793     albertel 4434: 		split/:/,$response;
1.772     raeburn  4435:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   4436:             push(@{$codetitles},&str2array($codetitles_str));
                   4437:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   4438:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   4439:             $ok_response = 1;
                   4440:         }
                   4441:     }
                   4442:     if ($ok_response) {
1.521     raeburn  4443:         return 'ok';
1.772     raeburn  4444:     } else {
                   4445:         return $response;
1.521     raeburn  4446:     }
                   4447: }
                   4448: 
1.792     raeburn  4449: sub auto_instcode_defaults {
                   4450:     my ($domain,$returnhash,$code_order) = @_;
                   4451:     my @homeservers;
1.793     albertel 4452:     foreach my $tryserver (keys(%libserv)) {
1.792     raeburn  4453:         if ($hostdom{$tryserver} eq $domain) {
1.793     albertel 4454:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
1.792     raeburn  4455:                 push(@homeservers,$tryserver);
                   4456:             }
                   4457:         }
                   4458:     }
                   4459:     my $ok_response = 0;
                   4460:     my $response;
                   4461:     while (@homeservers > 0 && $ok_response == 0) {
                   4462:         my $server = shift(@homeservers);
                   4463:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
                   4464:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
1.793     albertel 4465:             foreach my $pair (split(/\&/,$response)) {
                   4466:                 my ($name,$value)=split(/\=/,$pair);
1.792     raeburn  4467:                 if ($name eq 'code_order') {
1.796     raeburn  4468:                     @{$code_order} = split(/\&/,&unescape($value));
1.792     raeburn  4469:                 } else {
1.796     raeburn  4470:                     $returnhash->{&unescape($name)}=&unescape($value);
1.792     raeburn  4471:                 }
                   4472:             }
1.804     raeburn  4473:             $ok_response = 1;
1.792     raeburn  4474:         }
                   4475:     }
                   4476:     if ($ok_response) {
                   4477:         return 'ok';
                   4478:     } else {
                   4479:         return $response;
                   4480:     }
                   4481: } 
                   4482: 
1.777     albertel 4483: sub auto_validate_class_sec {
1.773     raeburn  4484:     my ($cdom,$cnum,$owner,$inst_class) = @_;
                   4485:     my $homeserver = &homeserver($cnum,$cdom);
                   4486:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.774     banghart 4487:                         &escape($owner).':'.$cdom,$homeserver);
1.773     raeburn  4488:     return $response;
                   4489: }
                   4490: 
1.679     raeburn  4491: # ------------------------------------------------------- Course Group routines
                   4492: 
                   4493: sub get_coursegroups {
1.809     raeburn  4494:     my ($cdom,$cnum,$group,$namespace) = @_;
                   4495:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  4496: }
                   4497: 
1.679     raeburn  4498: sub modify_coursegroup {
                   4499:     my ($cdom,$cnum,$groupsettings) = @_;
                   4500:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   4501: }
                   4502: 
1.809     raeburn  4503: sub toggle_coursegroup_status {
                   4504:     my ($cdom,$cnum,$group,$action) = @_;
                   4505:     my ($from_namespace,$to_namespace);
                   4506:     if ($action eq 'delete') {
                   4507:         $from_namespace = 'coursegroups';
                   4508:         $to_namespace = 'deleted_groups';
                   4509:     } else {
                   4510:         $from_namespace = 'deleted_groups';
                   4511:         $to_namespace = 'coursegroups';
                   4512:     }
                   4513:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  4514:     if (my $tmp = &error(%curr_group)) {
                   4515:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   4516:         return ('read error',$tmp);
                   4517:     } else {
                   4518:         my %savedsettings = %curr_group; 
1.809     raeburn  4519:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  4520:         my $deloutcome;
                   4521:         if ($result eq 'ok') {
1.809     raeburn  4522:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  4523:         } else {
                   4524:             return ('write error',$result);
                   4525:         }
                   4526:         if ($deloutcome eq 'ok') {
                   4527:             return 'ok';
                   4528:         } else {
                   4529:             return ('delete error',$deloutcome);
                   4530:         }
                   4531:     }
                   4532: }
                   4533: 
1.679     raeburn  4534: sub modify_group_roles {
                   4535:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
                   4536:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   4537:     my $role = 'gr/'.&escape($userprivs);
                   4538:     my ($uname,$udom) = split(/:/,$user);
                   4539:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
1.684     raeburn  4540:     if ($result eq 'ok') {
                   4541:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   4542:     }
1.679     raeburn  4543:     return $result;
                   4544: }
                   4545: 
                   4546: sub modify_coursegroup_membership {
                   4547:     my ($cdom,$cnum,$membership) = @_;
                   4548:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   4549:     return $result;
                   4550: }
                   4551: 
1.682     raeburn  4552: sub get_active_groups {
                   4553:     my ($udom,$uname,$cdom,$cnum) = @_;
                   4554:     my $now = time;
                   4555:     my %groups = ();
                   4556:     foreach my $key (keys(%env)) {
1.811     albertel 4557:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  4558:             my ($start,$end) = split(/\./,$env{$key});
                   4559:             if (($end!=0) && ($end<$now)) { next; }
                   4560:             if (($start!=0) && ($start>$now)) { next; }
                   4561:             if ($1 eq $cdom && $2 eq $cnum) {
                   4562:                 $groups{$3} = $env{$key} ;
                   4563:             }
                   4564:         }
                   4565:     }
                   4566:     return %groups;
                   4567: }
                   4568: 
1.683     raeburn  4569: sub get_group_membership {
                   4570:     my ($cdom,$cnum,$group) = @_;
                   4571:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   4572: }
                   4573: 
                   4574: sub get_users_groups {
                   4575:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  4576:     my @usersgroups;
1.683     raeburn  4577:     my $cachetime=1800;
                   4578: 
                   4579:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  4580:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   4581:     if (defined($cached)) {
1.734     albertel 4582:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  4583:     } else {  
                   4584:         $grouplist = '';
1.816     raeburn  4585:         my $courseurl = &courseid_to_courseurl($courseid);
                   4586:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  4587:         my $access_end = $env{'course.'.$courseid.
                   4588:                               '.default_enrollment_end_date'};
                   4589:         my $now = time;
                   4590:         foreach my $key (keys(%roleshash)) {
                   4591:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   4592:                 my $group = $1;
                   4593:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   4594:                     my $start = $2;
                   4595:                     my $end = $1;
                   4596:                     if ($start == -1) { next; } # deleted from group
                   4597:                     if (($start!=0) && ($start>$now)) { next; }
                   4598:                     if (($end!=0) && ($end<$now)) {
                   4599:                         if ($access_end && $access_end < $now) {
                   4600:                             if ($access_end - $end < 86400) {
                   4601:                                 push(@usersgroups,$group);
1.733     raeburn  4602:                             }
                   4603:                         }
1.817     raeburn  4604:                         next;
1.733     raeburn  4605:                     }
1.817     raeburn  4606:                     push(@usersgroups,$group);
1.683     raeburn  4607:                 }
                   4608:             }
                   4609:         }
1.817     raeburn  4610:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   4611:         $grouplist = join(':',@usersgroups);
                   4612:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  4613:     }
1.733     raeburn  4614:     return @usersgroups;
1.683     raeburn  4615: }
                   4616: 
                   4617: sub devalidate_getgroups_cache {
                   4618:     my ($udom,$uname,$cdom,$cnum)=@_;
                   4619:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 4620: 
1.683     raeburn  4621:     my $hashid="$udom:$uname:$courseid";
                   4622:     &devalidate_cache_new('getgroups',$hashid);
                   4623: }
                   4624: 
1.12      www      4625: # ------------------------------------------------------------------ Plain Text
                   4626: 
                   4627: sub plaintext {
1.742     raeburn  4628:     my ($short,$type,$cid) = @_;
1.758     albertel 4629:     if ($short =~ /^cr/) {
                   4630: 	return (split('/',$short))[-1];
                   4631:     }
1.742     raeburn  4632:     if (!defined($cid)) {
                   4633:         $cid = $env{'request.course.id'};
                   4634:     }
                   4635:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
                   4636:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
                   4637:                                           '.plaintext'});
                   4638:     }
                   4639:     my %rolenames = (
                   4640:                       Course => 'std',
                   4641:                       Group => 'alt1',
                   4642:                     );
                   4643:     if (defined($type) && 
                   4644:          defined($rolenames{$type}) && 
                   4645:          defined($prp{$short}{$rolenames{$type}})) {
                   4646:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   4647:     } else {
                   4648:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   4649:     }
1.12      www      4650: }
                   4651: 
                   4652: # ----------------------------------------------------------------- Assign Role
                   4653: 
                   4654: sub assignrole {
1.357     www      4655:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
1.21      www      4656:     my $mrole;
                   4657:     if ($role =~ /^cr\//) {
1.393     www      4658:         my $cwosec=$url;
1.811     albertel 4659:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      4660: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      4661:            &logthis('Refused custom assignrole: '.
                   4662:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4663: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4664:            return 'refused'; 
                   4665:         }
1.21      www      4666:         $mrole='cr';
1.678     raeburn  4667:     } elsif ($role =~ /^gr\//) {
                   4668:         my $cwogrp=$url;
1.811     albertel 4669:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  4670:         unless (&allowed('mdg',$cwogrp)) {
                   4671:             &logthis('Refused group assignrole: '.
                   4672:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   4673:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   4674:             return 'refused';
                   4675:         }
                   4676:         $mrole='gr';
1.21      www      4677:     } else {
1.82      www      4678:         my $cwosec=$url;
1.811     albertel 4679:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.373     www      4680:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
1.104     www      4681:            &logthis('Refused assignrole: '.
                   4682:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4683: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4684:            return 'refused'; 
                   4685:         }
1.21      www      4686:         $mrole=$role;
                   4687:     }
1.620     albertel 4688:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4689:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      4690:     if ($end) { $command.='_'.$end; }
1.21      www      4691:     if ($start) {
                   4692: 	if ($end) { 
1.81      www      4693:            $command.='_'.$start; 
1.21      www      4694:         } else {
1.81      www      4695:            $command.='_0_'.$start;
1.21      www      4696:         }
                   4697:     }
1.739     raeburn  4698:     my $origstart = $start;
                   4699:     my $origend = $end;
1.357     www      4700: # actually delete
                   4701:     if ($deleteflag) {
1.373     www      4702: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      4703: # modify command to delete the role
1.620     albertel 4704:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      4705:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 4706: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      4707: # set start and finish to negative values for userrolelog
                   4708:            $start=-1;
                   4709:            $end=-1;
                   4710:         }
                   4711:     }
                   4712: # send command
1.349     www      4713:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      4714: # log new user role if status is ok
1.349     www      4715:     if ($answer eq 'ok') {
1.663     raeburn  4716: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  4717: # for course roles, perform group memberships changes triggered by role change.
                   4718:         unless ($role =~ /^gr/) {
                   4719:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   4720:                                              $origstart);
                   4721:         }
1.349     www      4722:     }
                   4723:     return $answer;
1.169     harris41 4724: }
                   4725: 
                   4726: # -------------------------------------------------- Modify user authentication
1.197     www      4727: # Overrides without validation
                   4728: 
1.169     harris41 4729: sub modifyuserauth {
                   4730:     my ($udom,$uname,$umode,$upass)=@_;
                   4731:     my $uhome=&homeserver($uname,$udom);
1.197     www      4732:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   4733:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 4734:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4735:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 4736:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   4737: 		     &escape($upass),$uhome);
1.620     albertel 4738:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      4739:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   4740:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   4741:     &log($udom,,$uname,$uhome,
1.620     albertel 4742:         'Authentication changed by '.$env{'user.domain'}.', '.
                   4743:                                      $env{'user.name'}.', '.$umode.
1.197     www      4744:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 4745:     unless ($reply eq 'ok') {
1.197     www      4746:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 4747: 	return 'error: '.$reply;
                   4748:     }   
1.170     harris41 4749:     return 'ok';
1.80      www      4750: }
                   4751: 
1.81      www      4752: # --------------------------------------------------------------- Modify a user
1.80      www      4753: 
1.81      www      4754: sub modifyuser {
1.206     matthew  4755:     my ($udom,    $uname, $uid,
                   4756:         $umode,   $upass, $first,
                   4757:         $middle,  $last,  $gene,
1.387     www      4758:         $forceid, $desiredhome, $email)=@_;
1.807     albertel 4759:     $udom= &LONCAPA::clean_domain($udom);
                   4760:     $uname=&LONCAPA::clean_username($uname);
1.81      www      4761:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4762:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  4763: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   4764:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   4765:                                      ' desiredhome not specified'). 
1.620     albertel 4766:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4767:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 4768:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      4769: # ----------------------------------------------------------------- Create User
1.406     albertel 4770:     if (($uhome eq 'no_host') && 
                   4771: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      4772:         my $unhome='';
1.209     matthew  4773:         if (defined($desiredhome) && $hostdom{$desiredhome} eq $udom) { 
                   4774:             $unhome = $desiredhome;
1.620     albertel 4775: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   4776: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  4777:         } else { # load balancing routine for determining $unhome
1.80      www      4778:             my $tryserver;
1.81      www      4779:             my $loadm=10000000;
1.80      www      4780:             foreach $tryserver (keys %libserv) {
                   4781: 	       if ($hostdom{$tryserver} eq $udom) {
                   4782:                   my $answer=reply('load',$tryserver);
                   4783:                   if (($answer=~/\d+/) && ($answer<$loadm)) {
                   4784: 		      $loadm=$answer;
                   4785:                       $unhome=$tryserver;
                   4786:                   }
                   4787: 	       }
                   4788: 	    }
                   4789:         }
                   4790:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  4791: 	    return 'error: unable to find a home server for '.$uname.
                   4792:                    ' in domain '.$udom;
1.80      www      4793:         }
                   4794:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   4795:                          &escape($upass),$unhome);
                   4796: 	unless ($reply eq 'ok') {
                   4797:             return 'error: '.$reply;
                   4798:         }   
1.230     stredwic 4799:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      4800:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  4801: 	    return 'error: unable verify users home machine.';
1.80      www      4802:         }
1.209     matthew  4803:     }   # End of creation of new user
1.80      www      4804: # ---------------------------------------------------------------------- Add ID
                   4805:     if ($uid) {
                   4806:        $uid=~tr/A-Z/a-z/;
                   4807:        my %uidhash=&idrget($udom,$uname);
1.196     www      4808:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   4809:          && (!$forceid)) {
1.80      www      4810: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  4811: 	      return 'error: user id "'.$uid.'" does not match '.
                   4812:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      4813:           }
                   4814:        } else {
                   4815: 	  &idput($udom,($uname => $uid));
                   4816:        }
                   4817:     }
                   4818: # -------------------------------------------------------------- Add names, etc
1.313     matthew  4819:     my @tmp=&get('environment',
1.134     albertel 4820: 		   ['firstname','middlename','lastname','generation'],
                   4821: 		   $udom,$uname);
1.313     matthew  4822:     my %names;
                   4823:     if ($tmp[0] =~ m/^error:.*/) { 
                   4824:         %names=(); 
                   4825:     } else {
                   4826:         %names = @tmp;
                   4827:     }
1.388     www      4828: #
                   4829: # Make sure to not trash student environment if instructor does not bother
                   4830: # to supply name and email information
                   4831: #
                   4832:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  4833:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      4834:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  4835:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      4836:     if ($email) {
                   4837:        $email=~s/[^\w\@\.\-\,]//gs;
                   4838:        if ($email=~/\@/) { $names{'notification'} = $email;
                   4839: 			   $names{'critnotification'} = $email;
                   4840: 			   $names{'permanentemail'} = $email; }
                   4841:     }
1.134     albertel 4842:     my $reply = &put('environment', \%names, $udom,$uname);
                   4843:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.680     www      4844:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.81      www      4845:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4846:              $umode.', '.$first.', '.$middle.', '.
                   4847: 	     $last.', '.$gene.' by '.
1.620     albertel 4848:              $env{'user.name'}.' at '.$env{'user.domain'});
1.134     albertel 4849:     return 'ok';
1.80      www      4850: }
                   4851: 
1.81      www      4852: # -------------------------------------------------------------- Modify student
1.80      www      4853: 
1.81      www      4854: sub modifystudent {
                   4855:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.515     raeburn  4856:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
1.455     albertel 4857:     if (!$cid) {
1.620     albertel 4858: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 4859: 	    return 'not_in_class';
                   4860: 	}
1.80      www      4861:     }
                   4862: # --------------------------------------------------------------- Make the user
1.81      www      4863:     my $reply=&modifyuser
1.209     matthew  4864: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      4865:          $desiredhome,$email);
1.80      www      4866:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  4867:     # This will cause &modify_student_enrollment to get the uid from the
                   4868:     # students environment
                   4869:     $uid = undef if (!$forceid);
1.455     albertel 4870:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.515     raeburn  4871: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
1.297     matthew  4872:     return $reply;
                   4873: }
                   4874: 
                   4875: sub modify_student_enrollment {
1.515     raeburn  4876:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
1.455     albertel 4877:     my ($cdom,$cnum,$chome);
                   4878:     if (!$cid) {
1.620     albertel 4879: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 4880: 	    return 'not_in_class';
                   4881: 	}
1.620     albertel 4882: 	$cdom=$env{'course.'.$cid.'.domain'};
                   4883: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 4884:     } else {
                   4885: 	($cdom,$cnum)=split(/_/,$cid);
                   4886:     }
1.620     albertel 4887:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 4888:     if (!$chome) {
1.457     raeburn  4889: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  4890:     }
1.455     albertel 4891:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  4892:     # Make sure the user exists
1.81      www      4893:     my $uhome=&homeserver($uname,$udom);
                   4894:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   4895: 	return 'error: no such user';
                   4896:     }
1.297     matthew  4897:     # Get student data if we were not given enough information
                   4898:     if (!defined($first)  || $first  eq '' || 
                   4899:         !defined($last)   || $last   eq '' || 
                   4900:         !defined($uid)    || $uid    eq '' || 
                   4901:         !defined($middle) || $middle eq '' || 
                   4902:         !defined($gene)   || $gene   eq '') {
1.294     matthew  4903:         # They did not supply us with enough data to enroll the student, so
                   4904:         # we need to pick up more information.
1.297     matthew  4905:         my %tmp = &get('environment',
1.294     matthew  4906:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  4907:                        ,$udom,$uname);
                   4908: 
1.800     albertel 4909:         #foreach my $key (keys(%tmp)) {
                   4910:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 4911:         #}
1.294     matthew  4912:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   4913:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   4914:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  4915:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  4916:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   4917:     }
1.556     albertel 4918:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 4919:     my $reply=cput('classlist',
                   4920: 		   {"$uname:$udom" => 
1.515     raeburn  4921: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 4922: 		   $cdom,$cnum);
1.81      www      4923:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   4924: 	return 'error: '.$reply;
1.652     albertel 4925:     } else {
                   4926: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      4927:     }
1.297     matthew  4928:     # Add student role to user
1.83      www      4929:     my $uurl='/'.$cid;
1.81      www      4930:     $uurl=~s/\_/\//g;
                   4931:     if ($usec) {
                   4932: 	$uurl.='/'.$usec;
                   4933:     }
                   4934:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21      www      4935: }
                   4936: 
1.556     albertel 4937: sub format_name {
                   4938:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   4939:     my $name;
                   4940:     if ($first ne 'lastname') {
                   4941: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   4942:     } else {
                   4943: 	if ($lastname=~/\S/) {
                   4944: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   4945: 	    $name=~s/\s+,/,/;
                   4946: 	} else {
                   4947: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   4948: 	}
                   4949:     }
                   4950:     $name=~s/^\s+//;
                   4951:     $name=~s/\s+$//;
                   4952:     $name=~s/\s+/ /g;
                   4953:     return $name;
                   4954: }
                   4955: 
1.84      www      4956: # ------------------------------------------------- Write to course preferences
                   4957: 
                   4958: sub writecoursepref {
                   4959:     my ($courseid,%prefs)=@_;
                   4960:     $courseid=~s/^\///;
                   4961:     $courseid=~s/\_/\//g;
                   4962:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   4963:     my $chome=homeserver($cnum,$cdomain);
                   4964:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   4965: 	return 'error: no such course';
                   4966:     }
                   4967:     my $cstring='';
1.800     albertel 4968:     foreach my $pref (keys(%prefs)) {
                   4969: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 4970:     }
1.84      www      4971:     $cstring=~s/\&$//;
                   4972:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   4973: }
                   4974: 
                   4975: # ---------------------------------------------------------- Make/modify course
                   4976: 
                   4977: sub createcourse {
1.741     raeburn  4978:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
                   4979:         $course_owner,$crstype)=@_;
1.84      www      4980:     $url=&declutter($url);
                   4981:     my $cid='';
1.264     matthew  4982:     unless (&allowed('ccc',$udom)) {
1.84      www      4983:         return 'refused';
                   4984:     }
                   4985: # ------------------------------------------------------------------- Create ID
1.674     www      4986:    my $uname=int(1+rand(9)).
                   4987:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   4988:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      4989:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   4990: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 4991:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      4992:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   4993:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   4994:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 4995:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      4996:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   4997:            return 'error: unable to generate unique course-ID';
                   4998:        } 
                   4999:    }
1.264     matthew  5000: # ------------------------------------------------ Check supplied server name
1.620     albertel 5001:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.264     matthew  5002:     if (! exists($libserv{$course_server})) {
                   5003:         return 'error:bad server name '.$course_server;
                   5004:     }
1.84      www      5005: # ------------------------------------------------------------- Make the course
                   5006:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  5007:                       $course_server);
1.84      www      5008:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 5009:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      5010:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5011: 	return 'error: no such course';
                   5012:     }
1.271     www      5013: # ----------------------------------------------------------------- Course made
1.516     raeburn  5014: # log existence
                   5015:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
1.741     raeburn  5016:                  ':'.&escape($inst_code).':'.&escape($course_owner).':'.
                   5017:                   &escape($crstype),$uhome);
1.358     www      5018:     &flushcourselogs();
                   5019: # set toplevel url
1.271     www      5020:     my $topurl=$url;
                   5021:     unless ($nonstandard) {
                   5022: # ------------------------------------------ For standard courses, make top url
                   5023:         my $mapurl=&clutter($url);
1.278     www      5024:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 5025:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      5026: <map>
                   5027: <resource id="1" type="start"></resource>
                   5028: <resource id="2" src="$mapurl"></resource>
                   5029: <resource id="3" type="finish"></resource>
                   5030: <link index="1" from="1" to="2"></link>
                   5031: <link index="2" from="2" to="3"></link>
                   5032: </map>
                   5033: ENDINITMAP
                   5034:         $topurl=&declutter(
1.638     albertel 5035:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      5036:                           );
                   5037:     }
                   5038: # ----------------------------------------------------------- Write preferences
1.84      www      5039:     &writecoursepref($udom.'_'.$uname,
                   5040:                      ('description' => $description,
1.271     www      5041:                       'url'         => $topurl));
1.84      www      5042:     return '/'.$udom.'/'.$uname;
                   5043: }
                   5044: 
1.813     albertel 5045: sub is_course {
                   5046:     my ($cdom,$cnum) = @_;
                   5047:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
                   5048: 				undef,'.');
                   5049:     if (exists($courses{$cdom.'_'.$cnum})) {
                   5050:         return 1;
                   5051:     }
                   5052:     return 0;
                   5053: }
                   5054: 
1.21      www      5055: # ---------------------------------------------------------- Assign Custom Role
                   5056: 
                   5057: sub assigncustomrole {
1.357     www      5058:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21      www      5059:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357     www      5060:                        $end,$start,$deleteflag);
1.21      www      5061: }
                   5062: 
                   5063: # ----------------------------------------------------------------- Revoke Role
                   5064: 
                   5065: sub revokerole {
1.357     www      5066:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21      www      5067:     my $now=time;
1.357     www      5068:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21      www      5069: }
                   5070: 
                   5071: # ---------------------------------------------------------- Revoke Custom Role
                   5072: 
                   5073: sub revokecustomrole {
1.357     www      5074:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21      www      5075:     my $now=time;
1.357     www      5076:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
                   5077:            $deleteflag);
1.17      www      5078: }
                   5079: 
1.533     banghart 5080: # ------------------------------------------------------------ Disk usage
1.535     albertel 5081: sub diskusage {
1.533     banghart 5082:     my ($udom,$uname,$directoryRoot)=@_;
                   5083:     $directoryRoot =~ s/\/$//;
1.535     albertel 5084:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
1.514     albertel 5085:     return $listing;
1.512     banghart 5086: }
                   5087: 
1.566     banghart 5088: sub is_locked {
                   5089:     my ($file_name, $domain, $user) = @_;
                   5090:     my @check;
                   5091:     my $is_locked;
                   5092:     push @check, $file_name;
1.613     albertel 5093:     my %locked = &get('file_permissions',\@check,
1.620     albertel 5094: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 5095:     my ($tmp)=keys(%locked);
                   5096:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  5097:     
1.566     banghart 5098:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  5099:         $is_locked = 'false';
                   5100:         foreach my $entry (@{$locked{$file_name}}) {
                   5101:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  5102:                $is_locked = 'true';
                   5103:                last;
1.745     raeburn  5104:            }
                   5105:        }
1.566     banghart 5106:     } else {
                   5107:         $is_locked = 'false';
                   5108:     }
                   5109: }
                   5110: 
1.759     albertel 5111: sub declutter_portfile {
                   5112:     my ($file) = @_;
                   5113:     &logthis("got $file");
                   5114:     $file =~ s-^(/portfolio/|portfolio/)-/-;
                   5115:     &logthis("ret $file");
                   5116:     return $file;
                   5117: }
                   5118: 
1.559     banghart 5119: # ------------------------------------------------------------- Mark as Read Only
                   5120: 
                   5121: sub mark_as_readonly {
                   5122:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 5123:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5124:     my ($tmp)=keys(%current_permissions);
                   5125:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 5126:     foreach my $file (@{$files}) {
1.759     albertel 5127: 	$file = &declutter_portfile($file);
1.561     banghart 5128:         push(@{$current_permissions{$file}},$what);
1.559     banghart 5129:     }
1.613     albertel 5130:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5131:     return;
                   5132: }
                   5133: 
1.572     banghart 5134: # ------------------------------------------------------------Save Selected Files
                   5135: 
                   5136: sub save_selected_files {
                   5137:     my ($user, $path, @files) = @_;
                   5138:     my $filename = $user."savedfiles";
1.573     banghart 5139:     my @other_files = &files_not_in_path($user, $path);
1.574     banghart 5140:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 5141:     foreach my $file (@files) {
1.620     albertel 5142:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 5143:     }
                   5144:     foreach my $file (@other_files) {
1.574     banghart 5145:         print (OUT $file."\n");
1.572     banghart 5146:     }
1.574     banghart 5147:     close (OUT);
1.572     banghart 5148:     return 'ok';
                   5149: }
                   5150: 
1.574     banghart 5151: sub clear_selected_files {
                   5152:     my ($user) = @_;
                   5153:     my $filename = $user."savedfiles";
                   5154:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5155:     print (OUT undef);
                   5156:     close (OUT);
                   5157:     return ("ok");    
                   5158: }
                   5159: 
1.572     banghart 5160: sub files_in_path {
                   5161:     my ($user, $path) = @_;
                   5162:     my $filename = $user."savedfiles";
                   5163:     my %return_files;
1.574     banghart 5164:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 5165:     while (my $line_in = <IN>) {
1.574     banghart 5166:         chomp ($line_in);
                   5167:         my @paths_and_file = split (m!/!, $line_in);
                   5168:         my $file_part = pop (@paths_and_file);
                   5169:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 5170:         $path_part.='/';
                   5171:         my $path_and_file = $path_part.$file_part;
                   5172:         if ($path_part eq $path) {
                   5173:             $return_files{$file_part}= 'selected';
                   5174:         }
                   5175:     }
1.574     banghart 5176:     close (IN);
                   5177:     return (\%return_files);
1.572     banghart 5178: }
                   5179: 
                   5180: # called in portfolio select mode, to show files selected NOT in current directory
                   5181: sub files_not_in_path {
                   5182:     my ($user, $path) = @_;
                   5183:     my $filename = $user."savedfiles";
                   5184:     my @return_files;
                   5185:     my $path_part;
1.800     albertel 5186:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5187:     while (my $line = <IN>) {
1.572     banghart 5188:         #ok, I know it's clunky, but I want it to work
1.800     albertel 5189:         my @paths_and_file = split(m|/|, $line);
                   5190:         my $file_part = pop(@paths_and_file);
                   5191:         chomp($file_part);
                   5192:         my $path_part = join('/', @paths_and_file);
1.572     banghart 5193:         $path_part .= '/';
                   5194:         my $path_and_file = $path_part.$file_part;
                   5195:         if ($path_part ne $path) {
1.800     albertel 5196:             push(@return_files, ($path_and_file));
1.572     banghart 5197:         }
                   5198:     }
1.800     albertel 5199:     close(OUT);
1.574     banghart 5200:     return (@return_files);
1.572     banghart 5201: }
                   5202: 
1.745     raeburn  5203: #----------------------------------------------Get portfolio file permissions
1.629     banghart 5204: 
1.745     raeburn  5205: sub get_portfile_permissions {
                   5206:     my ($domain,$user) = @_;
1.613     albertel 5207:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5208:     my ($tmp)=keys(%current_permissions);
                   5209:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5210:     return \%current_permissions;
                   5211: }
                   5212: 
                   5213: #---------------------------------------------Get portfolio file access controls
                   5214: 
1.749     raeburn  5215: sub get_access_controls {
1.745     raeburn  5216:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 5217:     my %access;
                   5218:     my $real_file = $file;
                   5219:     $file =~ s/\.meta$//;
1.745     raeburn  5220:     if (defined($file)) {
1.749     raeburn  5221:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   5222:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 5223:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  5224:             }
                   5225:         }
1.745     raeburn  5226:     } else {
1.749     raeburn  5227:         foreach my $key (keys(%{$current_permissions})) {
                   5228:             if ($key =~ /\0accesscontrol$/) {
                   5229:                 if (defined($group)) {
                   5230:                     if ($key !~ m-^\Q$group\E/-) {
                   5231:                         next;
                   5232:                     }
                   5233:                 }
                   5234:                 my ($fullpath) = split(/\0/,$key);
                   5235:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   5236:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   5237:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   5238:                     }
                   5239:                 }
                   5240:             }
                   5241:         }
                   5242:     }
                   5243:     return %access;
                   5244: }
                   5245: 
                   5246: sub modify_access_controls {
                   5247:     my ($file_name,$changes,$domain,$user)=@_;
                   5248:     my ($outcome,$deloutcome);
                   5249:     my %store_permissions;
                   5250:     my %new_values;
                   5251:     my %new_control;
                   5252:     my %translation;
                   5253:     my @deletions = ();
                   5254:     my $now = time;
                   5255:     if (exists($$changes{'activate'})) {
                   5256:         if (ref($$changes{'activate'}) eq 'HASH') {
                   5257:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   5258:             my $numnew = scalar(@newitems);
                   5259:             for (my $i=0; $i<$numnew; $i++) {
                   5260:                 my $newkey = $newitems[$i];
                   5261:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  5262:                 if ($newkey =~ /^\d+:/) { 
                   5263:                     $newkey =~ s/^(\d+)/$newid/;
                   5264:                     $translation{$1} = $newid;
                   5265:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   5266:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   5267:                     $translation{$1} = $newid;
                   5268:                 }
1.749     raeburn  5269:                 $new_values{$file_name."\0".$newkey} = 
                   5270:                                           $$changes{'activate'}{$newitems[$i]};
                   5271:                 $new_control{$newkey} = $now;
                   5272:             }
                   5273:         }
                   5274:     }
                   5275:     my %todelete;
                   5276:     my %changed_items;
                   5277:     foreach my $action ('delete','update') {
                   5278:         if (exists($$changes{$action})) {
                   5279:             if (ref($$changes{$action}) eq 'HASH') {
                   5280:                 foreach my $key (keys(%{$$changes{$action}})) {
                   5281:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   5282:                     if ($action eq 'delete') { 
                   5283:                         $todelete{$itemnum} = 1;
                   5284:                     } else {
                   5285:                         $changed_items{$itemnum} = $key;
                   5286:                     }
                   5287:                 }
1.745     raeburn  5288:             }
                   5289:         }
1.749     raeburn  5290:     }
                   5291:     # get lock on access controls for file.
                   5292:     my $lockhash = {
                   5293:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   5294:                                                        ':'.$env{'user.domain'},
                   5295:                    }; 
                   5296:     my $tries = 0;
                   5297:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5298:    
                   5299:     while (($gotlock ne 'ok') && $tries <3) {
                   5300:         $tries ++;
                   5301:         sleep 1;
                   5302:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5303:     }
                   5304:     if ($gotlock eq 'ok') {
                   5305:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   5306:         my ($tmp)=keys(%curr_permissions);
                   5307:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   5308:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   5309:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   5310:             if (ref($curr_controls) eq 'HASH') {
                   5311:                 foreach my $control_item (keys(%{$curr_controls})) {
                   5312:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   5313:                     if (defined($todelete{$itemnum})) {
                   5314:                         push(@deletions,$file_name."\0".$control_item);
                   5315:                     } else {
                   5316:                         if (defined($changed_items{$itemnum})) {
                   5317:                             $new_control{$changed_items{$itemnum}} = $now;
                   5318:                             push(@deletions,$file_name."\0".$control_item);
                   5319:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   5320:                         } else {
                   5321:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   5322:                         }
                   5323:                     }
1.745     raeburn  5324:                 }
                   5325:             }
                   5326:         }
1.749     raeburn  5327:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   5328:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   5329:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   5330:         #  remove lock
                   5331:         my @del_lock = ($file_name."\0".'locked_access_records');
                   5332:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  5333:         my ($file,$group);
                   5334:         if (&is_course($domain,$user)) {
                   5335:             ($group,$file) = split(/\//,$file_name,2);
                   5336:         } else {
                   5337:             $file = $file_name;
                   5338:         }
                   5339:         my $sqlresult =
                   5340:             &update_portfolio_table($user,$domain,$file,'portfolio_access',
                   5341:                                     $group);
1.749     raeburn  5342:     } else {
                   5343:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  5344:     }
1.749     raeburn  5345:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  5346: }
                   5347: 
1.827     raeburn  5348: sub make_public_indefinitely {
                   5349:     my ($requrl) = @_;
                   5350:     my $now = time;
                   5351:     my $action = 'activate';
                   5352:     my $aclnum = 0;
                   5353:     if (&is_portfolio_url($requrl)) {
                   5354:         my (undef,$udom,$unum,$file_name,$group) =
                   5355:             &parse_portfolio_url($requrl);
                   5356:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   5357:         my %access_controls = &get_access_controls($current_perms,
                   5358:                                                    $group,$file_name);
                   5359:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   5360:             my ($num,$scope,$end,$start) = 
                   5361:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   5362:             if ($scope eq 'public') {
                   5363:                 if ($start <= $now && $end == 0) {
                   5364:                     $action = 'none';
                   5365:                 } else {
                   5366:                     $action = 'update';
                   5367:                     $aclnum = $num;
                   5368:                 }
                   5369:                 last;
                   5370:             }
                   5371:         }
                   5372:         if ($action eq 'none') {
                   5373:              return 'ok';
                   5374:         } else {
                   5375:             my %changes;
                   5376:             my $newend = 0;
                   5377:             my $newstart = $now;
                   5378:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   5379:             $changes{$action}{$newkey} = {
                   5380:                 type => 'public',
                   5381:                 time => {
                   5382:                     start => $newstart,
                   5383:                     end   => $newend,
                   5384:                 },
                   5385:             };
                   5386:             my ($outcome,$deloutcome,$new_values,$translation) =
                   5387:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   5388:             return $outcome;
                   5389:         }
                   5390:     } else {
                   5391:         return 'invalid';
                   5392:     }
                   5393: }
                   5394: 
1.745     raeburn  5395: #------------------------------------------------------Get Marked as Read Only
                   5396: 
                   5397: sub get_marked_as_readonly {
                   5398:     my ($domain,$user,$what,$group) = @_;
                   5399:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 5400:     my @readonly_files;
1.629     banghart 5401:     my $cmp1=$what;
                   5402:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  5403:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5404:         if (defined($group)) {
                   5405:             if ($file_name !~ m-^\Q$group\E/-) {
                   5406:                 next;
                   5407:             }
                   5408:         }
1.561     banghart 5409:         if (ref($value) eq "ARRAY"){
                   5410:             foreach my $stored_what (@{$value}) {
1.629     banghart 5411:                 my $cmp2=$stored_what;
1.759     albertel 5412:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  5413:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  5414:                 }
1.629     banghart 5415:                 if ($cmp1 eq $cmp2) {
1.561     banghart 5416:                     push(@readonly_files, $file_name);
1.745     raeburn  5417:                     last;
1.563     banghart 5418:                 } elsif (!defined($what)) {
                   5419:                     push(@readonly_files, $file_name);
1.745     raeburn  5420:                     last;
1.561     banghart 5421:                 }
                   5422:             }
1.745     raeburn  5423:         }
1.561     banghart 5424:     }
                   5425:     return @readonly_files;
                   5426: }
1.577     banghart 5427: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 5428: 
1.577     banghart 5429: sub get_marked_as_readonly_hash {
1.745     raeburn  5430:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 5431:     my %readonly_files;
1.745     raeburn  5432:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5433:         if (defined($group)) {
                   5434:             if ($file_name !~ m-^\Q$group\E/-) {
                   5435:                 next;
                   5436:             }
                   5437:         }
1.577     banghart 5438:         if (ref($value) eq "ARRAY"){
                   5439:             foreach my $stored_what (@{$value}) {
1.745     raeburn  5440:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 5441:                     foreach my $lock_descriptor(@{$stored_what}) {
                   5442:                         if ($lock_descriptor eq 'graded') {
                   5443:                             $readonly_files{$file_name} = 'graded';
                   5444:                         } elsif ($lock_descriptor eq 'handback') {
                   5445:                             $readonly_files{$file_name} = 'handback';
                   5446:                         } else {
                   5447:                             if (!exists($readonly_files{$file_name})) {
                   5448:                                 $readonly_files{$file_name} = 'locked';
                   5449:                             }
                   5450:                         }
1.745     raeburn  5451:                     }
1.750     banghart 5452:                 } 
1.577     banghart 5453:             }
                   5454:         } 
                   5455:     }
                   5456:     return %readonly_files;
                   5457: }
1.559     banghart 5458: # ------------------------------------------------------------ Unmark as Read Only
                   5459: 
                   5460: sub unmark_as_readonly {
1.629     banghart 5461:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   5462:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  5463:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 5464:     $file_name = &declutter_portfile($file_name);
1.634     albertel 5465:     my $symb_crs = $what;
                   5466:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  5467:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 5468:     my ($tmp)=keys(%current_permissions);
                   5469:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5470:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 5471:     foreach my $file (@readonly_files) {
1.759     albertel 5472: 	my $clean_file = &declutter_portfile($file);
                   5473: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 5474: 	my $current_locks = $current_permissions{$file};
1.563     banghart 5475:         my @new_locks;
                   5476:         my @del_keys;
                   5477:         if (ref($current_locks) eq "ARRAY"){
                   5478:             foreach my $locker (@{$current_locks}) {
1.632     albertel 5479:                 my $compare=$locker;
1.749     raeburn  5480:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  5481:                     $compare=join('',@{$locker});
1.746     raeburn  5482:                     if ($compare ne $symb_crs) {
                   5483:                         push(@new_locks, $locker);
                   5484:                     }
1.563     banghart 5485:                 }
                   5486:             }
1.650     albertel 5487:             if (scalar(@new_locks) > 0) {
1.563     banghart 5488:                 $current_permissions{$file} = \@new_locks;
                   5489:             } else {
                   5490:                 push(@del_keys, $file);
1.613     albertel 5491:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 5492:                 delete($current_permissions{$file});
1.563     banghart 5493:             }
                   5494:         }
1.561     banghart 5495:     }
1.613     albertel 5496:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5497:     return;
                   5498: }
1.512     banghart 5499: 
1.17      www      5500: # ------------------------------------------------------------ Directory lister
                   5501: 
                   5502: sub dirlist {
1.253     stredwic 5503:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
                   5504: 
1.18      www      5505:     $uri=~s/^\///;
                   5506:     $uri=~s/\/$//;
1.253     stredwic 5507:     my ($udom, $uname);
                   5508:     (undef,$udom,$uname)=split(/\//,$uri);
                   5509:     if(defined($userdomain)) {
                   5510:         $udom = $userdomain;
                   5511:     }
                   5512:     if(defined($username)) {
                   5513:         $uname = $username;
                   5514:     }
                   5515: 
                   5516:     my $dirRoot = $perlvar{'lonDocRoot'};
                   5517:     if(defined($alternateDirectoryRoot)) {
                   5518:         $dirRoot = $alternateDirectoryRoot;
                   5519:         $dirRoot =~ s/\/$//;
1.751     banghart 5520:     }
1.253     stredwic 5521: 
                   5522:     if($udom) {
                   5523:         if($uname) {
1.800     albertel 5524:             my $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   5525: 				 &homeserver($uname,$udom));
1.605     matthew  5526:             my @listing_results;
                   5527:             if ($listing eq 'unknown_cmd') {
1.800     albertel 5528:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   5529: 				  &homeserver($uname,$udom));
1.605     matthew  5530:                 @listing_results = split(/:/,$listing);
                   5531:             } else {
                   5532:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   5533:             }
                   5534:             return @listing_results;
1.253     stredwic 5535:         } elsif(!defined($alternateDirectoryRoot)) {
1.800     albertel 5536:             my %allusers;
                   5537:             foreach my $tryserver (keys(%libserv)) {
1.253     stredwic 5538:                 if($hostdom{$tryserver} eq $udom) {
1.800     albertel 5539:                     my $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   5540: 					 $udom, $tryserver);
1.605     matthew  5541:                     my @listing_results;
                   5542:                     if ($listing eq 'unknown_cmd') {
1.800     albertel 5543:                         $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   5544: 					  $udom, $tryserver);
1.605     matthew  5545:                         @listing_results = split(/:/,$listing);
                   5546:                     } else {
                   5547:                         @listing_results =
                   5548:                             map { &unescape($_); } split(/:/,$listing);
                   5549:                     }
                   5550:                     if ($listing_results[0] ne 'no_such_dir' && 
                   5551:                         $listing_results[0] ne 'empty'       &&
                   5552:                         $listing_results[0] ne 'con_lost') {
1.800     albertel 5553:                         foreach my $line (@listing_results) {
                   5554:                             my ($entry) = split(/&/,$line,2);
                   5555:                             $allusers{$entry} = 1;
1.253     stredwic 5556:                         }
                   5557:                     }
1.191     harris41 5558:                 }
1.253     stredwic 5559:             }
                   5560:             my $alluserstr='';
1.800     albertel 5561:             foreach my $user (sort(keys(%allusers))) {
                   5562:                 $alluserstr.=$user.'&user:';
1.253     stredwic 5563:             }
                   5564:             $alluserstr=~s/:$//;
                   5565:             return split(/:/,$alluserstr);
                   5566:         } else {
1.800     albertel 5567:             return ('missing user name');
1.253     stredwic 5568:         }
                   5569:     } elsif(!defined($alternateDirectoryRoot)) {
                   5570:         my $tryserver;
                   5571:         my %alldom=();
1.800     albertel 5572:         foreach $tryserver (keys(%libserv)) {
1.253     stredwic 5573:             $alldom{$hostdom{$tryserver}}=1;
                   5574:         }
                   5575:         my $alldomstr='';
1.800     albertel 5576:         foreach my $domain (sort(keys(%alldom))) {
                   5577:             $alldomstr.=$perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain:';
1.253     stredwic 5578:         }
                   5579:         $alldomstr=~s/:$//;
                   5580:         return split(/:/,$alldomstr);       
                   5581:     } else {
1.800     albertel 5582:         return ('missing domain');
1.275     stredwic 5583:     }
                   5584: }
                   5585: 
                   5586: # --------------------------------------------- GetFileTimestamp
                   5587: # This function utilizes dirlist and returns the date stamp for
                   5588: # when it was last modified.  It will also return an error of -1
                   5589: # if an error occurs
                   5590: 
1.410     matthew  5591: ##
                   5592: ## FIXME: This subroutine assumes its caller knows something about the
                   5593: ## directory structure of the home server for the student ($root).
                   5594: ## Not a good assumption to make.  Since this is for looking up files
                   5595: ## in user directories, the full path should be constructed by lond, not
                   5596: ## whatever machine we request data from.
                   5597: ##
1.275     stredwic 5598: sub GetFileTimestamp {
                   5599:     my ($studentDomain,$studentName,$filename,$root)=@_;
1.807     albertel 5600:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   5601:     $studentName   = &LONCAPA::clean_username($studentName);
1.275     stredwic 5602:     my $subdir=$studentName.'__';
                   5603:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   5604:     my $proname="$studentDomain/$subdir/$studentName";
                   5605:     $proname .= '/'.$filename;
1.375     matthew  5606:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
                   5607:                                               $studentName, $root);
1.275     stredwic 5608:     my @stats = split('&', $fileStat);
                   5609:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  5610:         # @stats contains first the filename, then the stat output
                   5611:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 5612:     } else {
                   5613:         return -1;
1.253     stredwic 5614:     }
1.26      www      5615: }
                   5616: 
1.712     albertel 5617: sub stat_file {
                   5618:     my ($uri) = @_;
1.787     albertel 5619:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 5620: 
1.712     albertel 5621:     my ($udom,$uname,$file,$dir);
                   5622:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   5623: 	($udom,$uname,$file) =
1.811     albertel 5624: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 5625: 	$file = 'userfiles/'.$file;
1.740     www      5626: 	$dir = &propath($udom,$uname);
1.712     albertel 5627:     }
                   5628:     if ($uri =~ m-^/res/-) {
                   5629: 	($udom,$uname) = 
1.807     albertel 5630: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 5631: 	$file = $uri;
                   5632:     }
                   5633: 
                   5634:     if (!$udom || !$uname || !$file) {
                   5635: 	# unable to handle the uri
                   5636: 	return ();
                   5637:     }
                   5638: 
                   5639:     my ($result) = &dirlist($file,$udom,$uname,$dir);
                   5640:     my @stats = split('&', $result);
1.721     banghart 5641:     
1.712     albertel 5642:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   5643: 	shift(@stats); #filename is first
                   5644: 	return @stats;
                   5645:     }
                   5646:     return ();
                   5647: }
                   5648: 
1.26      www      5649: # -------------------------------------------------------- Value of a Condition
                   5650: 
1.713     albertel 5651: # gets the value of a specific preevaluated condition
                   5652: #    stored in the string  $env{user.state.<cid>}
                   5653: # or looks up a condition reference in the bighash and if if hasn't
                   5654: # already been evaluated recurses into docondval to get the value of
                   5655: # the condition, then memoizing it to 
                   5656: #   $env{user.state.<cid>.<condition>}
1.40      www      5657: sub directcondval {
                   5658:     my $number=shift;
1.620     albertel 5659:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 5660: 	&Apache::lonuserstate::evalstate();
                   5661:     }
1.713     albertel 5662:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   5663: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   5664:     } elsif ($number =~ /^_/) {
                   5665: 	my $sub_condition;
                   5666: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   5667: 		&GDBM_READER(),0640)) {
                   5668: 	    $sub_condition=$bighash{'conditions'.$number};
                   5669: 	    untie(%bighash);
                   5670: 	}
                   5671: 	my $value = &docondval($sub_condition);
                   5672: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
                   5673: 	return $value;
                   5674:     }
1.620     albertel 5675:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   5676:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      5677:     } else {
                   5678:        return 2;
                   5679:     }
                   5680: }
                   5681: 
1.713     albertel 5682: # get the collection of conditions for this resource
1.26      www      5683: sub condval {
                   5684:     my $condidx=shift;
1.54      www      5685:     my $allpathcond='';
1.713     albertel 5686:     foreach my $cond (split(/\|/,$condidx)) {
                   5687: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   5688: 	    $allpathcond.=
                   5689: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   5690: 	}
1.191     harris41 5691:     }
1.54      www      5692:     $allpathcond=~s/\|$//;
1.713     albertel 5693:     return &docondval($allpathcond);
                   5694: }
                   5695: 
                   5696: #evaluates an expression of conditions
                   5697: sub docondval {
                   5698:     my ($allpathcond) = @_;
                   5699:     my $result=0;
                   5700:     if ($env{'request.course.id'}
                   5701: 	&& defined($allpathcond)) {
                   5702: 	my $operand='|';
                   5703: 	my @stack;
                   5704: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   5705: 	    if ($chunk eq '(') {
                   5706: 		push @stack,($operand,$result);
                   5707: 	    } elsif ($chunk eq ')') {
                   5708: 		my $before=pop @stack;
                   5709: 		if (pop @stack eq '&') {
                   5710: 		    $result=$result>$before?$before:$result;
                   5711: 		} else {
                   5712: 		    $result=$result>$before?$result:$before;
                   5713: 		}
                   5714: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   5715: 		$operand=$chunk;
                   5716: 	    } else {
                   5717: 		my $new=directcondval($chunk);
                   5718: 		if ($operand eq '&') {
                   5719: 		    $result=$result>$new?$new:$result;
                   5720: 		} else {
                   5721: 		    $result=$result>$new?$result:$new;
                   5722: 		}
                   5723: 	    }
                   5724: 	}
1.26      www      5725:     }
                   5726:     return $result;
1.421     albertel 5727: }
                   5728: 
                   5729: # ---------------------------------------------------- Devalidate courseresdata
                   5730: 
                   5731: sub devalidatecourseresdata {
                   5732:     my ($coursenum,$coursedomain)=@_;
                   5733:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 5734:     &devalidate_cache_new('courseres',$hashid);
1.28      www      5735: }
                   5736: 
1.763     www      5737: 
1.200     www      5738: # --------------------------------------------------- Course Resourcedata Query
                   5739: 
1.624     albertel 5740: sub get_courseresdata {
                   5741:     my ($coursenum,$coursedomain)=@_;
1.200     www      5742:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   5743:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 5744:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 5745:     my %dumpreply;
1.417     albertel 5746:     unless (defined($cached)) {
1.624     albertel 5747: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 5748: 	$result=\%dumpreply;
1.251     albertel 5749: 	my ($tmp) = keys(%dumpreply);
                   5750: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 5751: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 5752: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   5753: 	    return $tmp;
1.416     albertel 5754: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 5755: 	    $result=undef;
1.599     albertel 5756: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 5757: 	}
                   5758:     }
1.624     albertel 5759:     return $result;
                   5760: }
                   5761: 
1.633     albertel 5762: sub devalidateuserresdata {
                   5763:     my ($uname,$udom)=@_;
                   5764:     my $hashid="$udom:$uname";
                   5765:     &devalidate_cache_new('userres',$hashid);
                   5766: }
                   5767: 
1.624     albertel 5768: sub get_userresdata {
                   5769:     my ($uname,$udom)=@_;
                   5770:     #most student don\'t have any data set, check if there is some data
                   5771:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   5772: 
                   5773:     my $hashid="$udom:$uname";
                   5774:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   5775:     if (!defined($cached)) {
                   5776: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   5777: 	$result=\%resourcedata;
                   5778: 	&do_cache_new('userres',$hashid,$result,600);
                   5779:     }
                   5780:     my ($tmp)=keys(%$result);
                   5781:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   5782: 	return $result;
                   5783:     }
                   5784:     #error 2 occurs when the .db doesn't exist
                   5785:     if ($tmp!~/error: 2 /) {
1.672     albertel 5786: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 5787: 		 " Trying to get resource data for ".
                   5788: 		 $uname." at ".$udom.": ".
                   5789: 		 $tmp."</font>");
                   5790:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 5791: 	#&EXT_cache_set($udom,$uname);
                   5792: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 5793: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 5794:     }
                   5795:     return $tmp;
                   5796: }
                   5797: 
                   5798: sub resdata {
                   5799:     my ($name,$domain,$type,@which)=@_;
                   5800:     my $result;
                   5801:     if ($type eq 'course') {
                   5802: 	$result=&get_courseresdata($name,$domain);
                   5803:     } elsif ($type eq 'user') {
                   5804: 	$result=&get_userresdata($name,$domain);
                   5805:     }
                   5806:     if (!ref($result)) { return $result; }    
1.251     albertel 5807:     foreach my $item (@which) {
1.417     albertel 5808: 	if (defined($result->{$item})) {
                   5809: 	    return $result->{$item};
1.251     albertel 5810: 	}
1.250     albertel 5811:     }
1.291     albertel 5812:     return undef;
1.200     www      5813: }
                   5814: 
1.379     matthew  5815: #
                   5816: # EXT resource caching routines
                   5817: #
                   5818: 
                   5819: sub clear_EXT_cache_status {
1.383     albertel 5820:     &delenv('cache.EXT.');
1.379     matthew  5821: }
                   5822: 
                   5823: sub EXT_cache_status {
                   5824:     my ($target_domain,$target_user) = @_;
1.383     albertel 5825:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 5826:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  5827:         # We know already the user has no data
                   5828:         return 1;
                   5829:     } else {
                   5830:         return 0;
                   5831:     }
                   5832: }
                   5833: 
                   5834: sub EXT_cache_set {
                   5835:     my ($target_domain,$target_user) = @_;
1.383     albertel 5836:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.633     albertel 5837:     #&appenv($cachename => time);
1.379     matthew  5838: }
                   5839: 
1.28      www      5840: # --------------------------------------------------------- Value of a Variable
1.58      www      5841: sub EXT {
1.715     albertel 5842: 
1.395     albertel 5843:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      5844:     unless ($varname) { return ''; }
1.218     albertel 5845:     #get real user name/domain, courseid and symb
                   5846:     my $courseid;
1.359     albertel 5847:     my $publicuser;
1.427     www      5848:     if ($symbparm) {
                   5849: 	$symbparm=&get_symb_from_alias($symbparm);
                   5850:     }
1.218     albertel 5851:     if (!($uname && $udom)) {
1.790     albertel 5852:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 5853:       if (!$symbparm) {	$symbparm=$cursymb; }
                   5854:     } else {
1.620     albertel 5855: 	$courseid=$env{'request.course.id'};
1.218     albertel 5856:     }
1.48      www      5857:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   5858:     my $rest;
1.320     albertel 5859:     if (defined($therest[0])) {
1.48      www      5860:        $rest=join('.',@therest);
                   5861:     } else {
                   5862:        $rest='';
                   5863:     }
1.320     albertel 5864: 
1.57      www      5865:     my $qualifierrest=$qualifier;
                   5866:     if ($rest) { $qualifierrest.='.'.$rest; }
                   5867:     my $spacequalifierrest=$space;
                   5868:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      5869:     if ($realm eq 'user') {
1.48      www      5870: # --------------------------------------------------------------- user.resource
                   5871: 	if ($space eq 'resource') {
1.651     albertel 5872: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   5873: 		  || defined($Apache::lonhomework::parsing_a_task))
                   5874: 		 &&
1.744     albertel 5875: 		 ($symbparm eq &symbread()) ) {	
                   5876: 		# if we are in the middle of processing the resource the
                   5877: 		# get the value we are planning on committing
                   5878:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   5879:                     return $Apache::lonhomework::results{$qualifierrest};
                   5880:                 } else {
                   5881:                     return $Apache::lonhomework::history{$qualifierrest};
                   5882:                 }
1.335     albertel 5883: 	    } else {
1.359     albertel 5884: 		my %restored;
1.620     albertel 5885: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 5886: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   5887: 		} else {
                   5888: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   5889: 		}
1.335     albertel 5890: 		return $restored{$qualifierrest};
                   5891: 	    }
1.48      www      5892: # ----------------------------------------------------------------- user.access
                   5893:         } elsif ($space eq 'access') {
1.218     albertel 5894: 	    # FIXME - not supporting calls for a specific user
1.48      www      5895:             return &allowed($qualifier,$rest);
                   5896: # ------------------------------------------ user.preferences, user.environment
                   5897:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 5898: 	    if (($uname eq $env{'user.name'}) &&
                   5899: 		($udom eq $env{'user.domain'})) {
                   5900: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 5901: 	    } else {
1.359     albertel 5902: 		my %returnhash;
                   5903: 		if (!$publicuser) {
                   5904: 		    %returnhash=&userenvironment($udom,$uname,
                   5905: 						 $qualifierrest);
                   5906: 		}
1.218     albertel 5907: 		return $returnhash{$qualifierrest};
                   5908: 	    }
1.48      www      5909: # ----------------------------------------------------------------- user.course
                   5910:         } elsif ($space eq 'course') {
1.218     albertel 5911: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 5912:             return $env{join('.',('request.course',$qualifier))};
1.48      www      5913: # ------------------------------------------------------------------- user.role
                   5914:         } elsif ($space eq 'role') {
1.218     albertel 5915: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 5916:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      5917:             if ($qualifier eq 'value') {
                   5918: 		return $role;
                   5919:             } elsif ($qualifier eq 'extent') {
                   5920:                 return $where;
                   5921:             }
                   5922: # ----------------------------------------------------------------- user.domain
                   5923:         } elsif ($space eq 'domain') {
1.218     albertel 5924:             return $udom;
1.48      www      5925: # ------------------------------------------------------------------- user.name
                   5926:         } elsif ($space eq 'name') {
1.218     albertel 5927:             return $uname;
1.48      www      5928: # ---------------------------------------------------- Any other user namespace
1.29      www      5929:         } else {
1.359     albertel 5930: 	    my %reply;
                   5931: 	    if (!$publicuser) {
                   5932: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   5933: 	    }
                   5934: 	    return $reply{$qualifierrest};
1.48      www      5935:         }
1.236     www      5936:     } elsif ($realm eq 'query') {
                   5937: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 5938:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   5939: 						[$spacequalifierrest]);
1.620     albertel 5940: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      5941:    } elsif ($realm eq 'request') {
1.48      www      5942: # ------------------------------------------------------------- request.browser
                   5943:         if ($space eq 'browser') {
1.430     www      5944: 	    if ($qualifier eq 'textremote') {
1.676     albertel 5945: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      5946: 		    return 1;
                   5947: 		} else {
                   5948: 		    return 0;
                   5949: 		}
                   5950: 	    } else {
1.620     albertel 5951: 		return $env{'browser.'.$qualifier};
1.430     www      5952: 	    }
1.57      www      5953: # ------------------------------------------------------------ request.filename
                   5954:         } else {
1.620     albertel 5955:             return $env{'request.'.$spacequalifierrest};
1.29      www      5956:         }
1.28      www      5957:     } elsif ($realm eq 'course') {
1.48      www      5958: # ---------------------------------------------------------- course.description
1.620     albertel 5959:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      5960:     } elsif ($realm eq 'resource') {
1.165     www      5961: 
1.620     albertel 5962: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 5963: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   5964: 	}
1.693     albertel 5965: 
                   5966: 	if ($space eq 'title') {
                   5967: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   5968: 	    return &gettitle($symbparm);
                   5969: 	}
                   5970: 	
                   5971: 	if ($space eq 'map') {
                   5972: 	    my ($map) = &decode_symb($symbparm);
                   5973: 	    return &symbread($map);
                   5974: 	}
                   5975: 
                   5976: 	my ($section, $group, @groups);
1.593     albertel 5977: 	my ($courselevelm,$courselevel);
1.539     albertel 5978: 	if ($symbparm && defined($courseid) && 
1.620     albertel 5979: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      5980: 
1.218     albertel 5981: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      5982: 
1.60      www      5983: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 5984: 	    my $symbp=$symbparm;
1.735     albertel 5985: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 5986: 
                   5987: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   5988: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   5989: 
1.620     albertel 5990: 	    if (($env{'user.name'} eq $uname) &&
                   5991: 		($env{'user.domain'} eq $udom)) {
                   5992: 		$section=$env{'request.course.sec'};
1.733     raeburn  5993:                 @groups = split(/:/,$env{'request.course.groups'});  
                   5994:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 5995: 	    } else {
1.539     albertel 5996: 		if (! defined($usection)) {
1.551     albertel 5997: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 5998: 		} else {
                   5999: 		    $section = $usection;
                   6000: 		}
1.733     raeburn  6001:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 6002: 	    }
                   6003: 
                   6004: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   6005: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   6006: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   6007: 
1.593     albertel 6008: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 6009: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 6010: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      6011: 
1.60      www      6012: # ----------------------------------------------------------- first, check user
1.624     albertel 6013: 
                   6014: 	    my $userreply=&resdata($uname,$udom,'user',
                   6015: 				       ($courselevelr,$courselevelm,
                   6016: 					$courselevel));
                   6017: 	    if (defined($userreply)) { return $userreply; }
1.95      www      6018: 
1.594     albertel 6019: # ------------------------------------------------ second, check some of course
1.684     raeburn  6020:             my $coursereply;
1.691     raeburn  6021:             if (@groups > 0) {
                   6022:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   6023:                                        $mapparm,$spacequalifierrest);
1.684     raeburn  6024:                 if (defined($coursereply)) { return $coursereply; }
                   6025:             }
1.96      www      6026: 
1.684     raeburn  6027: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.624     albertel 6028: 				     $env{'course.'.$courseid.'.domain'},
                   6029: 				     'course',
                   6030: 				     ($seclevelr,$seclevelm,$seclevel,
                   6031: 				      $courselevelr));
1.287     albertel 6032: 	    if (defined($coursereply)) { return $coursereply; }
1.200     www      6033: 
1.60      www      6034: # ------------------------------------------------------ third, check map parms
1.218     albertel 6035: 	    my %parmhash=();
                   6036: 	    my $thisparm='';
                   6037: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 6038: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 6039: 		    &GDBM_READER(),0640)) {
1.218     albertel 6040: 		$thisparm=$parmhash{$symbparm};
                   6041: 		untie(%parmhash);
                   6042: 	    }
                   6043: 	    if ($thisparm) { return $thisparm; }
                   6044: 	}
1.594     albertel 6045: # ------------------------------------------ fourth, look in resource metadata
1.71      www      6046: 
1.218     albertel 6047: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 6048: 	my $filename;
                   6049: 	if (!$symbparm) { $symbparm=&symbread(); }
                   6050: 	if ($symbparm) {
1.409     www      6051: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 6052: 	} else {
1.620     albertel 6053: 	    $filename=$env{'request.filename'};
1.282     albertel 6054: 	}
                   6055: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.288     albertel 6056: 	if (defined($metadata)) { return $metadata; }
1.282     albertel 6057: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.288     albertel 6058: 	if (defined($metadata)) { return $metadata; }
1.142     www      6059: 
1.594     albertel 6060: # ---------------------------------------------- fourth, look in rest pf course
1.593     albertel 6061: 	if ($symbparm && defined($courseid) && 
1.620     albertel 6062: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 6063: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   6064: 				     $env{'course.'.$courseid.'.domain'},
                   6065: 				     'course',
                   6066: 				     ($courselevelm,$courselevel));
1.593     albertel 6067: 	    if (defined($coursereply)) { return $coursereply; }
                   6068: 	}
1.145     www      6069: # ------------------------------------------------------------------ Cascade up
1.218     albertel 6070: 	unless ($space eq '0') {
1.336     albertel 6071: 	    my @parts=split(/_/,$space);
                   6072: 	    my $id=pop(@parts);
                   6073: 	    my $part=join('_',@parts);
                   6074: 	    if ($part eq '') { $part='0'; }
                   6075: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 6076: 				 $symbparm,$udom,$uname,$section,1);
1.337     albertel 6077: 	    if (defined($partgeneral)) { return $partgeneral; }
1.218     albertel 6078: 	}
1.395     albertel 6079: 	if ($recurse) { return undef; }
                   6080: 	my $pack_def=&packages_tab_default($filename,$varname);
                   6081: 	if (defined($pack_def)) { return $pack_def; }
1.71      www      6082: 
1.48      www      6083: # ---------------------------------------------------- Any other user namespace
                   6084:     } elsif ($realm eq 'environment') {
                   6085: # ----------------------------------------------------------------- environment
1.620     albertel 6086: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   6087: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 6088: 	} else {
1.770     albertel 6089: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   6090: 		return '';
                   6091: 	    }
1.219     albertel 6092: 	    my %returnhash=&userenvironment($udom,$uname,
                   6093: 					    $spacequalifierrest);
                   6094: 	    return $returnhash{$spacequalifierrest};
                   6095: 	}
1.28      www      6096:     } elsif ($realm eq 'system') {
1.48      www      6097: # ----------------------------------------------------------------- system.time
                   6098: 	if ($space eq 'time') {
                   6099: 	    return time;
                   6100:         }
1.696     albertel 6101:     } elsif ($realm eq 'server') {
                   6102: # ----------------------------------------------------------------- system.time
                   6103: 	if ($space eq 'name') {
                   6104: 	    return $ENV{'SERVER_NAME'};
                   6105:         }
1.28      www      6106:     }
1.48      www      6107:     return '';
1.61      www      6108: }
                   6109: 
1.691     raeburn  6110: sub check_group_parms {
                   6111:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   6112:     my @groupitems = ();
                   6113:     my $resultitem;
                   6114:     my @levels = ($symbparm,$mapparm,$what);
                   6115:     foreach my $group (@{$groups}) {
                   6116:         foreach my $level (@levels) {
                   6117:              my $item = $courseid.'.['.$group.'].'.$level;
                   6118:              push(@groupitems,$item);
                   6119:         }
                   6120:     }
                   6121:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   6122:                             $env{'course.'.$courseid.'.domain'},
                   6123:                                      'course',@groupitems);
                   6124:     return $coursereply;
                   6125: }
                   6126: 
                   6127: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  6128:     my ($courseid,@groups) = @_;
                   6129:     @groups = sort(@groups);
1.691     raeburn  6130:     return @groups;
                   6131: }
                   6132: 
1.395     albertel 6133: sub packages_tab_default {
                   6134:     my ($uri,$varname)=@_;
                   6135:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 6136: 
                   6137:     my (@extension,@specifics,$do_default);
                   6138:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 6139: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 6140: 	if ($pack_type eq 'default') {
                   6141: 	    $do_default=1;
                   6142: 	} elsif ($pack_type eq 'extension') {
                   6143: 	    push(@extension,[$package,$pack_type,$pack_part]);
                   6144: 	} else {
                   6145: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   6146: 	}
                   6147:     }
                   6148:     # first look for a package that matches the requested part id
                   6149:     foreach my $package (@specifics) {
                   6150: 	my (undef,$pack_type,$pack_part)=@{$package};
                   6151: 	next if ($pack_part ne $part);
                   6152: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6153: 	    return $packagetab{"$pack_type&$name&default"};
                   6154: 	}
                   6155:     }
                   6156:     # look for any possible matching non extension_ package
                   6157:     foreach my $package (@specifics) {
                   6158: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 6159: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6160: 	    return $packagetab{"$pack_type&$name&default"};
                   6161: 	}
1.585     albertel 6162: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 6163: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   6164: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 6165: 	}
                   6166:     }
1.738     albertel 6167:     # look for any posible extension_ match
                   6168:     foreach my $package (@extension) {
                   6169: 	my ($package,$pack_type)=@{$package};
                   6170: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6171: 	    return $packagetab{"$pack_type&$name&default"};
                   6172: 	}
                   6173: 	if (defined($packagetab{$package."&$name&default"})) {
                   6174: 	    return $packagetab{$package."&$name&default"};
                   6175: 	}
                   6176:     }
                   6177:     # look for a global default setting
                   6178:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   6179: 	return $packagetab{"default&$name&default"};
                   6180:     }
1.395     albertel 6181:     return undef;
                   6182: }
                   6183: 
1.334     albertel 6184: sub add_prefix_and_part {
                   6185:     my ($prefix,$part)=@_;
                   6186:     my $keyroot;
                   6187:     if (defined($prefix) && $prefix !~ /^__/) {
                   6188: 	# prefix that has a part already
                   6189: 	$keyroot=$prefix;
                   6190:     } elsif (defined($prefix)) {
                   6191: 	# prefix that is missing a part
                   6192: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   6193:     } else {
                   6194: 	# no prefix at all
                   6195: 	if (defined($part)) { $keyroot='_'.$part; }
                   6196:     }
                   6197:     return $keyroot;
                   6198: }
                   6199: 
1.71      www      6200: # ---------------------------------------------------------------- Get metadata
                   6201: 
1.599     albertel 6202: my %metaentry;
1.71      www      6203: sub metadata {
1.176     www      6204:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      6205:     $uri=&declutter($uri);
1.288     albertel 6206:     # if it is a non metadata possible uri return quickly
1.529     albertel 6207:     if (($uri eq '') || 
                   6208: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 6209: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.423     albertel 6210:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
1.807     albertel 6211: 	($uri =~ m|home/$match_username/public_html/|)) {
1.468     albertel 6212: 	return undef;
1.288     albertel 6213:     }
1.73      www      6214:     my $filename=$uri;
                   6215:     $uri=~s/\.meta$//;
1.172     www      6216: #
                   6217: # Is the metadata already cached?
1.177     www      6218: # Look at timestamp of caching
1.172     www      6219: # Everything is cached by the main uri, libraries are never directly cached
                   6220: #
1.428     albertel 6221:     if (!defined($liburi)) {
1.599     albertel 6222: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 6223: 	if (defined($cached)) { return $result->{':'.$what}; }
                   6224:     }
                   6225:     {
1.172     www      6226: #
                   6227: # Is this a recursive call for a library?
                   6228: #
1.599     albertel 6229: #	if (! exists($metacache{$uri})) {
                   6230: #	    $metacache{$uri}={};
                   6231: #	}
1.171     www      6232:         if ($liburi) {
                   6233: 	    $liburi=&declutter($liburi);
                   6234:             $filename=$liburi;
1.401     bowersj2 6235:         } else {
1.599     albertel 6236: 	    &devalidate_cache_new('meta',$uri);
                   6237: 	    undef(%metaentry);
1.401     bowersj2 6238: 	}
1.140     www      6239:         my %metathesekeys=();
1.73      www      6240:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 6241: 	my $metastring;
1.768     albertel 6242: 	if ($uri !~ m -^(editupload)/-) {
1.543     albertel 6243: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 6244: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 6245: 	    $metastring=&getfile($file);
1.489     albertel 6246: 	}
1.208     albertel 6247:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      6248:         my $token;
1.140     www      6249:         undef %metathesekeys;
1.71      www      6250:         while ($token=$parser->get_token) {
1.339     albertel 6251: 	    if ($token->[0] eq 'S') {
                   6252: 		if (defined($token->[2]->{'package'})) {
1.172     www      6253: #
                   6254: # This is a package - get package info
                   6255: #
1.339     albertel 6256: 		    my $package=$token->[2]->{'package'};
                   6257: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6258: 		    if (defined($token->[2]->{'id'})) { 
                   6259: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   6260: 		    }
1.599     albertel 6261: 		    if ($metaentry{':packages'}) {
                   6262: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 6263: 		    } else {
1.599     albertel 6264: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 6265: 		    }
1.736     albertel 6266: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 6267: 			my $part=$keyroot;
                   6268: 			$part=~s/^\_//;
1.736     albertel 6269: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   6270: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   6271: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 6272: 			    # ignore package.tab specified default values
                   6273:                             # here &package_tab_default() will fetch those
                   6274: 			    if ($subp eq 'default') { next; }
1.736     albertel 6275: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 6276: 			    my $unikey;
                   6277: 			    if ($pack =~ /_0$/) {
                   6278: 				$unikey='parameter_0_'.$name;
                   6279: 				$part=0;
                   6280: 			    } else {
                   6281: 				$unikey='parameter'.$keyroot.'_'.$name;
                   6282: 			    }
1.339     albertel 6283: 			    if ($subp eq 'display') {
                   6284: 				$value.=' [Part: '.$part.']';
                   6285: 			    }
1.599     albertel 6286: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 6287: 			    $metathesekeys{$unikey}=1;
1.599     albertel 6288: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6289: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 6290: 			    }
1.599     albertel 6291: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   6292: 				$metaentry{':'.$unikey}=
                   6293: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 6294: 			    }
1.339     albertel 6295: 			}
                   6296: 		    }
                   6297: 		} else {
1.172     www      6298: #
                   6299: # This is not a package - some other kind of start tag
1.339     albertel 6300: #
                   6301: 		    my $entry=$token->[1];
                   6302: 		    my $unikey;
                   6303: 		    if ($entry eq 'import') {
                   6304: 			$unikey='';
                   6305: 		    } else {
                   6306: 			$unikey=$entry;
                   6307: 		    }
                   6308: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6309: 
                   6310: 		    if (defined($token->[2]->{'id'})) { 
                   6311: 			$unikey.='_'.$token->[2]->{'id'}; 
                   6312: 		    }
1.175     www      6313: 
1.339     albertel 6314: 		    if ($entry eq 'import') {
1.175     www      6315: #
                   6316: # Importing a library here
1.339     albertel 6317: #
                   6318: 			if ($depthcount<20) {
                   6319: 			    my $location=$parser->get_text('/import');
                   6320: 			    my $dir=$filename;
                   6321: 			    $dir=~s|[^/]*$||;
                   6322: 			    $location=&filelocation($dir,$location);
1.736     albertel 6323: 			    my $metadata = 
                   6324: 				&metadata($uri,'keys', $location,$unikey,
                   6325: 					  $depthcount+1);
                   6326: 			    foreach my $meta (split(',',$metadata)) {
                   6327: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   6328: 				$metathesekeys{$meta}=1;
1.339     albertel 6329: 			    }
                   6330: 			}
                   6331: 		    } else { 
                   6332: 			
                   6333: 			if (defined($token->[2]->{'name'})) { 
                   6334: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   6335: 			}
                   6336: 			$metathesekeys{$unikey}=1;
1.736     albertel 6337: 			foreach my $param (@{$token->[3]}) {
                   6338: 			    $metaentry{':'.$unikey.'.'.$param} =
                   6339: 				$token->[2]->{$param};
1.339     albertel 6340: 			}
                   6341: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 6342: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 6343: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   6344: 		 # only ws inside the tag, and not in default, so use default
                   6345: 		 # as value
1.599     albertel 6346: 			    $metaentry{':'.$unikey}=$default;
1.339     albertel 6347: 			} else {
1.321     albertel 6348: 		  # either something interesting inside the tag or default
                   6349:                   # uninteresting
1.599     albertel 6350: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 6351: 			}
1.172     www      6352: # end of not-a-package not-a-library import
1.339     albertel 6353: 		    }
1.172     www      6354: # end of not-a-package start tag
1.339     albertel 6355: 		}
1.172     www      6356: # the next is the end of "start tag"
1.339     albertel 6357: 	    }
                   6358: 	}
1.483     albertel 6359: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.737     albertel 6360: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 6361: 	    #no specific packages #how's our extension
                   6362: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 6363: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 6364: 					 \%metathesekeys);
                   6365: 	}
1.599     albertel 6366: 	if (!exists($metaentry{':packages'})) {
1.737     albertel 6367: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 6368: 		#no specific packages well let's get default then
                   6369: 		if ($key!~/^default&/) { next; }
1.488     albertel 6370: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 6371: 					     \%metathesekeys);
                   6372: 	    }
                   6373: 	}
1.338     www      6374: # are there custom rights to evaluate
1.599     albertel 6375: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 6376: 
1.338     www      6377:     #
                   6378:     # Importing a rights file here
1.339     albertel 6379:     #
                   6380: 	    unless ($depthcount) {
1.599     albertel 6381: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 6382: 		my $dir=$filename;
                   6383: 		$dir=~s|[^/]*$||;
                   6384: 		$location=&filelocation($dir,$location);
1.736     albertel 6385: 		my $rights_metadata =
                   6386: 		    &metadata($uri,'keys',$location,'_rights',
                   6387: 			      $depthcount+1);
                   6388: 		foreach my $rights (split(',',$rights_metadata)) {
                   6389: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   6390: 		    $metathesekeys{$rights}=1;
1.339     albertel 6391: 		}
                   6392: 	    }
                   6393: 	}
1.737     albertel 6394: 	# uniqifiy package listing
                   6395: 	my %seen;
                   6396: 	my @uniq_packages =
                   6397: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   6398: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   6399: 
                   6400: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 6401: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   6402: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.699     albertel 6403: 	&do_cache_new('meta',$uri,\%metaentry,60*60);
1.177     www      6404: # this is the end of "was not already recently cached
1.71      www      6405:     }
1.599     albertel 6406:     return $metaentry{':'.$what};
1.261     albertel 6407: }
                   6408: 
1.488     albertel 6409: sub metadata_create_package_def {
1.483     albertel 6410:     my ($uri,$key,$package,$metathesekeys)=@_;
                   6411:     my ($pack,$name,$subp)=split(/\&/,$key);
                   6412:     if ($subp eq 'default') { next; }
                   6413:     
1.599     albertel 6414:     if (defined($metaentry{':packages'})) {
                   6415: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 6416:     } else {
1.599     albertel 6417: 	$metaentry{':packages'}=$package;
1.483     albertel 6418:     }
                   6419:     my $value=$packagetab{$key};
                   6420:     my $unikey;
                   6421:     $unikey='parameter_0_'.$name;
1.599     albertel 6422:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 6423:     $$metathesekeys{$unikey}=1;
1.599     albertel 6424:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6425: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 6426:     }
1.599     albertel 6427:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   6428: 	$metaentry{':'.$unikey}=
                   6429: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 6430:     }
                   6431: }
                   6432: 
1.261     albertel 6433: sub metadata_generate_part0 {
                   6434:     my ($metadata,$metacache,$uri) = @_;
                   6435:     my %allnames;
1.737     albertel 6436:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 6437: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 6438: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   6439: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 6440: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 6441: 	    $allnames{$name}=$part;
                   6442: 	  }
                   6443: 	}
                   6444:     }
                   6445:     foreach my $name (keys(%allnames)) {
                   6446:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 6447:       my $key=":parameter_0_$name";
1.261     albertel 6448:       $$metacache{"$key.part"}='0';
                   6449:       $$metacache{"$key.name"}=$name;
1.428     albertel 6450:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 6451: 					   $allnames{$name}.'_'.$name.
                   6452: 					   '.type'};
1.428     albertel 6453:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 6454: 			     '.display'};
1.644     www      6455:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 6456:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 6457:       $$metacache{"$key.display"}=$olddis;
                   6458:     }
1.71      www      6459: }
                   6460: 
1.764     albertel 6461: # ------------------------------------------------------ Devalidate title cache
                   6462: 
                   6463: sub devalidate_title_cache {
                   6464:     my ($url)=@_;
                   6465:     if (!$env{'request.course.id'}) { return; }
                   6466:     my $symb=&symbread($url);
                   6467:     if (!$symb) { return; }
                   6468:     my $key=$env{'request.course.id'}."\0".$symb;
                   6469:     &devalidate_cache_new('title',$key);
                   6470: }
                   6471: 
1.301     www      6472: # ------------------------------------------------- Get the title of a resource
                   6473: 
                   6474: sub gettitle {
                   6475:     my $urlsymb=shift;
                   6476:     my $symb=&symbread($urlsymb);
1.534     albertel 6477:     if ($symb) {
1.620     albertel 6478: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 6479: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 6480: 	if (defined($cached)) { 
                   6481: 	    return $result;
                   6482: 	}
1.534     albertel 6483: 	my ($map,$resid,$url)=&decode_symb($symb);
                   6484: 	my $title='';
                   6485: 	my %bighash;
1.620     albertel 6486: 	if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.534     albertel 6487: 		&GDBM_READER(),0640)) {
                   6488: 	    my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   6489: 	    $title=$bighash{'title_'.$mapid.'.'.$resid};
                   6490: 	    untie %bighash;
                   6491: 	}
                   6492: 	$title=~s/\&colon\;/\:/gs;
                   6493: 	if ($title) {
1.599     albertel 6494: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 6495: 	}
                   6496: 	$urlsymb=$url;
                   6497:     }
                   6498:     my $title=&metadata($urlsymb,'title');
                   6499:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   6500:     return $title;
1.301     www      6501: }
1.613     albertel 6502: 
1.614     albertel 6503: sub get_slot {
                   6504:     my ($which,$cnum,$cdom)=@_;
                   6505:     if (!$cnum || !$cdom) {
1.790     albertel 6506: 	(undef,my $courseid)=&whichuser();
1.620     albertel 6507: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   6508: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 6509:     }
1.703     albertel 6510:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   6511:     my %slotinfo;
                   6512:     if (exists($remembered{$key})) {
                   6513: 	$slotinfo{$which} = $remembered{$key};
                   6514:     } else {
                   6515: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   6516: 	&Apache::lonhomework::showhash(%slotinfo);
                   6517: 	my ($tmp)=keys(%slotinfo);
                   6518: 	if ($tmp=~/^error:/) { return (); }
                   6519: 	$remembered{$key} = $slotinfo{$which};
                   6520:     }
1.616     albertel 6521:     if (ref($slotinfo{$which}) eq 'HASH') {
                   6522: 	return %{$slotinfo{$which}};
                   6523:     }
                   6524:     return $slotinfo{$which};
1.614     albertel 6525: }
1.31      www      6526: # ------------------------------------------------- Update symbolic store links
                   6527: 
                   6528: sub symblist {
                   6529:     my ($mapname,%newhash)=@_;
1.438     www      6530:     $mapname=&deversion(&declutter($mapname));
1.31      www      6531:     my %hash;
1.620     albertel 6532:     if (($env{'request.course.fn'}) && (%newhash)) {
                   6533:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6534:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 6535: 	    foreach my $url (keys %newhash) {
                   6536: 		next if ($url eq 'last_known'
                   6537: 			 && $env{'form.no_update_last_known'});
                   6538: 		$hash{declutter($url)}=&encode_symb($mapname,
                   6539: 						    $newhash{$url}->[1],
                   6540: 						    $newhash{$url}->[0]);
1.191     harris41 6541:             }
1.31      www      6542:             if (untie(%hash)) {
                   6543: 		return 'ok';
                   6544:             }
                   6545:         }
                   6546:     }
                   6547:     return 'error';
1.212     www      6548: }
                   6549: 
                   6550: # --------------------------------------------------------------- Verify a symb
                   6551: 
                   6552: sub symbverify {
1.510     www      6553:     my ($symb,$thisurl)=@_;
                   6554:     my $thisfn=$thisurl;
1.439     www      6555:     $thisfn=&declutter($thisfn);
1.215     www      6556: # direct jump to resource in page or to a sequence - will construct own symbs
                   6557:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   6558: # check URL part
1.409     www      6559:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      6560: 
1.431     www      6561:     unless ($url eq $thisfn) { return 0; }
1.213     www      6562: 
1.216     www      6563:     $symb=&symbclean($symb);
1.510     www      6564:     $thisurl=&deversion($thisurl);
1.439     www      6565:     $thisfn=&deversion($thisfn);
1.213     www      6566: 
                   6567:     my %bighash;
                   6568:     my $okay=0;
1.431     www      6569: 
1.620     albertel 6570:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6571:                             &GDBM_READER(),0640)) {
1.510     www      6572:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      6573:         unless ($ids) { 
1.510     www      6574:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      6575:         }
                   6576:         if ($ids) {
                   6577: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 6578: 	    foreach my $id (split(/\,/,$ids)) {
                   6579: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      6580:                if (
                   6581:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   6582:    eq $symb) { 
1.620     albertel 6583: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 6584: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 6585: 		       $okay=1; 
                   6586: 		   }
                   6587: 	       }
1.216     www      6588: 	   }
                   6589:         }
1.213     www      6590: 	untie(%bighash);
                   6591:     }
                   6592:     return $okay;
1.31      www      6593: }
                   6594: 
1.210     www      6595: # --------------------------------------------------------------- Clean-up symb
                   6596: 
                   6597: sub symbclean {
                   6598:     my $symb=shift;
1.568     albertel 6599:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      6600: # remove version from map
                   6601:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      6602: 
1.210     www      6603: # remove version from URL
                   6604:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      6605: 
1.507     www      6606: # remove wrapper
                   6607: 
1.510     www      6608:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 6609:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      6610:     return $symb;
1.409     www      6611: }
                   6612: 
                   6613: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 6614: 
                   6615: sub encode_symb {
                   6616:     my ($map,$resid,$url)=@_;
                   6617:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   6618: }
1.409     www      6619: 
                   6620: sub decode_symb {
1.568     albertel 6621:     my $symb=shift;
                   6622:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   6623:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      6624:     return (&fixversion($map),$resid,&fixversion($url));
                   6625: }
                   6626: 
                   6627: sub fixversion {
                   6628:     my $fn=shift;
1.609     banghart 6629:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      6630:     my %bighash;
                   6631:     my $uri=&clutter($fn);
1.620     albertel 6632:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      6633: # is this cached?
1.599     albertel 6634:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      6635:     if (defined($cached)) { return $result; }
                   6636: # unfortunately not cached, or expired
1.620     albertel 6637:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      6638: 	    &GDBM_READER(),0640)) {
                   6639:  	if ($bighash{'version_'.$uri}) {
                   6640:  	    my $version=$bighash{'version_'.$uri};
1.444     www      6641:  	    unless (($version eq 'mostrecent') || 
                   6642: 		    ($version==&getversion($uri))) {
1.440     www      6643:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   6644:  	    }
                   6645:  	}
                   6646:  	untie %bighash;
1.413     www      6647:     }
1.599     albertel 6648:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      6649: }
                   6650: 
                   6651: sub deversion {
                   6652:     my $url=shift;
                   6653:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   6654:     return $url;
1.210     www      6655: }
                   6656: 
1.31      www      6657: # ------------------------------------------------------ Return symb list entry
                   6658: 
                   6659: sub symbread {
1.249     www      6660:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 6661:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 6662:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      6663: # no filename provided? try from environment
1.44      www      6664:     unless ($thisfn) {
1.620     albertel 6665:         if ($env{'request.symb'}) {
                   6666: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 6667: 	}
1.620     albertel 6668: 	$thisfn=$env{'request.filename'};
1.44      www      6669:     }
1.569     albertel 6670:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      6671: # is that filename actually a symb? Verify, clean, and return
                   6672:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 6673: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 6674: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 6675: 	}
1.242     www      6676:     }
1.44      www      6677:     $thisfn=declutter($thisfn);
1.31      www      6678:     my %hash;
1.37      www      6679:     my %bighash;
                   6680:     my $syval='';
1.620     albertel 6681:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  6682:         my $targetfn = $thisfn;
1.609     banghart 6683:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  6684:             $targetfn = 'adm/wrapper/'.$thisfn;
                   6685:         }
1.687     albertel 6686: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   6687: 	    $targetfn=$1;
                   6688: 	}
1.620     albertel 6689:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6690:                       &GDBM_READER(),0640)) {
1.481     raeburn  6691: 	    $syval=$hash{$targetfn};
1.37      www      6692:             untie(%hash);
                   6693:         }
                   6694: # ---------------------------------------------------------- There was an entry
                   6695:         if ($syval) {
1.601     albertel 6696: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 6697: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.601     albertel 6698: 		    #&appenv('request.ambiguous' => $thisfn);
1.620     albertel 6699: 		    #return $env{$cache_str}='';
1.601     albertel 6700: 		#}    
                   6701: 		#$syval.=$1;
                   6702: 	    #}
1.37      www      6703:         } else {
                   6704: # ------------------------------------------------------- Was not in symb table
1.620     albertel 6705:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6706:                             &GDBM_READER(),0640)) {
1.37      www      6707: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      6708:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      6709:               unless ($ids) { 
                   6710:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      6711:               }
                   6712:               unless ($ids) {
                   6713: # alias?
                   6714: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      6715:               }
1.37      www      6716:               if ($ids) {
                   6717: # ------------------------------------------------------------------- Has ID(s)
                   6718:                  my @possibilities=split(/\,/,$ids);
1.39      www      6719:                  if ($#possibilities==0) {
                   6720: # ----------------------------------------------- There is only one possibility
1.37      www      6721: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 6722: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6723: 						    $resid,$thisfn);
1.249     www      6724:                  } elsif (!$donotrecurse) {
1.39      www      6725: # ------------------------------------------ There is more than one possibility
                   6726:                      my $realpossible=0;
1.800     albertel 6727:                      foreach my $id (@possibilities) {
                   6728: 			 my $file=$bighash{'src_'.$id};
1.39      www      6729:                          if (&allowed('bre',$file)) {
1.800     albertel 6730:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      6731:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   6732: 				$realpossible++;
1.626     albertel 6733:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6734: 						    $resid,$thisfn);
1.39      www      6735:                             }
                   6736: 			 }
1.191     harris41 6737:                      }
1.39      www      6738: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      6739:                  } else {
                   6740:                      $syval='';
1.37      www      6741:                  }
                   6742: 	      }
                   6743:               untie(%bighash)
1.481     raeburn  6744:            }
1.31      www      6745:         }
1.62      www      6746:         if ($syval) {
1.620     albertel 6747: 	    return $env{$cache_str}=$syval;
1.62      www      6748:         }
1.31      www      6749:     }
1.44      www      6750:     &appenv('request.ambiguous' => $thisfn);
1.620     albertel 6751:     return $env{$cache_str}='';
1.31      www      6752: }
                   6753: 
                   6754: # ---------------------------------------------------------- Return random seed
                   6755: 
1.32      www      6756: sub numval {
                   6757:     my $txt=shift;
                   6758:     $txt=~tr/A-J/0-9/;
                   6759:     $txt=~tr/a-j/0-9/;
                   6760:     $txt=~tr/K-T/0-9/;
                   6761:     $txt=~tr/k-t/0-9/;
                   6762:     $txt=~tr/U-Z/0-5/;
                   6763:     $txt=~tr/u-z/0-5/;
                   6764:     $txt=~s/\D//g;
1.564     albertel 6765:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      6766:     return int($txt);
1.368     albertel 6767: }
                   6768: 
1.484     albertel 6769: sub numval2 {
                   6770:     my $txt=shift;
                   6771:     $txt=~tr/A-J/0-9/;
                   6772:     $txt=~tr/a-j/0-9/;
                   6773:     $txt=~tr/K-T/0-9/;
                   6774:     $txt=~tr/k-t/0-9/;
                   6775:     $txt=~tr/U-Z/0-5/;
                   6776:     $txt=~tr/u-z/0-5/;
                   6777:     $txt=~s/\D//g;
                   6778:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   6779:     my $total;
                   6780:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 6781:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 6782:     return int($total);
                   6783: }
                   6784: 
1.575     albertel 6785: sub numval3 {
                   6786:     use integer;
                   6787:     my $txt=shift;
                   6788:     $txt=~tr/A-J/0-9/;
                   6789:     $txt=~tr/a-j/0-9/;
                   6790:     $txt=~tr/K-T/0-9/;
                   6791:     $txt=~tr/k-t/0-9/;
                   6792:     $txt=~tr/U-Z/0-5/;
                   6793:     $txt=~tr/u-z/0-5/;
                   6794:     $txt=~s/\D//g;
                   6795:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   6796:     my $total;
                   6797:     foreach my $val (@txts) { $total+=$val; }
                   6798:     if ($_64bit) { $total=(($total<<32)>>32); }
                   6799:     return $total;
                   6800: }
                   6801: 
1.675     albertel 6802: sub digest {
                   6803:     my ($data)=@_;
                   6804:     my $digest=&Digest::MD5::md5($data);
                   6805:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   6806:     my ($e,$f);
                   6807:     {
                   6808:         use integer;
                   6809:         $e=($a+$b);
                   6810:         $f=($c+$d);
                   6811:         if ($_64bit) {
                   6812:             $e=(($e<<32)>>32);
                   6813:             $f=(($f<<32)>>32);
                   6814:         }
                   6815:     }
                   6816:     if (wantarray) {
                   6817: 	return ($e,$f);
                   6818:     } else {
                   6819: 	my $g;
                   6820: 	{
                   6821: 	    use integer;
                   6822: 	    $g=($e+$f);
                   6823: 	    if ($_64bit) {
                   6824: 		$g=(($g<<32)>>32);
                   6825: 	    }
                   6826: 	}
                   6827: 	return $g;
                   6828:     }
                   6829: }
                   6830: 
1.368     albertel 6831: sub latest_rnd_algorithm_id {
1.675     albertel 6832:     return '64bit5';
1.366     albertel 6833: }
1.32      www      6834: 
1.503     albertel 6835: sub get_rand_alg {
                   6836:     my ($courseid)=@_;
1.790     albertel 6837:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 6838:     if ($courseid) {
1.620     albertel 6839: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 6840:     }
                   6841:     return &latest_rnd_algorithm_id();
                   6842: }
                   6843: 
1.562     albertel 6844: sub validCODE {
                   6845:     my ($CODE)=@_;
                   6846:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   6847:     return 0;
                   6848: }
                   6849: 
1.491     albertel 6850: sub getCODE {
1.620     albertel 6851:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 6852:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   6853: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   6854: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 6855: 	return $Apache::lonhomework::history{'resource.CODE'};
                   6856:     }
                   6857:     return undef;
                   6858: }
                   6859: 
1.31      www      6860: sub rndseed {
1.155     albertel 6861:     my ($symb,$courseid,$domain,$username)=@_;
1.366     albertel 6862: 
1.790     albertel 6863:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.155     albertel 6864:     if (!$symb) {
1.366     albertel 6865: 	unless ($symb=$wsymb) { return time; }
                   6866:     }
                   6867:     if (!$courseid) { $courseid=$wcourseid; }
                   6868:     if (!$domain) { $domain=$wdomain; }
                   6869:     if (!$username) { $username=$wusername }
1.503     albertel 6870:     my $which=&get_rand_alg();
1.803     albertel 6871: 
1.491     albertel 6872:     if (defined(&getCODE())) {
1.675     albertel 6873: 	if ($which eq '64bit5') {
                   6874: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   6875: 	} elsif ($which eq '64bit4') {
1.575     albertel 6876: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   6877: 	} else {
                   6878: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   6879: 	}
1.675     albertel 6880:     } elsif ($which eq '64bit5') {
                   6881: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 6882:     } elsif ($which eq '64bit4') {
                   6883: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 6884:     } elsif ($which eq '64bit3') {
                   6885: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 6886:     } elsif ($which eq '64bit2') {
                   6887: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 6888:     } elsif ($which eq '64bit') {
                   6889: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   6890:     }
                   6891:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   6892: }
                   6893: 
                   6894: sub rndseed_32bit {
                   6895:     my ($symb,$courseid,$domain,$username)=@_;
                   6896:     {
                   6897: 	use integer;
                   6898: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   6899: 	my $symbseed=numval($symb) << 22;
                   6900: 	my $namechck=unpack("%32C*",$username) << 17;
                   6901: 	my $nameseed=numval($username) << 12;
                   6902: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   6903: 	my $courseseed=unpack("%32C*",$courseid);
                   6904: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 6905: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6906: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 6907: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 6908: 	return $num;
                   6909:     }
                   6910: }
                   6911: 
                   6912: sub rndseed_64bit {
                   6913:     my ($symb,$courseid,$domain,$username)=@_;
                   6914:     {
                   6915: 	use integer;
                   6916: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   6917: 	my $symbseed=numval($symb) << 10;
                   6918: 	my $namechck=unpack("%32S*",$username);
                   6919: 	
                   6920: 	my $nameseed=numval($username) << 21;
                   6921: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   6922: 	my $courseseed=unpack("%32S*",$courseid);
                   6923: 	
                   6924: 	my $num1=$symbchck+$symbseed+$namechck;
                   6925: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6926: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6927: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 6928: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 6929: 	return "$num1,$num2";
1.155     albertel 6930:     }
1.366     albertel 6931: }
                   6932: 
1.443     albertel 6933: sub rndseed_64bit2 {
                   6934:     my ($symb,$courseid,$domain,$username)=@_;
                   6935:     {
                   6936: 	use integer;
                   6937: 	# strings need to be an even # of cahracters long, it it is odd the
                   6938:         # last characters gets thrown away
                   6939: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6940: 	my $symbseed=numval($symb) << 10;
                   6941: 	my $namechck=unpack("%32S*",$username.' ');
                   6942: 	
                   6943: 	my $nameseed=numval($username) << 21;
1.501     albertel 6944: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6945: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6946: 	
                   6947: 	my $num1=$symbchck+$symbseed+$namechck;
                   6948: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6949: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6950: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 6951: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 6952: 	return "$num1,$num2";
                   6953:     }
                   6954: }
                   6955: 
                   6956: sub rndseed_64bit3 {
                   6957:     my ($symb,$courseid,$domain,$username)=@_;
                   6958:     {
                   6959: 	use integer;
                   6960: 	# strings need to be an even # of cahracters long, it it is odd the
                   6961:         # last characters gets thrown away
                   6962: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6963: 	my $symbseed=numval2($symb) << 10;
                   6964: 	my $namechck=unpack("%32S*",$username.' ');
                   6965: 	
                   6966: 	my $nameseed=numval2($username) << 21;
1.443     albertel 6967: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6968: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6969: 	
                   6970: 	my $num1=$symbchck+$symbseed+$namechck;
                   6971: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6972: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6973: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 6974: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6975: 	
1.503     albertel 6976: 	return "$num1:$num2";
1.443     albertel 6977:     }
                   6978: }
                   6979: 
1.575     albertel 6980: sub rndseed_64bit4 {
                   6981:     my ($symb,$courseid,$domain,$username)=@_;
                   6982:     {
                   6983: 	use integer;
                   6984: 	# strings need to be an even # of cahracters long, it it is odd the
                   6985:         # last characters gets thrown away
                   6986: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6987: 	my $symbseed=numval3($symb) << 10;
                   6988: 	my $namechck=unpack("%32S*",$username.' ');
                   6989: 	
                   6990: 	my $nameseed=numval3($username) << 21;
                   6991: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6992: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6993: 	
                   6994: 	my $num1=$symbchck+$symbseed+$namechck;
                   6995: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6996: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6997: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 6998: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6999: 	
                   7000: 	return "$num1:$num2";
                   7001:     }
                   7002: }
                   7003: 
1.675     albertel 7004: sub rndseed_64bit5 {
                   7005:     my ($symb,$courseid,$domain,$username)=@_;
                   7006:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   7007:     return "$num1:$num2";
                   7008: }
                   7009: 
1.366     albertel 7010: sub rndseed_CODE_64bit {
                   7011:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 7012:     {
1.366     albertel 7013: 	use integer;
1.443     albertel 7014: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 7015: 	my $symbseed=numval2($symb);
1.491     albertel 7016: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   7017: 	my $CODEseed=numval(&getCODE());
1.443     albertel 7018: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 7019: 	my $num1=$symbseed+$CODEchck;
                   7020: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 7021: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   7022: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 7023: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   7024: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 7025: 	return "$num1:$num2";
1.366     albertel 7026:     }
                   7027: }
                   7028: 
1.575     albertel 7029: sub rndseed_CODE_64bit4 {
                   7030:     my ($symb,$courseid,$domain,$username)=@_;
                   7031:     {
                   7032: 	use integer;
                   7033: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   7034: 	my $symbseed=numval3($symb);
                   7035: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   7036: 	my $CODEseed=numval3(&getCODE());
                   7037: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7038: 	my $num1=$symbseed+$CODEchck;
                   7039: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 7040: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   7041: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 7042: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   7043: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   7044: 	return "$num1:$num2";
                   7045:     }
                   7046: }
                   7047: 
1.675     albertel 7048: sub rndseed_CODE_64bit5 {
                   7049:     my ($symb,$courseid,$domain,$username)=@_;
                   7050:     my $code = &getCODE();
                   7051:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   7052:     return "$num1:$num2";
                   7053: }
                   7054: 
1.366     albertel 7055: sub setup_random_from_rndseed {
                   7056:     my ($rndseed)=@_;
1.503     albertel 7057:     if ($rndseed =~/([,:])/) {
                   7058: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 7059: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   7060:     } else {
                   7061: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 7062:     }
1.36      albertel 7063: }
                   7064: 
1.474     albertel 7065: sub latest_receipt_algorithm_id {
                   7066:     return 'receipt2';
                   7067: }
                   7068: 
1.480     www      7069: sub recunique {
                   7070:     my $fucourseid=shift;
                   7071:     my $unique;
1.620     albertel 7072:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   7073: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      7074:     } else {
                   7075: 	$unique=$perlvar{'lonReceipt'};
                   7076:     }
                   7077:     return unpack("%32C*",$unique);
                   7078: }
                   7079: 
                   7080: sub recprefix {
                   7081:     my $fucourseid=shift;
                   7082:     my $prefix;
1.620     albertel 7083:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   7084: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      7085:     } else {
                   7086: 	$prefix=$perlvar{'lonHostID'};
                   7087:     }
                   7088:     return unpack("%32C*",$prefix);
                   7089: }
                   7090: 
1.76      www      7091: sub ireceipt {
1.474     albertel 7092:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.76      www      7093:     my $cuname=unpack("%32C*",$funame);
                   7094:     my $cudom=unpack("%32C*",$fudom);
                   7095:     my $cucourseid=unpack("%32C*",$fucourseid);
                   7096:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      7097:     my $cunique=&recunique($fucourseid);
1.474     albertel 7098:     my $cpart=unpack("%32S*",$part);
1.480     www      7099:     my $return =&recprefix($fucourseid).'-';
1.620     albertel 7100:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   7101: 	$env{'request.state'} eq 'construct') {
1.790     albertel 7102: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 7103: 			       
                   7104: 	$return.= ($cunique%$cuname+
                   7105: 		   $cunique%$cudom+
                   7106: 		   $cusymb%$cuname+
                   7107: 		   $cusymb%$cudom+
                   7108: 		   $cucourseid%$cuname+
                   7109: 		   $cucourseid%$cudom+
                   7110: 		   $cpart%$cuname+
                   7111: 		   $cpart%$cudom);
                   7112:     } else {
                   7113: 	$return.= ($cunique%$cuname+
                   7114: 		   $cunique%$cudom+
                   7115: 		   $cusymb%$cuname+
                   7116: 		   $cusymb%$cudom+
                   7117: 		   $cucourseid%$cuname+
                   7118: 		   $cucourseid%$cudom);
                   7119:     }
                   7120:     return $return;
1.76      www      7121: }
                   7122: 
                   7123: sub receipt {
1.474     albertel 7124:     my ($part)=@_;
1.790     albertel 7125:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 7126:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      7127: }
1.260     ng       7128: 
1.790     albertel 7129: sub whichuser {
                   7130:     my ($passedsymb)=@_;
                   7131:     my ($symb,$courseid,$domain,$name,$publicuser);
                   7132:     if (defined($env{'form.grade_symb'})) {
                   7133: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   7134: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   7135: 	if (!$allowed &&
                   7136: 	    exists($env{'request.course.sec'}) &&
                   7137: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   7138: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   7139: 			      '/'.$env{'request.course.sec'});
                   7140: 	}
                   7141: 	if ($allowed) {
                   7142: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   7143: 	    $courseid=$tmp_courseid;
                   7144: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   7145: 	    ($name)=&get_env_multiple('form.grade_username');
                   7146: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   7147: 	}
                   7148:     }
                   7149:     if (!$passedsymb) {
                   7150: 	$symb=&symbread();
                   7151:     } else {
                   7152: 	$symb=$passedsymb;
                   7153:     }
                   7154:     $courseid=$env{'request.course.id'};
                   7155:     $domain=$env{'user.domain'};
                   7156:     $name=$env{'user.name'};
                   7157:     if ($name eq 'public' && $domain eq 'public') {
                   7158: 	if (!defined($env{'form.username'})) {
                   7159: 	    $env{'form.username'}.=time.rand(10000000);
                   7160: 	}
                   7161: 	$name.=$env{'form.username'};
                   7162:     }
                   7163:     return ($symb,$courseid,$domain,$name,$publicuser);
                   7164: 
                   7165: }
                   7166: 
1.36      albertel 7167: # ------------------------------------------------------------ Serves up a file
1.472     albertel 7168: # returns either the contents of the file or 
                   7169: # -1 if the file doesn't exist
1.481     raeburn  7170: #
                   7171: # if the target is a file that was uploaded via DOCS, 
                   7172: # a check will be made to see if a current copy exists on the local server,
                   7173: # if it does this will be served, otherwise a copy will be retrieved from
                   7174: # the home server for the course and stored in /home/httpd/html/userfiles on
                   7175: # the local server.   
1.472     albertel 7176: 
1.36      albertel 7177: sub getfile {
1.538     albertel 7178:     my ($file) = @_;
1.609     banghart 7179:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 7180:     &repcopy($file);
                   7181:     return &readfile($file);
                   7182: }
                   7183: 
                   7184: sub repcopy_userfile {
                   7185:     my ($file)=@_;
1.609     banghart 7186:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 7187:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 7188:     my ($cdom,$cnum,$filename) = 
1.811     albertel 7189: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 7190:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   7191:     if (-e "$file") {
1.828     www      7192: # we already have a local copy, check it out
1.538     albertel 7193: 	my @fileinfo = stat($file);
1.828     www      7194: 	my $rtncode;
                   7195: 	my $info;
1.538     albertel 7196: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 7197: 	if ($lwpresp ne 'ok') {
1.828     www      7198: # there is no such file anymore, even though we had a local copy
1.482     albertel 7199: 	    if ($rtncode eq '404') {
1.538     albertel 7200: 		unlink($file);
1.482     albertel 7201: 	    }
                   7202: 	    return -1;
                   7203: 	}
                   7204: 	if ($info < $fileinfo[9]) {
1.828     www      7205: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  7206: 	    return 'ok';
1.828     www      7207: 	} else {
                   7208: # the file is outdated, get rid of it
                   7209: 	    unlink($file);
1.482     albertel 7210: 	}
1.828     www      7211:     }
                   7212: # one way or the other, at this point, we don't have the file
                   7213: # construct the correct path for the file
                   7214:     my @parts = ($cdom,$cnum); 
                   7215:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   7216: 	push @parts, split(/\//,$1);
                   7217:     }
                   7218:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   7219:     foreach my $part (@parts) {
                   7220: 	$path .= '/'.$part;
                   7221: 	if (!-e $path) {
                   7222: 	    mkdir($path,0770);
1.482     albertel 7223: 	}
                   7224:     }
1.828     www      7225: # now the path exists for sure
                   7226: # get a user agent
                   7227:     my $ua=new LWP::UserAgent;
                   7228:     my $transferfile=$file.'.in.transfer';
                   7229: # FIXME: this should flock
                   7230:     if (-e $transferfile) { return 'ok'; }
                   7231:     my $request;
                   7232:     $uri=~s/^\///;
1.829     www      7233:     $request=new HTTP::Request('GET','http://'.$hostname{&homeserver($cnum,$cdom)}.'/raw/'.$uri);
1.828     www      7234:     my $response=$ua->request($request,$transferfile);
                   7235: # did it work?
                   7236:     if ($response->is_error()) {
                   7237: 	unlink($transferfile);
                   7238: 	&logthis("Userfile repcopy failed for $uri");
                   7239: 	return -1;
                   7240:     }
                   7241: # worked, rename the transfer file
                   7242:     rename($transferfile,$file);
1.607     raeburn  7243:     return 'ok';
1.481     raeburn  7244: }
                   7245: 
1.517     albertel 7246: sub tokenwrapper {
                   7247:     my $uri=shift;
1.552     albertel 7248:     $uri=~s|^http\://([^/]+)||;
                   7249:     $uri=~s|^/||;
1.620     albertel 7250:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 7251:     my $token=$1;
1.552     albertel 7252:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   7253:     if ($udom && $uname && $file) {
                   7254: 	$file=~s|(\?\.*)*$||;
1.620     albertel 7255:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
1.552     albertel 7256:         return 'http://'.$hostname{ &homeserver($uname,$udom)}.'/'.$uri.
1.517     albertel 7257:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   7258:                                '&tokenissued='.$perlvar{'lonHostID'};
                   7259:     } else {
                   7260:         return '/adm/notfound.html';
                   7261:     }
                   7262: }
                   7263: 
1.828     www      7264: # call with reqtype HEAD: get last modification time
                   7265: # call with reqtype GET: get the file contents
                   7266: # Do not call this with reqtype GET for large files! It loads everything into memory
                   7267: #
1.481     raeburn  7268: sub getuploaded {
                   7269:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   7270:     $uri=~s/^\///;
                   7271:     $uri = 'http://'.$hostname{ &homeserver($cnum,$cdom)}.'/raw/'.$uri;
                   7272:     my $ua=new LWP::UserAgent;
                   7273:     my $request=new HTTP::Request($reqtype,$uri);
                   7274:     my $response=$ua->request($request);
                   7275:     $$rtncode = $response->code;
1.482     albertel 7276:     if (! $response->is_success()) {
                   7277: 	return 'failed';
                   7278:     }      
                   7279:     if ($reqtype eq 'HEAD') {
1.486     www      7280: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 7281:     } elsif ($reqtype eq 'GET') {
                   7282: 	$$info = $response->content;
1.472     albertel 7283:     }
1.482     albertel 7284:     return 'ok';
1.36      albertel 7285: }
                   7286: 
1.481     raeburn  7287: sub readfile {
                   7288:     my $file = shift;
                   7289:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   7290:     my $fh;
                   7291:     open($fh,"<$file");
                   7292:     my $a='';
1.800     albertel 7293:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  7294:     return $a;
                   7295: }
                   7296: 
1.36      albertel 7297: sub filelocation {
1.590     banghart 7298:     my ($dir,$file) = @_;
                   7299:     my $location;
                   7300:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 7301: 
                   7302:     if ($file =~ m-^/adm/-) {
                   7303: 	$file=~s-^/adm/wrapper/-/-;
                   7304: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   7305:     }
1.590     banghart 7306:     if ($file=~m:^/~:) { # is a contruction space reference
                   7307:         $location = $file;
                   7308:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 7309:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 7310: 	# is a correct contruction space reference
                   7311:         $location = $file;
1.609     banghart 7312:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 7313:         my ($udom,$uname,$filename)=
1.811     albertel 7314:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 7315:         my $home=&homeserver($uname,$udom);
                   7316:         my $is_me=0;
                   7317:         my @ids=&current_machine_ids();
                   7318:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   7319:         if ($is_me) {
1.740     www      7320:   	    $location=&propath($udom,$uname).
1.590     banghart 7321:   	      '/userfiles/'.$filename;
                   7322:         } else {
                   7323:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   7324:   	      $udom.'/'.$uname.'/'.$filename;
                   7325:         }
                   7326:     } else {
                   7327:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   7328:         $file=~s:^/res/:/:;
                   7329:         if ( !( $file =~ m:^/:) ) {
                   7330:             $location = $dir. '/'.$file;
                   7331:         } else {
                   7332:             $location = '/home/httpd/html/res'.$file;
                   7333:         }
1.59      albertel 7334:     }
1.590     banghart 7335:     $location=~s://+:/:g; # remove duplicate /
                   7336:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
                   7337:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   7338:     return $location;
1.46      www      7339: }
1.36      albertel 7340: 
1.46      www      7341: sub hreflocation {
                   7342:     my ($dir,$file)=@_;
1.460     albertel 7343:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666     albertel 7344: 	$file=filelocation($dir,$file);
1.700     albertel 7345:     } elsif ($file=~m-^/adm/-) {
                   7346: 	$file=~s-^/adm/wrapper/-/-;
                   7347: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 7348:     }
                   7349:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   7350: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 7351:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   7352: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 7353:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 7354: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 7355: 	    -/uploaded/$1/$2/-x;
1.46      www      7356:     }
1.462     albertel 7357:     return $file;
1.465     albertel 7358: }
                   7359: 
                   7360: sub current_machine_domains {
                   7361:     my $hostname=$hostname{$perlvar{'lonHostID'}};
                   7362:     my @domains;
                   7363:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  7364: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 7365: 	if ($hostname eq $name) {
                   7366: 	    push(@domains,$hostdom{$id});
                   7367: 	}
                   7368:     }
                   7369:     return @domains;
                   7370: }
                   7371: 
                   7372: sub current_machine_ids {
                   7373:     my $hostname=$hostname{$perlvar{'lonHostID'}};
                   7374:     my @ids;
                   7375:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  7376: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 7377: 	if ($hostname eq $name) {
                   7378: 	    push(@ids,$id);
                   7379: 	}
                   7380:     }
                   7381:     return @ids;
1.31      www      7382: }
                   7383: 
1.824     raeburn  7384: sub additional_machine_domains {
                   7385:     my @domains;
                   7386:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   7387:     while( my $line = <$fh>) {
                   7388:         $line =~ s/\s//g;
                   7389:         push(@domains,$line);
                   7390:     }
                   7391:     return @domains;
                   7392: }
                   7393: 
                   7394: sub default_login_domain {
                   7395:     my $domain = $perlvar{'lonDefDomain'};
                   7396:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   7397:     foreach my $posdom (&current_machine_domains(),
                   7398:                         &additional_machine_domains()) {
                   7399:         if (lc($posdom) eq lc($testdomain)) {
                   7400:             $domain=$posdom;
                   7401:             last;
                   7402:         }
                   7403:     }
                   7404:     return $domain;
                   7405: }
                   7406: 
1.31      www      7407: # ------------------------------------------------------------- Declutters URLs
                   7408: 
                   7409: sub declutter {
                   7410:     my $thisfn=shift;
1.569     albertel 7411:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 7412:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      7413:     $thisfn=~s/^\///;
1.697     albertel 7414:     $thisfn=~s|^adm/wrapper/||;
                   7415:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      7416:     $thisfn=~s/^res\///;
1.235     www      7417:     $thisfn=~s/\?.+$//;
1.268     www      7418:     return $thisfn;
                   7419: }
                   7420: 
                   7421: # ------------------------------------------------------------- Clutter up URLs
                   7422: 
                   7423: sub clutter {
                   7424:     my $thisfn='/'.&declutter(shift);
1.609     banghart 7425:     unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) { 
1.270     www      7426:        $thisfn='/res'.$thisfn; 
                   7427:     }
1.694     albertel 7428:     if ($thisfn !~m|/adm|) {
1.695     albertel 7429: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 7430: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 7431: 	} else {
                   7432: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   7433: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 7434: 	    if ($embstyle eq 'ssi'
                   7435: 		|| ($embstyle eq 'hdn')
                   7436: 		|| ($embstyle eq 'rat')
                   7437: 		|| ($embstyle eq 'prv')
                   7438: 		|| ($embstyle eq 'ign')) {
                   7439: 		#do nothing with these
                   7440: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 7441: 		|| ($embstyle eq 'emb')
                   7442: 		|| ($embstyle eq 'wrp')) {
                   7443: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 7444: 	    } elsif ($embstyle eq 'unk'
                   7445: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 7446: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 7447: 	    } else {
1.718     www      7448: #		&logthis("Got a blank emb style");
1.695     albertel 7449: 	    }
1.694     albertel 7450: 	}
                   7451:     }
1.31      www      7452:     return $thisfn;
1.12      www      7453: }
                   7454: 
1.787     albertel 7455: sub clutter_with_no_wrapper {
                   7456:     my $uri = &clutter(shift);
                   7457:     if ($uri =~ m-^/adm/-) {
                   7458: 	$uri =~ s-^/adm/wrapper/-/-;
                   7459: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   7460:     }
                   7461:     return $uri;
                   7462: }
                   7463: 
1.557     albertel 7464: sub freeze_escape {
                   7465:     my ($value)=@_;
                   7466:     if (ref($value)) {
                   7467: 	$value=&nfreeze($value);
                   7468: 	return '__FROZEN__'.&escape($value);
                   7469:     }
                   7470:     return &escape($value);
                   7471: }
                   7472: 
1.11      www      7473: 
1.557     albertel 7474: sub thaw_unescape {
                   7475:     my ($value)=@_;
                   7476:     if ($value =~ /^__FROZEN__/) {
                   7477: 	substr($value,0,10,undef);
                   7478: 	$value=&unescape($value);
                   7479: 	return &thaw($value);
                   7480:     }
                   7481:     return &unescape($value);
                   7482: }
                   7483: 
1.436     albertel 7484: sub correct_line_ends {
                   7485:     my ($result)=@_;
                   7486:     $$result =~s/\r\n/\n/mg;
                   7487:     $$result =~s/\r/\n/mg;
1.415     albertel 7488: }
1.1       albertel 7489: # ================================================================ Main Program
                   7490: 
1.184     www      7491: sub goodbye {
1.204     albertel 7492:    &logthis("Starting Shut down");
1.443     albertel 7493: #not converted to using infrastruture and probably shouldn't be
1.599     albertel 7494:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&freeze(\%badServerCache))));
1.443     albertel 7495: #converted
1.599     albertel 7496: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
                   7497:    &logthis(sprintf("%-20s is %s",'%homecache',length(&freeze(\%homecache))));
                   7498: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&freeze(\%titlecache))));
                   7499: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&freeze(\%courseresdatacache))));
1.425     albertel 7500: #1.1 only
1.599     albertel 7501: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&freeze(\%userresdatacache))));
                   7502: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&freeze(\%getsectioncache))));
                   7503: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&freeze(\%courseresversioncache))));
                   7504: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&freeze(\%resversioncache))));
                   7505:    &logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
                   7506:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   7507:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      7508:    &flushcourselogs();
                   7509:    &logthis("Shutting down");
                   7510: }
                   7511: 
1.179     www      7512: BEGIN {
1.228     harris41 7513: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
1.195     www      7514:     unless ($readit) {
1.217     harris41 7515: {
1.781     raeburn  7516:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   7517:     %perlvar = (%perlvar,%{$configvars});
1.227     harris41 7518: }
1.1       albertel 7519: 
1.327     albertel 7520: # ------------------------------------------------------------ Read domain file
                   7521: {
                   7522:     %domaindescription = ();
                   7523:     %domain_auth_def = ();
                   7524:     %domain_auth_arg_def = ();
1.448     albertel 7525:     my $fh;
                   7526:     if (open($fh,"<".$Apache::lonnet::perlvar{'lonTabDir'}.'/domain.tab')) {
1.800     albertel 7527: 	while (my $line = <$fh>) {
                   7528:            next if ($line =~ /^(\#|\s*$)/);
1.390     matthew  7529: #           next if /^\#/;
1.801     foxr     7530:            chomp $line;
1.403     www      7531:            my ($domain, $domain_description, $def_auth, $def_auth_arg,
1.800     albertel 7532: 	       $def_lang, $city, $longi, $lati, $primary) = split(/:/,$line,9);
1.403     www      7533: 	   $domain_auth_def{$domain}=$def_auth;
1.327     albertel 7534:            $domain_auth_arg_def{$domain}=$def_auth_arg;
1.403     www      7535: 	   $domaindescription{$domain}=$domain_description;
                   7536: 	   $domain_lang_def{$domain}=$def_lang;
                   7537: 	   $domain_city{$domain}=$city;
                   7538: 	   $domain_longi{$domain}=$longi;
                   7539: 	   $domain_lati{$domain}=$lati;
1.685     raeburn  7540:            $domain_primary{$domain}=$primary;
1.403     www      7541: 
1.448     albertel 7542:  #         &logthis("Domain.tab: $domain, $domain_auth_def{$domain}, $domain_auth_arg_def{$domain},$domaindescription{$domain}");
1.327     albertel 7543: #          &logthis("Domain.tab: $domain ".$domaindescription{$domain} );
1.448     albertel 7544: 	}
1.327     albertel 7545:     }
1.448     albertel 7546:     close ($fh);
1.327     albertel 7547: }
                   7548: 
                   7549: 
1.1       albertel 7550: # ------------------------------------------------------------- Read hosts file
                   7551: {
1.448     albertel 7552:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
1.1       albertel 7553: 
                   7554:     while (my $configline=<$config>) {
1.303     matthew  7555:        next if ($configline =~ /^(\#|\s*$)/);
1.154     www      7556:        chomp($configline);
1.595     albertel 7557:        my ($id,$domain,$role,$name)=split(/:/,$configline);
1.597     albertel 7558:        $name=~s/\s//g;
1.595     albertel 7559:        if ($id && $domain && $role && $name) {
1.252     albertel 7560: 	 $hostname{$id}=$name;
                   7561: 	 $hostdom{$id}=$domain;
                   7562: 	 if ($role eq 'library') { $libserv{$id}=$name; }
1.245     www      7563:        }
1.1       albertel 7564:     }
1.448     albertel 7565:     close($config);
1.619     albertel 7566:     # FIXME: dev server don't want this, production servers _do_ want this
1.654     albertel 7567:     #&get_iphost();
1.1       albertel 7568: }
                   7569: 
1.598     albertel 7570: sub get_iphost {
                   7571:     if (%iphost) { return %iphost; }
1.653     albertel 7572:     my %name_to_ip;
1.598     albertel 7573:     foreach my $id (keys(%hostname)) {
                   7574: 	my $name=$hostname{$id};
1.653     albertel 7575: 	my $ip;
                   7576: 	if (!exists($name_to_ip{$name})) {
                   7577: 	    $ip = gethostbyname($name);
                   7578: 	    if (!$ip || length($ip) ne 4) {
1.826     www      7579: 		&logthis("Skipping host $id name $name no IP found");
1.653     albertel 7580: 		next;
                   7581: 	    }
                   7582: 	    $ip=inet_ntoa($ip);
                   7583: 	    $name_to_ip{$name} = $ip;
                   7584: 	} else {
                   7585: 	    $ip = $name_to_ip{$name};
1.598     albertel 7586: 	}
                   7587: 	push(@{$iphost{$ip}},$id);
                   7588:     }
                   7589:     return %iphost;
                   7590: }
                   7591: 
1.1       albertel 7592: # ------------------------------------------------------ Read spare server file
                   7593: {
1.448     albertel 7594:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 7595: 
                   7596:     while (my $configline=<$config>) {
                   7597:        chomp($configline);
1.284     matthew  7598:        if ($configline) {
1.784     albertel 7599: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 7600: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 7601: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 7602:        }
                   7603:     }
1.448     albertel 7604:     close($config);
1.1       albertel 7605: }
1.11      www      7606: # ------------------------------------------------------------ Read permissions
                   7607: {
1.448     albertel 7608:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      7609: 
                   7610:     while (my $configline=<$config>) {
1.448     albertel 7611: 	chomp($configline);
                   7612: 	if ($configline) {
                   7613: 	    my ($role,$perm)=split(/ /,$configline);
                   7614: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   7615: 	}
1.11      www      7616:     }
1.448     albertel 7617:     close($config);
1.11      www      7618: }
                   7619: 
                   7620: # -------------------------------------------- Read plain texts for permissions
                   7621: {
1.448     albertel 7622:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      7623: 
                   7624:     while (my $configline=<$config>) {
1.448     albertel 7625: 	chomp($configline);
                   7626: 	if ($configline) {
1.742     raeburn  7627: 	    my ($short,@plain)=split(/:/,$configline);
                   7628:             %{$prp{$short}} = ();
                   7629: 	    if (@plain > 0) {
                   7630:                 $prp{$short}{'std'} = $plain[0];
                   7631:                 for (my $i=1; $i<@plain; $i++) {
                   7632:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   7633:                 }
                   7634:             }
1.448     albertel 7635: 	}
1.135     www      7636:     }
1.448     albertel 7637:     close($config);
1.135     www      7638: }
                   7639: 
                   7640: # ---------------------------------------------------------- Read package table
                   7641: {
1.448     albertel 7642:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      7643: 
                   7644:     while (my $configline=<$config>) {
1.483     albertel 7645: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 7646: 	chomp($configline);
                   7647: 	my ($short,$plain)=split(/:/,$configline);
                   7648: 	my ($pack,$name)=split(/\&/,$short);
                   7649: 	if ($plain ne '') {
                   7650: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   7651: 	    $packagetab{$short}=$plain; 
                   7652: 	}
1.11      www      7653:     }
1.448     albertel 7654:     close($config);
1.329     matthew  7655: }
                   7656: 
                   7657: # ------------- set up temporary directory
                   7658: {
                   7659:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   7660: 
1.11      www      7661: }
                   7662: 
1.794     albertel 7663: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   7664: 				'compress_threshold'=> 20_000,
                   7665:  			        });
1.185     www      7666: 
1.281     www      7667: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      7668: $dumpcount=0;
1.22      www      7669: 
1.163     harris41 7670: &logtouch();
1.672     albertel 7671: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      7672: $readit=1;
1.564     albertel 7673:     {
                   7674: 	use integer;
                   7675: 	my $test=(2**32)+1;
1.568     albertel 7676: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 7677: 	&logthis(" Detected 64bit platform ($_64bit)");
                   7678:     }
1.195     www      7679: }
1.1       albertel 7680: }
1.179     www      7681: 
1.1       albertel 7682: 1;
1.191     harris41 7683: __END__
                   7684: 
1.243     albertel 7685: =pod
                   7686: 
1.191     harris41 7687: =head1 NAME
                   7688: 
1.243     albertel 7689: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 7690: 
                   7691: =head1 SYNOPSIS
                   7692: 
1.243     albertel 7693: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 7694: 
                   7695:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   7696: 
1.243     albertel 7697: Common parameters:
                   7698: 
                   7699: =over 4
                   7700: 
                   7701: =item *
                   7702: 
                   7703: $uname : an internal username (if $cname expecting a course Id specifically)
                   7704: 
                   7705: =item *
                   7706: 
                   7707: $udom : a domain (if $cdom expecting a course's domain specifically)
                   7708: 
                   7709: =item *
                   7710: 
                   7711: $symb : a resource instance identifier
                   7712: 
                   7713: =item *
                   7714: 
                   7715: $namespace : the name of a .db file that contains the data needed or
                   7716: being set.
                   7717: 
                   7718: =back
                   7719: 
1.394     bowersj2 7720: =head1 OVERVIEW
1.191     harris41 7721: 
1.394     bowersj2 7722: lonnet provides subroutines which interact with the
                   7723: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   7724: about classes, users, and resources.
1.243     albertel 7725: 
                   7726: For many of these objects you can also use this to store data about
                   7727: them or modify them in various ways.
1.191     harris41 7728: 
1.394     bowersj2 7729: =head2 Symbs
1.191     harris41 7730: 
1.394     bowersj2 7731: To identify a specific instance of a resource, LON-CAPA uses symbols
                   7732: or "symbs"X<symb>. These identifiers are built from the URL of the
                   7733: map, the resource number of the resource in the map, and the URL of
                   7734: the resource itself. The latter is somewhat redundant, but might help
                   7735: if maps change.
                   7736: 
                   7737: An example is
                   7738: 
                   7739:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   7740: 
                   7741: The respective map entry is
                   7742: 
                   7743:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   7744:   title="Problem 2">
                   7745:  </resource>
                   7746: 
                   7747: Symbs are used by the random number generator, as well as to store and
                   7748: restore data specific to a certain instance of for example a problem.
                   7749: 
                   7750: =head2 Storing And Retrieving Data
                   7751: 
                   7752: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   7753: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   7754: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   7755: is is the non-critical message twin of cstore. These functions are for
                   7756: handlers to store a perl hash to a user's permanent data space in an
                   7757: easy manner, and to retrieve it again on another call. It is expected
                   7758: that a handler would use this once at the beginning to retrieve data,
                   7759: and then again once at the end to send only the new data back.
                   7760: 
                   7761: The data is stored in the user's data directory on the user's
                   7762: homeserver under the ID of the course.
                   7763: 
                   7764: The hash that is returned by restore will have all of the previous
                   7765: value for all of the elements of the hash.
                   7766: 
                   7767: Example:
                   7768: 
                   7769:  #creating a hash
                   7770:  my %hash;
                   7771:  $hash{'foo'}='bar';
                   7772: 
                   7773:  #storing it
                   7774:  &Apache::lonnet::cstore(\%hash);
                   7775: 
                   7776:  #changing a value
                   7777:  $hash{'foo'}='notbar';
                   7778: 
                   7779:  #adding a new value
                   7780:  $hash{'bar'}='foo';
                   7781:  &Apache::lonnet::cstore(\%hash);
                   7782: 
                   7783:  #retrieving the hash
                   7784:  my %history=&Apache::lonnet::restore();
                   7785: 
                   7786:  #print the hash
                   7787:  foreach my $key (sort(keys(%history))) {
                   7788:    print("\%history{$key} = $history{$key}");
                   7789:  }
                   7790: 
                   7791: Will print out:
1.191     harris41 7792: 
1.394     bowersj2 7793:  %history{1:foo} = bar
                   7794:  %history{1:keys} = foo:timestamp
                   7795:  %history{1:timestamp} = 990455579
                   7796:  %history{2:bar} = foo
                   7797:  %history{2:foo} = notbar
                   7798:  %history{2:keys} = foo:bar:timestamp
                   7799:  %history{2:timestamp} = 990455580
                   7800:  %history{bar} = foo
                   7801:  %history{foo} = notbar
                   7802:  %history{timestamp} = 990455580
                   7803:  %history{version} = 2
                   7804: 
                   7805: Note that the special hash entries C<keys>, C<version> and
                   7806: C<timestamp> were added to the hash. C<version> will be equal to the
                   7807: total number of versions of the data that have been stored. The
                   7808: C<timestamp> attribute will be the UNIX time the hash was
                   7809: stored. C<keys> is available in every historical section to list which
                   7810: keys were added or changed at a specific historical revision of a
                   7811: hash.
                   7812: 
                   7813: B<Warning>: do not store the hash that restore returns directly. This
                   7814: will cause a mess since it will restore the historical keys as if the
                   7815: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 7816: 
1.394     bowersj2 7817: Calling convention:
1.191     harris41 7818: 
1.394     bowersj2 7819:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   7820:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 7821: 
1.394     bowersj2 7822: For more detailed information, see lonnet specific documentation.
1.191     harris41 7823: 
1.394     bowersj2 7824: =head1 RETURN MESSAGES
1.191     harris41 7825: 
1.394     bowersj2 7826: =over 4
1.191     harris41 7827: 
1.394     bowersj2 7828: =item * B<con_lost>: unable to contact remote host
1.191     harris41 7829: 
1.394     bowersj2 7830: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   7831: when the connection is brought back up
1.191     harris41 7832: 
1.394     bowersj2 7833: =item * B<con_failed>: unable to contact remote host and unable to save message
                   7834: for later delivery
1.191     harris41 7835: 
1.394     bowersj2 7836: =item * B<error:>: an error a occured, a description of the error follows the :
1.191     harris41 7837: 
1.394     bowersj2 7838: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 7839: that was requested
1.191     harris41 7840: 
1.243     albertel 7841: =back
1.191     harris41 7842: 
1.243     albertel 7843: =head1 PUBLIC SUBROUTINES
1.191     harris41 7844: 
1.243     albertel 7845: =head2 Session Environment Functions
1.191     harris41 7846: 
1.243     albertel 7847: =over 4
1.191     harris41 7848: 
1.394     bowersj2 7849: =item * 
                   7850: X<appenv()>
                   7851: B<appenv(%hash)>: the value of %hash is written to
                   7852: the user envirnoment file, and will be restored for each access this
1.620     albertel 7853: user makes during this session, also modifies the %env for the current
1.394     bowersj2 7854: process
1.191     harris41 7855: 
                   7856: =item *
1.394     bowersj2 7857: X<delenv()>
                   7858: B<delenv($regexp)>: removes all items from the session
                   7859: environment file that matches the regular expression in $regexp. The
1.620     albertel 7860: values are also delted from the current processes %env.
1.191     harris41 7861: 
1.795     albertel 7862: =item * get_env_multiple($name) 
                   7863: 
                   7864: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   7865: values may be defined and end up as an array ref.
                   7866: 
                   7867: returns an array of values
                   7868: 
1.243     albertel 7869: =back
                   7870: 
                   7871: =head2 User Information
1.191     harris41 7872: 
1.243     albertel 7873: =over 4
1.191     harris41 7874: 
                   7875: =item *
1.394     bowersj2 7876: X<queryauthenticate()>
                   7877: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 7878: authentication scheme
                   7879: 
                   7880: =item *
1.394     bowersj2 7881: X<authenticate()>
                   7882: B<authenticate($uname,$upass,$udom)>: try to
                   7883: authenticate user from domain's lib servers (first use the current
                   7884: one). C<$upass> should be the users password.
1.191     harris41 7885: 
                   7886: =item *
1.394     bowersj2 7887: X<homeserver()>
                   7888: B<homeserver($uname,$udom)>: find the server which has
                   7889: the user's directory and files (there must be only one), this caches
                   7890: the answer, and also caches if there is a borken connection.
1.191     harris41 7891: 
                   7892: =item *
1.394     bowersj2 7893: X<idget()>
                   7894: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   7895: (IDs are a unique resource in a domain, there must be only 1 ID per
                   7896: username, and only 1 username per ID in a specific domain) (returns
                   7897: hash: id=>name,id=>name)
1.191     harris41 7898: 
                   7899: =item *
1.394     bowersj2 7900: X<idrget()>
                   7901: B<idrget($udom,@unames)>: find the IDs behind a list of
                   7902: usernames (returns hash: name=>id,name=>id)
1.191     harris41 7903: 
                   7904: =item *
1.394     bowersj2 7905: X<idput()>
                   7906: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 7907: 
                   7908: =item *
1.394     bowersj2 7909: X<rolesinit()>
                   7910: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 7911: 
                   7912: =item *
1.551     albertel 7913: X<getsection()>
                   7914: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 7915: course $cname, return section name/number or '' for "not in course"
                   7916: and '-1' for "no section"
                   7917: 
                   7918: =item *
1.394     bowersj2 7919: X<userenvironment()>
                   7920: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 7921: passed in @what from the requested user's environment, returns a hash
                   7922: 
                   7923: =back
                   7924: 
                   7925: =head2 User Roles
                   7926: 
                   7927: =over 4
                   7928: 
                   7929: =item *
                   7930: 
1.810     raeburn  7931: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 7932:  F: full access
                   7933:  U,I,K: authentication modes (cxx only)
                   7934:  '': forbidden
                   7935:  1: user needs to choose course
                   7936:  2: browse allowed
1.766     albertel 7937:  A: passphrase authentication needed
1.243     albertel 7938: 
                   7939: =item *
                   7940: 
                   7941: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   7942: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   7943: and course level
                   7944: 
                   7945: =item *
                   7946: 
                   7947: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   7948: explanation of a user role term
                   7949: 
                   7950: =back
                   7951: 
                   7952: =head2 User Modification
                   7953: 
                   7954: =over 4
                   7955: 
                   7956: =item *
                   7957: 
                   7958: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
                   7959: user for the level given by URL.  Optional start and end dates (leave empty
                   7960: string or zero for "no date")
1.191     harris41 7961: 
                   7962: =item *
                   7963: 
1.243     albertel 7964: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   7965: change a users, password, possible return values are: ok,
                   7966: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   7967: refused
1.191     harris41 7968: 
                   7969: =item *
                   7970: 
1.243     albertel 7971: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 7972: 
                   7973: =item *
                   7974: 
1.243     albertel 7975: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
                   7976: modify user
1.191     harris41 7977: 
                   7978: =item *
                   7979: 
1.286     matthew  7980: modifystudent
                   7981: 
                   7982: modify a students enrollment and identification information.
                   7983: The course id is resolved based on the current users environment.  
                   7984: This means the envoking user must be a course coordinator or otherwise
                   7985: associated with a course.
                   7986: 
1.297     matthew  7987: This call is essentially a wrapper for lonnet::modifyuser and
                   7988: lonnet::modify_student_enrollment
1.286     matthew  7989: 
                   7990: Inputs: 
                   7991: 
                   7992: =over 4
                   7993: 
                   7994: =item B<$udom> Students loncapa domain
                   7995: 
                   7996: =item B<$uname> Students loncapa login name
                   7997: 
                   7998: =item B<$uid> Students id/student number
                   7999: 
                   8000: =item B<$umode> Students authentication mode
                   8001: 
                   8002: =item B<$upass> Students password
                   8003: 
                   8004: =item B<$first> Students first name
                   8005: 
                   8006: =item B<$middle> Students middle name
                   8007: 
                   8008: =item B<$last> Students last name
                   8009: 
                   8010: =item B<$gene> Students generation
                   8011: 
                   8012: =item B<$usec> Students section in course
                   8013: 
                   8014: =item B<$end> Unix time of the roles expiration
                   8015: 
                   8016: =item B<$start> Unix time of the roles start date
                   8017: 
                   8018: =item B<$forceid> If defined, allow $uid to be changed
                   8019: 
                   8020: =item B<$desiredhome> server to use as home server for student
                   8021: 
                   8022: =back
1.297     matthew  8023: 
                   8024: =item *
                   8025: 
                   8026: modify_student_enrollment
                   8027: 
                   8028: Change a students enrollment status in a class.  The environment variable
                   8029: 'role.request.course' must be defined for this function to proceed.
                   8030: 
                   8031: Inputs:
                   8032: 
                   8033: =over 4
                   8034: 
                   8035: =item $udom, students domain
                   8036: 
                   8037: =item $uname, students name
                   8038: 
                   8039: =item $uid, students user id
                   8040: 
                   8041: =item $first, students first name
                   8042: 
                   8043: =item $middle
                   8044: 
                   8045: =item $last
                   8046: 
                   8047: =item $gene
                   8048: 
                   8049: =item $usec
                   8050: 
                   8051: =item $end
                   8052: 
                   8053: =item $start
                   8054: 
                   8055: =back
                   8056: 
1.191     harris41 8057: 
                   8058: =item *
                   8059: 
1.243     albertel 8060: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   8061: custom role; give a custom role to a user for the level given by URL.  Specify
                   8062: name and domain of role author, and role name
1.191     harris41 8063: 
                   8064: =item *
                   8065: 
1.243     albertel 8066: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 8067: 
                   8068: =item *
                   8069: 
1.243     albertel 8070: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   8071: 
                   8072: =back
                   8073: 
                   8074: =head2 Course Infomation
                   8075: 
                   8076: =over 4
1.191     harris41 8077: 
                   8078: =item *
                   8079: 
1.631     albertel 8080: coursedescription($courseid) : returns a hash of information about the
                   8081: specified course id, including all environment settings for the
                   8082: course, the description of the course will be in the hash under the
                   8083: key 'description'
1.191     harris41 8084: 
                   8085: =item *
                   8086: 
1.624     albertel 8087: resdata($name,$domain,$type,@which) : request for current parameter
                   8088: setting for a specific $type, where $type is either 'course' or 'user',
                   8089: @what should be a list of parameters to ask about. This routine caches
                   8090: answers for 5 minutes.
1.243     albertel 8091: 
                   8092: =back
                   8093: 
                   8094: =head2 Course Modification
                   8095: 
                   8096: =over 4
1.191     harris41 8097: 
                   8098: =item *
                   8099: 
1.243     albertel 8100: writecoursepref($courseid,%prefs) : write preferences (environment
                   8101: database) for a course
1.191     harris41 8102: 
                   8103: =item *
                   8104: 
1.243     albertel 8105: createcourse($udom,$description,$url) : make/modify course
                   8106: 
                   8107: =back
                   8108: 
                   8109: =head2 Resource Subroutines
                   8110: 
                   8111: =over 4
1.191     harris41 8112: 
                   8113: =item *
                   8114: 
1.243     albertel 8115: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 8116: 
                   8117: =item *
                   8118: 
1.243     albertel 8119: repcopy($filename) : subscribes to the requested file, and attempts to
                   8120: replicate from the owning library server, Might return
1.607     raeburn  8121: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   8122: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 8123: resource. Expects the local filesystem pathname
                   8124: (/home/httpd/html/res/....)
                   8125: 
                   8126: =back
                   8127: 
                   8128: =head2 Resource Information
                   8129: 
                   8130: =over 4
1.191     harris41 8131: 
                   8132: =item *
                   8133: 
1.243     albertel 8134: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   8135: a vairety of different possible values, $varname should be a request
                   8136: string, and the other parameters can be used to specify who and what
                   8137: one is asking about.
                   8138: 
                   8139: Possible values for $varname are environment.lastname (or other item
                   8140: from the envirnment hash), user.name (or someother aspect about the
                   8141: user), resource.0.maxtries (or some other part and parameter of a
                   8142: resource)
1.204     albertel 8143: 
                   8144: =item *
                   8145: 
1.243     albertel 8146: directcondval($number) : get current value of a condition; reads from a state
                   8147: string
1.204     albertel 8148: 
                   8149: =item *
                   8150: 
1.243     albertel 8151: condval($condidx) : value of condition index based on state
1.204     albertel 8152: 
                   8153: =item *
                   8154: 
1.243     albertel 8155: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   8156: resource's metadata, $what should be either a specific key, or either
                   8157: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   8158: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   8159: 
                   8160: this function automatically caches all requests
1.191     harris41 8161: 
                   8162: =item *
                   8163: 
1.243     albertel 8164: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   8165: network of library servers; returns file handle of where SQL and regex results
                   8166: will be stored for query
1.191     harris41 8167: 
                   8168: =item *
                   8169: 
1.243     albertel 8170: symbread($filename) : return symbolic list entry (filename argument optional);
                   8171: returns the data handle
1.191     harris41 8172: 
                   8173: =item *
                   8174: 
1.243     albertel 8175: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 8176: a possible symb for the URL in $thisfn, and if is an encryypted
                   8177: resource that the user accessed using /enc/ returns a 1 on success, 0
                   8178: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 8179: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 8180: 
1.191     harris41 8181: 
                   8182: =item *
                   8183: 
1.243     albertel 8184: symbclean($symb) : removes versions numbers from a symb, returns the
                   8185: cleaned symb
1.191     harris41 8186: 
                   8187: =item *
                   8188: 
1.243     albertel 8189: is_on_map($uri) : checks if the $uri is somewhere on the current
                   8190: course map, user must be in a course for it to work.
1.191     harris41 8191: 
                   8192: =item *
                   8193: 
1.243     albertel 8194: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 8195: 
                   8196: =item *
                   8197: 
1.243     albertel 8198: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   8199: a random seed, all arguments are optional, if they aren't sent it uses the
                   8200: environment to derive them. Note: if symb isn't sent and it can't get one
                   8201: from &symbread it will use the current time as its return value
1.191     harris41 8202: 
                   8203: =item *
                   8204: 
1.243     albertel 8205: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   8206: unfakeable, receipt
1.191     harris41 8207: 
                   8208: =item *
                   8209: 
1.620     albertel 8210: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 8211: 
                   8212: =item *
                   8213: 
1.243     albertel 8214: countacc($url) : count the number of accesses to a given URL
1.191     harris41 8215: 
                   8216: =item *
                   8217: 
1.243     albertel 8218: 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 8219: 
                   8220: =item *
                   8221: 
1.243     albertel 8222: 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 8223: 
                   8224: =item *
                   8225: 
1.243     albertel 8226: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 8227: 
                   8228: =item *
                   8229: 
1.243     albertel 8230: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   8231: forcing spreadsheet to reevaluate the resource scores next time.
                   8232: 
                   8233: =back
                   8234: 
                   8235: =head2 Storing/Retreiving Data
                   8236: 
                   8237: =over 4
1.191     harris41 8238: 
                   8239: =item *
                   8240: 
1.243     albertel 8241: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   8242: for this url; hashref needs to be given and should be a \%hashname; the
                   8243: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 8244: be derived from the env
1.191     harris41 8245: 
                   8246: =item *
                   8247: 
1.243     albertel 8248: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   8249: uses critical subroutine
1.191     harris41 8250: 
                   8251: =item *
                   8252: 
1.243     albertel 8253: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   8254: all args are optional
1.191     harris41 8255: 
                   8256: =item *
                   8257: 
1.717     albertel 8258: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   8259: dumps the complete (or key matching regexp) namespace into a hash
                   8260: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   8261: normally &store()ed into
                   8262: 
                   8263: $range should be either an integer '100' (give me the first 100
                   8264:                                            matching records)
                   8265:               or be  two integers sperated by a - with no spaces
                   8266:                  '30-50' (give me the 30th through the 50th matching
                   8267:                           records)
                   8268: 
                   8269: 
                   8270: =item *
                   8271: 
                   8272: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   8273: replaces a &store() version of data with a replacement set of data
                   8274: for a particular resource in a namespace passed in the $storehash hash 
                   8275: reference
                   8276: 
                   8277: =item *
                   8278: 
1.243     albertel 8279: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   8280: works very similar to store/cstore, but all data is stored in a
                   8281: temporary location and can be reset using tmpreset, $storehash should
                   8282: be a hash reference, returns nothing on success
1.191     harris41 8283: 
                   8284: =item *
                   8285: 
1.243     albertel 8286: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   8287: similar to restore, but all data is stored in a temporary location and
                   8288: can be reset using tmpreset. Returns a hash of values on success,
                   8289: error string otherwise.
1.191     harris41 8290: 
                   8291: =item *
                   8292: 
1.243     albertel 8293: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   8294: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 8295: 
                   8296: =item *
                   8297: 
1.243     albertel 8298: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   8299: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 8300: 
                   8301: =item *
                   8302: 
1.243     albertel 8303: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   8304: namesp ($udom and $uname are optional)
1.191     harris41 8305: 
                   8306: =item *
                   8307: 
1.702     albertel 8308: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 8309: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 8310: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  8311: 
1.702     albertel 8312: $range should be either an integer '100' (give me the first 100
                   8313:                                            matching records)
                   8314:               or be  two integers sperated by a - with no spaces
                   8315:                  '30-50' (give me the 30th through the 50th matching
                   8316:                           records)
1.449     matthew  8317: =item *
                   8318: 
                   8319: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   8320: $store can be a scalar, an array reference, or if the amount to be 
                   8321: incremented is > 1, a hash reference.
                   8322: 
                   8323: ($udom and $uname are optional)
1.191     harris41 8324: 
                   8325: =item *
                   8326: 
1.243     albertel 8327: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   8328: ($udom and $uname are optional)
1.191     harris41 8329: 
                   8330: =item *
                   8331: 
1.243     albertel 8332: cput($namespace,$storehash,$udom,$uname) : critical put
                   8333: ($udom and $uname are optional)
1.191     harris41 8334: 
                   8335: =item *
                   8336: 
1.748     albertel 8337: newput($namespace,$storehash,$udom,$uname) :
                   8338: 
                   8339: Attempts to store the items in the $storehash, but only if they don't
                   8340: currently exist, if this succeeds you can be certain that you have 
                   8341: successfully created a new key value pair in the $namespace db.
                   8342: 
                   8343: 
                   8344: Args:
                   8345:  $namespace: name of database to store values to
                   8346:  $storehash: hashref to store to the db
                   8347:  $udom: (optional) domain of user containing the db
                   8348:  $uname: (optional) name of user caontaining the db
                   8349: 
                   8350: Returns:
                   8351:  'ok' -> succeeded in storing all keys of $storehash
                   8352:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   8353:                         least <key> already existed in the db (other
                   8354:                         requested keys may also already exist)
                   8355:  'error: <msg>' -> unable to tie the DB or other erorr occured
                   8356:  'con_lost' -> unable to contact request server
                   8357:  'refused' -> action was not allowed by remote machine
                   8358: 
                   8359: 
                   8360: =item *
                   8361: 
1.243     albertel 8362: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   8363: reference filled in from namesp (encrypts the return communication)
                   8364: ($udom and $uname are optional)
1.191     harris41 8365: 
                   8366: =item *
                   8367: 
1.243     albertel 8368: log($udom,$name,$home,$message) : write to permanent log for user; use
                   8369: critical subroutine
                   8370: 
1.806     raeburn  8371: =item *
                   8372: 
                   8373: get_dom($namespace,$storearr,$udomain) : returns hash with keys from array
                   8374: reference filled in from namespace found in domain level on primary domain server ($udomain is optional)
                   8375: 
                   8376: =item *
                   8377: 
                   8378: put_dom($namespace,$storehash,$udomain) :  stores hash in namespace at domain level on primary domain server ($udomain is optional)
                   8379: 
1.243     albertel 8380: =back
                   8381: 
                   8382: =head2 Network Status Functions
                   8383: 
                   8384: =over 4
1.191     harris41 8385: 
                   8386: =item *
                   8387: 
                   8388: dirlist($uri) : return directory list based on URI
                   8389: 
                   8390: =item *
                   8391: 
1.243     albertel 8392: spareserver() : find server with least workload from spare.tab
                   8393: 
                   8394: =back
                   8395: 
                   8396: =head2 Apache Request
                   8397: 
                   8398: =over 4
1.191     harris41 8399: 
                   8400: =item *
                   8401: 
1.243     albertel 8402: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   8403: localhost, posts hash
                   8404: 
                   8405: =back
                   8406: 
                   8407: =head2 Data to String to Data
                   8408: 
                   8409: =over 4
1.191     harris41 8410: 
                   8411: =item *
                   8412: 
1.243     albertel 8413: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   8414: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 8415: 
                   8416: =item *
                   8417: 
1.243     albertel 8418: hashref2str($hashref) : convert a hashref into a string complete with
                   8419: escaping and '=' and '&' separators, supports elements that are
                   8420: arrayrefs and hashrefs
1.191     harris41 8421: 
                   8422: =item *
                   8423: 
1.243     albertel 8424: arrayref2str($arrayref) : convert an arrayref into a string complete
                   8425: with escaping and '&' separators, supports elements that are arrayrefs
                   8426: and hashrefs
1.191     harris41 8427: 
                   8428: =item *
                   8429: 
1.243     albertel 8430: str2hash($string) : convert string to hash using unescaping and
                   8431: splitting on '=' and '&', supports elements that are arrayrefs and
                   8432: hashrefs
1.191     harris41 8433: 
                   8434: =item *
                   8435: 
1.243     albertel 8436: str2array($string) : convert string to hash using unescaping and
                   8437: splitting on '&', supports elements that are arrayrefs and hashrefs
                   8438: 
                   8439: =back
                   8440: 
                   8441: =head2 Logging Routines
                   8442: 
                   8443: =over 4
                   8444: 
                   8445: These routines allow one to make log messages in the lonnet.log and
                   8446: lonnet.perm logfiles.
1.191     harris41 8447: 
                   8448: =item *
                   8449: 
1.243     albertel 8450: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 8451: 
                   8452: =item *
                   8453: 
1.243     albertel 8454: logthis() : append message to the normal lonnet.log file, it gets
                   8455: preiodically rolled over and deleted.
1.191     harris41 8456: 
                   8457: =item *
                   8458: 
1.243     albertel 8459: logperm() : append a permanent message to lonnet.perm.log, this log
                   8460: file never gets deleted by any automated portion of the system, only
                   8461: messages of critical importance should go in here.
                   8462: 
                   8463: =back
                   8464: 
                   8465: =head2 General File Helper Routines
                   8466: 
                   8467: =over 4
1.191     harris41 8468: 
                   8469: =item *
                   8470: 
1.481     raeburn  8471: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   8472: (a) files in /uploaded
                   8473:   (i) If a local copy of the file exists - 
                   8474:       compares modification date of local copy with last-modified date for 
                   8475:       definitive version stored on home server for course. If local copy is 
                   8476:       stale, requests a new version from the home server and stores it. 
                   8477:       If the original has been removed from the home server, then local copy 
                   8478:       is unlinked.
                   8479:   (ii) If local copy does not exist -
                   8480:       requests the file from the home server and stores it. 
                   8481:   
                   8482:   If $caller is 'uploadrep':  
                   8483:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   8484:     for request for files originally uploaded via DOCS. 
                   8485:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   8486:   
                   8487:   Otherwise:
                   8488:      This indicates a call from the content generation phase of the request.
                   8489:      -  returns the entire contents of the file or -1.
                   8490:      
                   8491: (b) files in /res
                   8492:    - returns the entire contents of a file or -1; 
                   8493:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 8494: 
1.712     albertel 8495: 
                   8496: =item *
                   8497: 
                   8498: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   8499:                   reference
                   8500: 
                   8501: returns either a stat() list of data about the file or an empty list
                   8502: if the file doesn't exist or couldn't find out about it (connection
                   8503: problems or user unknown)
                   8504: 
1.191     harris41 8505: =item *
                   8506: 
1.243     albertel 8507: filelocation($dir,$file) : returns file system location of a file
                   8508: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   8509: directory that relative $file lookups are to looked in ($dir of /a/dir
                   8510: and a file of ../bob will become /a/bob)
1.191     harris41 8511: 
                   8512: =item *
                   8513: 
                   8514: hreflocation($dir,$file) : returns file system location or a URL; same as
                   8515: filelocation except for hrefs
                   8516: 
                   8517: =item *
                   8518: 
                   8519: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   8520: 
1.243     albertel 8521: =back
                   8522: 
1.608     albertel 8523: =head2 Usererfile file routines (/uploaded*)
                   8524: 
                   8525: =over 4
                   8526: 
                   8527: =item *
                   8528: 
                   8529: userfileupload(): main rotine for putting a file in a user or course's
                   8530:                   filespace, arguments are,
                   8531: 
1.620     albertel 8532:  formname - required - this is the name of the element in $env where the
1.608     albertel 8533:            filename, and the contents of the file to create/modifed exist
1.620     albertel 8534:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   8535:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 8536:  coursedoc - if true, store the file in the course of the active role
                   8537:              of the current user
                   8538:  subdir - required - subdirectory to put the file in under ../userfiles/
                   8539:          if undefined, it will be placed in "unknown"
                   8540: 
                   8541:  (This routine calls clean_filename() to remove any dangerous
                   8542:  characters from the filename, and then calls finuserfileupload() to
                   8543:  complete the transaction)
                   8544: 
                   8545:  returns either the url of the uploaded file (/uploaded/....) if successful
                   8546:  and /adm/notfound.html if unsuccessful
                   8547: 
                   8548: =item *
                   8549: 
                   8550: clean_filename(): routine for cleaing a filename up for storage in
                   8551:                  userfile space, argument is:
                   8552: 
                   8553:  filename - proposed filename
                   8554: 
                   8555: returns: the new clean filename
                   8556: 
                   8557: =item *
                   8558: 
                   8559: finishuserfileupload(): routine that creaes and sends the file to
                   8560: userspace, probably shouldn't be called directly
                   8561: 
                   8562:   docuname: username or courseid of destination for the file
                   8563:   docudom: domain of user/course of destination for the file
                   8564:   formname: same as for userfileupload()
                   8565:   fname: filename (inculding subdirectories) for the file
                   8566: 
                   8567:  returns either the url of the uploaded file (/uploaded/....) if successful
                   8568:  and /adm/notfound.html if unsuccessful
                   8569: 
                   8570: =item *
                   8571: 
                   8572: renameuserfile(): renames an existing userfile to a new name
                   8573: 
                   8574:   Args:
                   8575:    docuname: username or courseid of destination for the file
                   8576:    docudom: domain of user/course of destination for the file
                   8577:    old: current file name (including any subdirs under userfiles)
                   8578:    new: desired file name (including any subdirs under userfiles)
                   8579: 
                   8580: =item *
                   8581: 
                   8582: mkdiruserfile(): creates a directory is a userfiles dir
                   8583: 
                   8584:   Args:
                   8585:    docuname: username or courseid of destination for the file
                   8586:    docudom: domain of user/course of destination for the file
                   8587:    dir: dir to create (including any subdirs under userfiles)
                   8588: 
                   8589: =item *
                   8590: 
                   8591: removeuserfile(): removes a file that exists in userfiles
                   8592: 
                   8593:   Args:
                   8594:    docuname: username or courseid of destination for the file
                   8595:    docudom: domain of user/course of destination for the file
                   8596:    fname: filname to delete (including any subdirs under userfiles)
                   8597: 
                   8598: =item *
                   8599: 
                   8600: removeuploadedurl(): convience function for removeuserfile()
                   8601: 
                   8602:   Args:
                   8603:    url:  a full /uploaded/... url to delete
                   8604: 
1.747     albertel 8605: =item * 
                   8606: 
                   8607: get_portfile_permissions():
                   8608:   Args:
                   8609:     domain: domain of user or course contain the portfolio files
                   8610:     user: name of user or num of course contain the portfolio files
                   8611:   Returns:
                   8612:     hashref of a dump of the proper file_permissions.db
                   8613:    
                   8614: 
                   8615: =item * 
                   8616: 
                   8617: get_access_controls():
                   8618: 
                   8619: Args:
                   8620:   current_permissions: the hash ref returned from get_portfile_permissions()
                   8621:   group: (optional) the group you want the files associated with
                   8622:   file: (optional) the file you want access info on
                   8623: 
                   8624: Returns:
1.749     raeburn  8625:     a hash (keys are file names) of hashes containing
                   8626:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   8627:         values are XML containing access control settings (see below) 
1.747     albertel 8628: 
                   8629: Internal notes:
                   8630: 
1.749     raeburn  8631:  access controls are stored in file_permissions.db as key=value pairs.
                   8632:     key -> path to file/file_name\0uniqueID:scope_end_start
                   8633:         where scope -> public,guest,course,group,domains or users.
                   8634:               end -> UNIX time for end of access (0 -> no end date)
                   8635:               start -> UNIX time for start of access
                   8636: 
                   8637:     value -> XML description of access control
                   8638:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   8639:             <start></start>
                   8640:             <end></end>
                   8641: 
                   8642:             <password></password>  for scope type = guest
                   8643: 
                   8644:             <domain></domain>     for scope type = course or group
                   8645:             <number></number>
                   8646:             <roles id="">
                   8647:              <role></role>
                   8648:              <access></access>
                   8649:              <section></section>
                   8650:              <group></group>
                   8651:             </roles>
                   8652: 
                   8653:             <dom></dom>         for scope type = domains
                   8654: 
                   8655:             <users>             for scope type = users
                   8656:              <user>
                   8657:               <uname></uname>
                   8658:               <udom></udom>
                   8659:              </user>
                   8660:             </users>
                   8661:            </scope> 
                   8662:               
                   8663:  Access data is also aggregated for each file in an additional key=value pair:
                   8664:  key -> path to file/file_name\0accesscontrol 
                   8665:  value -> reference to hash
                   8666:           hash contains key = value pairs
                   8667:           where key = uniqueID:scope_end_start
                   8668:                 value = UNIX time record was last updated
                   8669: 
                   8670:           Used to improve speed of look-ups of access controls for each file.  
                   8671:  
                   8672:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   8673: 
                   8674: modify_access_controls():
                   8675: 
                   8676: Modifies access controls for a portfolio file
                   8677: Args
                   8678: 1. file name
                   8679: 2. reference to hash of required changes,
                   8680: 3. domain
                   8681: 4. username
                   8682:   where domain,username are the domain of the portfolio owner 
                   8683:   (either a user or a course) 
                   8684: 
                   8685: Returns:
                   8686: 1. result of additions or updates ('ok' or 'error', with error message). 
                   8687: 2. result of deletions ('ok' or 'error', with error message).
                   8688: 3. reference to hash of any new or updated access controls.
                   8689: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   8690:    key = integer (inbound ID)
                   8691:    value = uniqueID  
1.747     albertel 8692: 
1.608     albertel 8693: =back
                   8694: 
1.243     albertel 8695: =head2 HTTP Helper Routines
                   8696: 
                   8697: =over 4
                   8698: 
1.191     harris41 8699: =item *
                   8700: 
                   8701: escape() : unpack non-word characters into CGI-compatible hex codes
                   8702: 
                   8703: =item *
                   8704: 
                   8705: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   8706: 
1.243     albertel 8707: =back
                   8708: 
                   8709: =head1 PRIVATE SUBROUTINES
                   8710: 
                   8711: =head2 Underlying communication routines (Shouldn't call)
                   8712: 
                   8713: =over 4
                   8714: 
                   8715: =item *
                   8716: 
                   8717: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   8718: 
                   8719: =item *
                   8720: 
                   8721: reply() : uses subreply to send a message to remote machine, logs all failures
                   8722: 
                   8723: =item *
                   8724: 
                   8725: critical() : passes a critical message to another server; if cannot
                   8726: get through then place message in connection buffer directory and
                   8727: returns con_delayed, if incapable of saving message, returns
                   8728: con_failed
                   8729: 
                   8730: =item *
                   8731: 
                   8732: reconlonc() : tries to reconnect lonc client processes.
                   8733: 
                   8734: =back
                   8735: 
                   8736: =head2 Resource Access Logging
                   8737: 
                   8738: =over 4
                   8739: 
                   8740: =item *
                   8741: 
                   8742: flushcourselogs() : flush (save) buffer logs and access logs
                   8743: 
                   8744: =item *
                   8745: 
                   8746: courselog($what) : save message for course in hash
                   8747: 
                   8748: =item *
                   8749: 
                   8750: courseacclog($what) : save message for course using &courselog().  Perform
                   8751: special processing for specific resource types (problems, exams, quizzes, etc).
                   8752: 
1.191     harris41 8753: =item *
                   8754: 
                   8755: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   8756: as a PerlChildExitHandler
1.243     albertel 8757: 
                   8758: =back
                   8759: 
                   8760: =head2 Other
                   8761: 
                   8762: =over 4
                   8763: 
                   8764: =item *
                   8765: 
                   8766: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 8767: 
                   8768: =back
                   8769: 
                   8770: =cut

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