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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.824.2.4! albertel    4: # $Id: lonnet.pm,v 1.824.2.3 2007/03/17 04:13:06 albertel Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.1       albertel   30: package Apache::lonnet;
                     31: 
                     32: use strict;
1.8       www        33: use LWP::UserAgent();
1.15      www        34: use HTTP::Headers;
1.486     www        35: use HTTP::Date;
                     36: # use Date::Parse;
1.11      www        37: use vars 
1.599     albertel   38: qw(%perlvar %hostname %badServerCache %iphost %spareid %hostdom 
                     39:    %libserv %pr %prp $memcache %packagetab 
1.662     raeburn    40:    %courselogs %accesshash %userrolehash %domainrolehash $processmarker $dumpcount 
1.741     raeburn    41:    %coursedombuf %coursenumbuf %coursehombuf %coursedescrbuf %courseinstcodebuf %courseownerbuf %coursetypebuf
1.599     albertel   42:    %domaindescription %domain_auth_def %domain_auth_arg_def 
1.685     raeburn    43:    %domain_lang_def %domain_city %domain_longi %domain_lati %domain_primary
                     44:    $tmpdir $_64bit %env);
1.403     www        45: 
1.1       albertel   46: use IO::Socket;
1.31      www        47: use GDBM_File;
1.208     albertel   48: use HTML::LCParser;
1.637     raeburn    49: use HTML::Parser;
1.88      www        50: use Fcntl qw(:flock);
1.557     albertel   51: use Storable qw(lock_store lock_nstore lock_retrieve freeze thaw nfreeze);
1.539     albertel   52: use Time::HiRes qw( gettimeofday tv_interval );
1.599     albertel   53: use Cache::Memcached;
1.676     albertel   54: use Digest::MD5;
1.790     albertel   55: use Math::Random;
1.807     albertel   56: use LONCAPA qw(:DEFAULT :match);
1.740     www        57: use LONCAPA::Configuration;
1.676     albertel   58: 
1.195     www        59: my $readit;
1.550     foxr       60: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel   61: 
1.619     albertel   62: require Exporter;
                     63: 
                     64: our @ISA = qw (Exporter);
                     65: our @EXPORT = qw(%env);
                     66: 
1.449     matthew    67: =pod
                     68: 
                     69: =head1 Package Variables
                     70: 
                     71: These are largely undocumented, so if you decipher one please note it here.
                     72: 
                     73: =over 4
                     74: 
                     75: =item $processmarker
                     76: 
                     77: Contains the time this process was started and this servers host id.
                     78: 
                     79: =item $dumpcount
                     80: 
                     81: Counts the number of times a message log flush has been attempted (regardless
                     82: of success) by this process.  Used as part of the filename when messages are
                     83: delayed.
                     84: 
                     85: =back
                     86: 
                     87: =cut
                     88: 
                     89: 
1.1       albertel   90: # --------------------------------------------------------------------- Logging
1.729     www        91: {
                     92:     my $logid;
                     93:     sub instructor_log {
                     94: 	my ($hash_name,$storehash,$delflag,$uname,$udom)=@_;
                     95: 	$logid++;
                     96: 	my $id=time().'00000'.$$.'00000'.$logid;
                     97: 	return &Apache::lonnet::put('nohist_'.$hash_name,
1.730     www        98: 				    { $id => {
                     99: 					'exe_uname' => $env{'user.name'},
                    100: 					'exe_udom'  => $env{'user.domain'},
                    101: 					'exe_time'  => time(),
                    102: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    103: 					'delflag'   => $delflag,
                    104: 					'logentry'  => $storehash,
                    105: 					'uname'     => $uname,
                    106: 					'udom'      => $udom,
                    107: 				    }
                    108: 				  },
1.729     www       109: 				    $env{'course.'.$env{'request.course.id'}.'.domain'},
                    110: 				    $env{'course.'.$env{'request.course.id'}.'.num'}
                    111: 				    );
                    112:     }
                    113: }
1.1       albertel  114: 
1.163     harris41  115: sub logtouch {
                    116:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  117:     unless (-e "$execdir/logs/lonnet.log") {	
                    118: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  119: 	close $fh;
                    120:     }
                    121:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    122:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    123: }
                    124: 
1.1       albertel  125: sub logthis {
                    126:     my $message=shift;
                    127:     my $execdir=$perlvar{'lonDaemons'};
                    128:     my $now=time;
                    129:     my $local=localtime($now);
1.448     albertel  130:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
                    131: 	print $fh "$local ($$): $message\n";
                    132: 	close($fh);
                    133:     }
1.1       albertel  134:     return 1;
                    135: }
                    136: 
                    137: sub logperm {
                    138:     my $message=shift;
                    139:     my $execdir=$perlvar{'lonDaemons'};
                    140:     my $now=time;
                    141:     my $local=localtime($now);
1.448     albertel  142:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    143: 	print $fh "$now:$message:$local\n";
                    144: 	close($fh);
                    145:     }
1.1       albertel  146:     return 1;
                    147: }
                    148: 
                    149: # -------------------------------------------------- Non-critical communication
                    150: sub subreply {
                    151:     my ($cmd,$server)=@_;
1.704     albertel  152:     my $peerfile="$perlvar{'lonSockDir'}/".$hostname{$server};
1.549     foxr      153:     #
                    154:     #  With loncnew process trimming, there's a timing hole between lonc server
                    155:     #  process exit and the master server picking up the listen on the AF_UNIX
                    156:     #  socket.  In that time interval, a lock file will exist:
                    157: 
                    158:     my $lockfile=$peerfile.".lock";
                    159:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    160: 	sleep(1);
                    161:     }
                    162:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      163:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      164:     #
1.550     foxr      165:     #   We'll give the connection a few tries before abandoning it.  If
                    166:     #   connection is not possible, we'll con_lost back to the client.
                    167:     #   
                    168:     my $client;
                    169:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    170: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    171: 				      Type    => SOCK_STREAM,
                    172: 				      Timeout => 10);
                    173: 	if($client) {
                    174: 	    last;		# Connected!
                    175: 	}
                    176: 	sleep(1);		# Try again later if failed connection.
                    177:     }
                    178:     my $answer;
                    179:     if ($client) {
1.704     albertel  180: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      181: 	$answer=<$client>;
                    182: 	if (!$answer) { $answer="con_lost"; }
                    183: 	chomp($answer);
                    184:     } else {
                    185: 	$answer = 'con_lost';	# Failed connection.
                    186:     }
1.1       albertel  187:     return $answer;
                    188: }
                    189: 
                    190: sub reply {
                    191:     my ($cmd,$server)=@_;
1.205     www       192:     unless (defined($hostname{$server})) { return 'no_such_host'; }
1.1       albertel  193:     my $answer=subreply($cmd,$server);
1.65      www       194:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  195:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       196:                 " $cmd to $server returned $answer</font>");
                    197:     }
1.1       albertel  198:     return $answer;
                    199: }
                    200: 
                    201: # ----------------------------------------------------------- Send USR1 to lonc
                    202: 
                    203: sub reconlonc {
                    204:     my $peerfile=shift;
                    205:     &logthis("Trying to reconnect for $peerfile");
                    206:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  207:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  208: 	my $loncpid=<$fh>;
                    209:         chomp($loncpid);
                    210:         if (kill 0 => $loncpid) {
                    211: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    212:             kill USR1 => $loncpid;
                    213:             sleep 1;
                    214:             if (-e "$peerfile") { return; }
                    215:             &logthis("$peerfile still not there, give it another try");
                    216:             sleep 5;
                    217:             if (-e "$peerfile") { return; }
1.12      www       218:             &logthis(
1.672     albertel  219:   "<font color=\"blue\">WARNING: $peerfile still not there, giving up</font>");
1.1       albertel  220:         } else {
1.12      www       221: 	    &logthis(
1.672     albertel  222:                "<font color=\"blue\">WARNING:".
1.12      www       223:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  224:         }
                    225:     } else {
1.672     albertel  226:      &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  227:     }
                    228: }
                    229: 
                    230: # ------------------------------------------------------ Critical communication
1.12      www       231: 
1.1       albertel  232: sub critical {
                    233:     my ($cmd,$server)=@_;
1.89      www       234:     unless ($hostname{$server}) {
1.672     albertel  235:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       236:                " Critical message to unknown server ($server)</font>");
                    237:         return 'no_such_host';
                    238:     }
1.1       albertel  239:     my $answer=reply($cmd,$server);
                    240:     if ($answer eq 'con_lost') {
                    241: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  242: 	my $answer=reply($cmd,$server);
1.1       albertel  243:         if ($answer eq 'con_lost') {
                    244:             my $now=time;
                    245:             my $middlename=$cmd;
1.5       www       246:             $middlename=substr($middlename,0,16);
1.1       albertel  247:             $middlename=~s/\W//g;
                    248:             my $dfilename=
1.305     www       249:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    250:             $dumpcount++;
1.1       albertel  251:             {
1.448     albertel  252: 		my $dfh;
                    253: 		if (open($dfh,">$dfilename")) {
                    254: 		    print $dfh "$cmd\n"; 
                    255: 		    close($dfh);
                    256: 		}
1.1       albertel  257:             }
                    258:             sleep 2;
                    259:             my $wcmd='';
                    260:             {
1.448     albertel  261: 		my $dfh;
                    262: 		if (open($dfh,"<$dfilename")) {
                    263: 		    $wcmd=<$dfh>; 
                    264: 		    close($dfh);
                    265: 		}
1.1       albertel  266:             }
                    267:             chomp($wcmd);
1.7       www       268:             if ($wcmd eq $cmd) {
1.672     albertel  269: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       270:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  271:                 &logperm("D:$server:$cmd");
                    272: 	        return 'con_delayed';
                    273:             } else {
1.672     albertel  274:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       275:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  276:                 &logperm("F:$server:$cmd");
                    277:                 return 'con_failed';
                    278:             }
                    279:         }
                    280:     }
                    281:     return $answer;
1.405     albertel  282: }
                    283: 
1.755     albertel  284: # ------------------------------------------- check if return value is an error
                    285: 
                    286: sub error {
                    287:     my ($result) = @_;
1.756     albertel  288:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  289: 	if ($2 == 2) { return undef; }
                    290: 	return $1;
                    291:     }
                    292:     return undef;
                    293: }
                    294: 
1.783     albertel  295: sub convert_and_load_session_env {
                    296:     my ($lonidsdir,$handle)=@_;
                    297:     my @profile;
                    298:     {
                    299: 	open(my $idf,"$lonidsdir/$handle.id");
                    300: 	flock($idf,LOCK_SH);
                    301: 	@profile=<$idf>;
                    302: 	close($idf);
                    303:     }
                    304:     my %temp_env;
                    305:     foreach my $line (@profile) {
1.786     albertel  306: 	if ($line !~ m/=/) {
                    307: 	    return 0;
                    308: 	}
1.783     albertel  309: 	chomp($line);
                    310: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    311: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    312:     }
                    313:     unlink("$lonidsdir/$handle.id");
                    314:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    315: 	    0640)) {
                    316: 	%disk_env = %temp_env;
                    317: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    318: 	untie(%disk_env);
                    319:     }
1.786     albertel  320:     return 1;
1.783     albertel  321: }
                    322: 
1.374     www       323: # ------------------------------------------- Transfer profile into environment
1.780     albertel  324: my $env_loaded;
                    325: sub transfer_profile_to_env {
1.788     albertel  326:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    327:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       328: 
1.720     albertel  329:     if (!defined($lonidsdir)) {
                    330: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    331:     }
                    332:     if (!defined($handle)) {
                    333:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    334:     }
                    335: 
1.786     albertel  336:     my $convert;
                    337:     {
                    338:     	open(my $idf,"$lonidsdir/$handle.id");
                    339: 	flock($idf,LOCK_SH);
                    340: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    341: 		&GDBM_READER(),0640)) {
                    342: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    343: 	    untie(%disk_env);
                    344: 	} else {
                    345: 	    $convert = 1;
                    346: 	}
                    347:     }
                    348:     if ($convert) {
                    349: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    350: 	    &logthis("Failed to load session, or convert session.");
                    351: 	}
1.374     www       352:     }
1.783     albertel  353: 
1.786     albertel  354:     my %remove;
1.783     albertel  355:     while ( my $envname = each(%env) ) {
1.433     matthew   356:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    357:             if ($time < time-300) {
1.783     albertel  358:                 $remove{$key}++;
1.433     matthew   359:             }
                    360:         }
                    361:     }
1.783     albertel  362: 
1.619     albertel  363:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  364:     $env_loaded=1;
1.783     albertel  365:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   366:         &delenv($expired_key);
1.374     www       367:     }
1.1       albertel  368: }
                    369: 
1.824.2.1  albertel  370: sub timed_flock {
                    371:     my ($file,$lock_type) = @_;
                    372:     my $failed=0;
                    373:     eval {
                    374: 	local $SIG{__DIE__}='DEFAULT';
                    375: 	local $SIG{ALRM}=sub {
                    376: 	    $failed=1;
                    377: 	    die("failed lock");
                    378: 	};
                    379: 	alarm(13);
                    380: 	flock($file,$lock_type);
                    381: 	alarm(0);
                    382:     };
                    383:     if ($failed) {
                    384: 	return undef;
                    385:     } else {
                    386: 	return 1;
                    387:     }
                    388: }
                    389: 
1.5       www       390: # ---------------------------------------------------------- Append Environment
                    391: 
                    392: sub appenv {
1.6       www       393:     my %newenv=@_;
1.692     albertel  394:     foreach my $key (keys(%newenv)) {
                    395: 	if (($newenv{$key}=~/^user\.role/) || ($newenv{$key}=~/^user\.priv/)) {
1.672     albertel  396:             &logthis("<font color=\"blue\">WARNING: ".
1.692     albertel  397:                 "Attempt to modify environment ".$key." to ".$newenv{$key}
1.151     www       398:                 .'</font>');
1.692     albertel  399: 	    delete($newenv{$key});
1.35      www       400:         } else {
1.692     albertel  401:             $env{$key}=$newenv{$key};
1.35      www       402:         }
1.191     harris41  403:     }
1.824.2.1  albertel  404:     open(my $env_file,$env{'user.environment'});
                    405:     if (&timed_flock($env_file,LOCK_EX)
                    406: 	&&
                    407: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    408: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  409: 	while (my ($key,$value) = each(%newenv)) {
                    410: 	    $disk_env{$key} = $value;
1.448     albertel  411: 	}
1.783     albertel  412: 	untie(%disk_env);
1.56      www       413:     }
                    414:     return 'ok';
                    415: }
                    416: # ----------------------------------------------------- Delete from Environment
                    417: 
                    418: sub delenv {
                    419:     my $delthis=shift;
                    420:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672     albertel  421:         &logthis("<font color=\"blue\">WARNING: ".
1.56      www       422:                 "Attempt to delete from environment ".$delthis);
                    423:         return 'error';
                    424:     }
1.824.2.1  albertel  425:     open(my $env_file,$env{'user.environment'});
                    426:     if (&timed_flock($env_file,LOCK_EX)
                    427: 	&&
                    428: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    429: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  430: 	foreach my $key (keys(%disk_env)) {
                    431: 	    if ($key=~/^$delthis/) { 
1.619     albertel  432:                 delete($env{$key});
1.783     albertel  433:                 delete($disk_env{$key});
1.473     matthew   434:             }
1.448     albertel  435: 	}
1.783     albertel  436: 	untie(%disk_env);
1.5       www       437:     }
                    438:     return 'ok';
1.369     albertel  439: }
                    440: 
1.790     albertel  441: sub get_env_multiple {
                    442:     my ($name) = @_;
                    443:     my @values;
                    444:     if (defined($env{$name})) {
                    445:         # exists is it an array
                    446:         if (ref($env{$name})) {
                    447:             @values=@{ $env{$name} };
                    448:         } else {
                    449:             $values[0]=$env{$name};
                    450:         }
                    451:     }
                    452:     return(@values);
                    453: }
                    454: 
1.369     albertel  455: # ------------------------------------------ Find out current server userload
                    456: # there is a copy in lond
                    457: sub userload {
                    458:     my $numusers=0;
                    459:     {
                    460: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    461: 	my $filename;
                    462: 	my $curtime=time;
                    463: 	while ($filename=readdir(LONIDS)) {
                    464: 	    if ($filename eq '.' || $filename eq '..') {next;}
1.404     albertel  465: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  466: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  467: 	}
                    468: 	closedir(LONIDS);
                    469:     }
                    470:     my $userloadpercent=0;
                    471:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    472:     if ($maxuserload) {
1.371     albertel  473: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  474:     }
1.372     albertel  475:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  476:     return $userloadpercent;
1.283     www       477: }
                    478: 
                    479: # ------------------------------------------ Fight off request when overloaded
                    480: 
                    481: sub overloaderror {
                    482:     my ($r,$checkserver)=@_;
                    483:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
                    484:     my $loadavg;
                    485:     if ($checkserver eq $perlvar{'lonHostID'}) {
1.448     albertel  486:        open(my $loadfile,'/proc/loadavg');
1.283     www       487:        $loadavg=<$loadfile>;
                    488:        $loadavg =~ s/\s.*//g;
1.285     matthew   489:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448     albertel  490:        close($loadfile);
1.283     www       491:     } else {
                    492:        $loadavg=&reply('load',$checkserver);
                    493:     }
1.285     matthew   494:     my $overload=$loadavg-100;
1.283     www       495:     if ($overload>0) {
1.285     matthew   496: 	$r->err_headers_out->{'Retry-After'}=$overload;
1.283     www       497:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554     www       498:         return 413;
1.283     www       499:     }    
                    500:     return '';
1.5       www       501: }
1.1       albertel  502: 
                    503: # ------------------------------ Find server with least workload from spare.tab
1.11      www       504: 
1.1       albertel  505: sub spareserver {
1.670     albertel  506:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.784     albertel  507:     my $spare_server;
1.370     albertel  508:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  509:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    510:                                                      :  $userloadpercent;
                    511:     
                    512:     foreach my $try_server (@{ $spareid{'primary'} }) {
                    513: 	($spare_server, $lowest_load) =
                    514: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
                    515:     }
                    516: 
                    517:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    518: 
                    519:     if (!$found_server) {
                    520: 	foreach my $try_server (@{ $spareid{'default'} }) {
                    521: 	    ($spare_server, $lowest_load) =
                    522: 		&compare_server_load($try_server, $spare_server, $lowest_load);
                    523: 	}
                    524:     }
                    525: 
                    526:     if (!$want_server_name) {
                    527: 	$spare_server="http://$hostname{$spare_server}";
                    528:     }
                    529:     return $spare_server;
                    530: }
                    531: 
                    532: sub compare_server_load {
                    533:     my ($try_server, $spare_server, $lowest_load) = @_;
                    534: 
                    535:     my $loadans     = &reply('load',    $try_server);
                    536:     my $userloadans = &reply('userload',$try_server);
                    537: 
                    538:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
                    539: 	next; #didn't get a number from the server
                    540:     }
                    541: 
                    542:     my $load;
                    543:     if ($loadans =~ /\d/) {
                    544: 	if ($userloadans =~ /\d/) {
                    545: 	    #both are numbers, pick the bigger one
                    546: 	    $load = ($loadans > $userloadans) ? $loadans 
                    547: 		                              : $userloadans;
1.411     albertel  548: 	} else {
1.784     albertel  549: 	    $load = $loadans;
1.411     albertel  550: 	}
1.784     albertel  551:     } else {
                    552: 	$load = $userloadans;
                    553:     }
                    554: 
                    555:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    556: 	$spare_server = $try_server;
                    557: 	$lowest_load  = $load;
1.370     albertel  558:     }
1.784     albertel  559:     return ($spare_server,$lowest_load);
1.202     matthew   560: }
                    561: # --------------------------------------------- Try to change a user's password
                    562: 
                    563: sub changepass {
1.799     raeburn   564:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   565:     $currentpass = &escape($currentpass);
                    566:     $newpass     = &escape($newpass);
1.799     raeburn   567:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
1.202     matthew   568: 		       $server);
                    569:     if (! $answer) {
                    570: 	&logthis("No reply on password change request to $server ".
                    571: 		 "by $uname in domain $udom.");
                    572:     } elsif ($answer =~ "^ok") {
                    573:         &logthis("$uname in $udom successfully changed their password ".
                    574: 		 "on $server.");
                    575:     } elsif ($answer =~ "^pwchange_failure") {
                    576: 	&logthis("$uname in $udom was unable to change their password ".
                    577: 		 "on $server.  The action was blocked by either lcpasswd ".
                    578: 		 "or pwchange");
                    579:     } elsif ($answer =~ "^non_authorized") {
                    580:         &logthis("$uname in $udom did not get their password correct when ".
                    581: 		 "attempting to change it on $server.");
                    582:     } elsif ($answer =~ "^auth_mode_error") {
                    583:         &logthis("$uname in $udom attempted to change their password despite ".
                    584: 		 "not being locally or internally authenticated on $server.");
                    585:     } elsif ($answer =~ "^unknown_user") {
                    586:         &logthis("$uname in $udom attempted to change their password ".
                    587: 		 "on $server but were unable to because $server is not ".
                    588: 		 "their home server.");
                    589:     } elsif ($answer =~ "^refused") {
                    590: 	&logthis("$server refused to change $uname in $udom password because ".
                    591: 		 "it was sent an unencrypted request to change the password.");
                    592:     }
                    593:     return $answer;
1.1       albertel  594: }
                    595: 
1.169     harris41  596: # ----------------------- Try to determine user's current authentication scheme
                    597: 
                    598: sub queryauthenticate {
                    599:     my ($uname,$udom)=@_;
1.456     albertel  600:     my $uhome=&homeserver($uname,$udom);
                    601:     if (!$uhome) {
                    602: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                    603: 	return 'no_host';
                    604:     }
                    605:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                    606:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                    607: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41  608:     }
1.456     albertel  609:     return $answer;
1.169     harris41  610: }
                    611: 
1.1       albertel  612: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       613: 
1.1       albertel  614: sub authenticate {
                    615:     my ($uname,$upass,$udom)=@_;
1.807     albertel  616:     $upass=&escape($upass);
                    617:     $uname= &LONCAPA::clean_username($uname);
1.471     albertel  618:     my $uhome=&homeserver($uname,$udom);
                    619:     if (!$uhome) {
                    620: 	&logthis("User $uname at $udom is unknown in authenticate");
                    621: 	return 'no_host';
1.1       albertel  622:     }
1.471     albertel  623:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
                    624:     if ($answer eq 'authorized') {
                    625: 	&logthis("User $uname at $udom authorized by $uhome"); 
                    626: 	return $uhome; 
                    627:     }
                    628:     if ($answer eq 'non_authorized') {
                    629: 	&logthis("User $uname at $udom rejected by $uhome");
                    630: 	return 'no_host'; 
1.9       www       631:     }
1.471     albertel  632:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel  633:     return 'no_host';
                    634: }
                    635: 
                    636: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www       637: 
1.599     albertel  638: my %homecache;
1.1       albertel  639: sub homeserver {
1.230     stredwic  640:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel  641:     my $index="$uname:$udom";
1.426     albertel  642: 
1.599     albertel  643:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.1       albertel  644:     my $tryserver;
                    645:     foreach $tryserver (keys %libserv) {
1.230     stredwic  646:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic  647: 		 exists($badServerCache{$tryserver}));
1.1       albertel  648: 	if ($hostdom{$tryserver} eq $udom) {
                    649:            my $answer=reply("home:$udom:$uname",$tryserver);
                    650:            if ($answer eq 'found') { 
1.599     albertel  651: 	       return $homecache{$index}=$tryserver;
1.231     stredwic  652:            } elsif ($answer eq 'no_host') {
                    653: 	       $badServerCache{$tryserver}=1;
1.221     matthew   654:            }
1.1       albertel  655:        }
                    656:     }    
                    657:     return 'no_host';
1.70      www       658: }
                    659: 
                    660: # ------------------------------------- Find the usernames behind a list of IDs
                    661: 
                    662: sub idget {
                    663:     my ($udom,@ids)=@_;
                    664:     my %returnhash=();
                    665:     
                    666:     my $tryserver;
                    667:     foreach $tryserver (keys %libserv) {
                    668:        if ($hostdom{$tryserver} eq $udom) {
                    669: 	  my $idlist=join('&',@ids);
                    670:           $idlist=~tr/A-Z/a-z/; 
                    671: 	  my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                    672:           my @answer=();
1.76      www       673:           if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1.70      www       674: 	      @answer=split(/\&/,$reply);
                    675:           }                    ;
                    676:           my $i;
                    677:           for ($i=0;$i<=$#ids;$i++) {
                    678:               if ($answer[$i]) {
                    679: 		  $returnhash{$ids[$i]}=$answer[$i];
                    680:               } 
                    681:           }
                    682:        }
                    683:     }    
                    684:     return %returnhash;
                    685: }
                    686: 
                    687: # ------------------------------------- Find the IDs behind a list of usernames
                    688: 
                    689: sub idrget {
                    690:     my ($udom,@unames)=@_;
                    691:     my %returnhash=();
1.800     albertel  692:     foreach my $uname (@unames) {
                    693:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41  694:     }
1.70      www       695:     return %returnhash;
                    696: }
                    697: 
                    698: # ------------------------------- Store away a list of names and associated IDs
                    699: 
                    700: sub idput {
                    701:     my ($udom,%ids)=@_;
                    702:     my %servers=();
1.800     albertel  703:     foreach my $uname (keys(%ids)) {
                    704: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                    705:         my $uhom=&homeserver($uname,$udom);
1.70      www       706:         if ($uhom ne 'no_host') {
1.800     albertel  707:             my $id=&escape($ids{$uname});
1.70      www       708:             $id=~tr/A-Z/a-z/;
1.800     albertel  709:             my $esc_unam=&escape($uname);
1.70      www       710: 	    if ($servers{$uhom}) {
1.800     albertel  711: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www       712:             } else {
1.800     albertel  713:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www       714:             }
                    715:         }
1.191     harris41  716:     }
1.800     albertel  717:     foreach my $server (keys(%servers)) {
                    718:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41  719:     }
1.344     www       720: }
                    721: 
1.806     raeburn   722: # ------------------------------------------- get items from domain db files   
                    723: 
                    724: sub get_dom {
                    725:     my ($namespace,$storearr,$udom)=@_;
                    726:     my $items='';
                    727:     foreach my $item (@$storearr) {
                    728:         $items.=&escape($item).'&';
                    729:     }
                    730:     $items=~s/\&$//;
                    731:     if (!$udom) { $udom=$env{'user.domain'}; }
                    732:     if (exists($domain_primary{$udom})) {
                    733:         my $uhome=$domain_primary{$udom};
                    734:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
                    735:         my @pairs=split(/\&/,$rep);
                    736:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                    737:             return @pairs;
                    738:         }
                    739:         my %returnhash=();
                    740:         my $i=0;
                    741:         foreach my $item (@$storearr) {
                    742:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                    743:             $i++;
                    744:         }
                    745:         return %returnhash;
                    746:     } else {
                    747:         &logthis("get_dom failed - no primary domain server for $udom");
                    748:     }
                    749: }
                    750: 
                    751: # -------------------------------------------- put items in domain db files 
                    752: 
                    753: sub put_dom {
                    754:     my ($namespace,$storehash,$udom)=@_;
                    755:     if (!$udom) { $udom=$env{'user.domain'}; }
                    756:     if (exists($domain_primary{$udom})) {
                    757:         my $uhome=$domain_primary{$udom};
                    758:         my $items='';
                    759:         foreach my $item (keys(%$storehash)) {
                    760:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                    761:         }
                    762:         $items=~s/\&$//;
                    763:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                    764:     } else {
                    765:         &logthis("put_dom failed - no primary domain server for $udom");
                    766:     }
                    767: }
                    768: 
1.344     www       769: # --------------------------------------------------- Assign a key to a student
                    770: 
                    771: sub assign_access_key {
1.364     www       772: #
                    773: # a valid key looks like uname:udom#comments
                    774: # comments are being appended
                    775: #
1.498     www       776:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                    777:     $kdom=
1.620     albertel  778:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www       779:     $knum=
1.620     albertel  780:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www       781:     $cdom=
1.620     albertel  782:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       783:     $cnum=
1.620     albertel  784:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    785:     $udom=$env{'user.name'} unless (defined($udom));
                    786:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www       787:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www       788:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel  789:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www       790:                                                   # assigned to this person
                    791:                                                   # - this should not happen,
1.345     www       792:                                                   # unless something went wrong
                    793:                                                   # the first time around
                    794: # ready to assign
1.364     www       795:         $logentry=$1.'; '.$logentry;
1.496     www       796:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www       797:                                                  $kdom,$knum) eq 'ok') {
1.345     www       798: # key now belongs to user
1.346     www       799: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www       800:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
                    801:                 &appenv('environment.'.$envkey => $ckey);
                    802:                 return 'ok';
                    803:             } else {
                    804:                 return 
                    805:   'error: Count not permanently assign key, will need to be re-entered later.';
                    806: 	    }
                    807:         } else {
                    808:             return 'error: Could not assign key, try again later.';
                    809:         }
1.364     www       810:     } elsif (!$existing{$ckey}) {
1.345     www       811: # the key does not exist
                    812: 	return 'error: The key does not exist';
                    813:     } else {
                    814: # the key is somebody else's
                    815: 	return 'error: The key is already in use';
                    816:     }
1.344     www       817: }
                    818: 
1.364     www       819: # ------------------------------------------ put an additional comment on a key
                    820: 
                    821: sub comment_access_key {
                    822: #
                    823: # a valid key looks like uname:udom#comments
                    824: # comments are being appended
                    825: #
                    826:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                    827:     $cdom=
1.620     albertel  828:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www       829:     $cnum=
1.620     albertel  830:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www       831:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                    832:     if ($existing{$ckey}) {
                    833:         $existing{$ckey}.='; '.$logentry;
                    834: # ready to assign
1.367     www       835:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www       836:                                                  $cdom,$cnum) eq 'ok') {
                    837: 	    return 'ok';
                    838:         } else {
                    839: 	    return 'error: Count not store comment.';
                    840:         }
                    841:     } else {
                    842: # the key does not exist
                    843: 	return 'error: The key does not exist';
                    844:     }
                    845: }
                    846: 
1.344     www       847: # ------------------------------------------------------ Generate a set of keys
                    848: 
                    849: sub generate_access_keys {
1.364     www       850:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www       851:     $cdom=
1.620     albertel  852:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       853:     $cnum=
1.620     albertel  854:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www       855:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www       856:     unless (($cdom) && ($cnum)) { return 0; }
                    857:     if ($number>10000) { return 0; }
                    858:     sleep(2); # make sure don't get same seed twice
                    859:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                    860:     my $total=0;
                    861:     for (my $i=1;$i<=$number;$i++) {
                    862:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                    863:                   sprintf("%lx",int(100000*rand)).'-'.
                    864:                   sprintf("%lx",int(100000*rand));
                    865:        $newkey=~s/1/g/g; # folks mix up 1 and l
                    866:        $newkey=~s/0/h/g; # and also 0 and O
                    867:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                    868:        if ($existing{$newkey}) {
                    869:            $i--;
                    870:        } else {
1.364     www       871: 	  if (&put('accesskeys',
                    872:               { $newkey => '# generated '.localtime().
1.620     albertel  873:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www       874:                            '; '.$logentry },
                    875: 		   $cdom,$cnum) eq 'ok') {
1.344     www       876:               $total++;
                    877: 	  }
                    878:        }
                    879:     }
1.620     albertel  880:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www       881:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                    882:     return $total;
                    883: }
                    884: 
                    885: # ------------------------------------------------------- Validate an accesskey
                    886: 
                    887: sub validate_access_key {
                    888:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                    889:     $cdom=
1.620     albertel  890:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       891:     $cnum=
1.620     albertel  892:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    893:     $udom=$env{'user.domain'} unless (defined($udom));
                    894:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www       895:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel  896:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www       897: }
                    898: 
                    899: # ------------------------------------- Find the section of student in a course
1.652     albertel  900: sub devalidate_getsection_cache {
                    901:     my ($udom,$unam,$courseid)=@_;
                    902:     my $hashid="$udom:$unam:$courseid";
                    903:     &devalidate_cache_new('getsection',$hashid);
                    904: }
1.298     matthew   905: 
1.815     albertel  906: sub courseid_to_courseurl {
                    907:     my ($courseid) = @_;
                    908:     #already url style courseid
                    909:     return $courseid if ($courseid =~ m{^/});
                    910: 
                    911:     if (exists($env{'course.'.$courseid.'.num'})) {
                    912: 	my $cnum = $env{'course.'.$courseid.'.num'};
                    913: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                    914: 	return "/$cdom/$cnum";
                    915:     }
                    916: 
                    917:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                    918:     if (exists($courseinfo{'num'})) {
                    919: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                    920:     }
                    921: 
                    922:     return undef;
                    923: }
                    924: 
1.298     matthew   925: sub getsection {
                    926:     my ($udom,$unam,$courseid)=@_;
1.599     albertel  927:     my $cachetime=1800;
1.551     albertel  928: 
                    929:     my $hashid="$udom:$unam:$courseid";
1.599     albertel  930:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel  931:     if (defined($cached)) { return $result; }
                    932: 
1.298     matthew   933:     my %Pending; 
                    934:     my %Expired;
                    935:     #
                    936:     # Each role can either have not started yet (pending), be active, 
                    937:     #    or have expired.
                    938:     #
                    939:     # If there is an active role, we are done.
                    940:     #
                    941:     # If there is more than one role which has not started yet, 
                    942:     #     choose the one which will start sooner
                    943:     # If there is one role which has not started yet, return it.
                    944:     #
                    945:     # If there is more than one expired role, choose the one which ended last.
                    946:     # If there is a role which has expired, return it.
                    947:     #
1.815     albertel  948:     $courseid = &courseid_to_courseurl($courseid);
1.817     raeburn   949:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
                    950:     foreach my $key (keys(%roleshash)) {
1.479     albertel  951:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew   952:         my $section=$1;
                    953:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn   954:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew   955:         my $now=time;
1.548     albertel  956:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew   957:             $Expired{$end}=$section;
                    958:             next;
                    959:         }
1.548     albertel  960:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew   961:             $Pending{$start}=$section;
                    962:             next;
                    963:         }
1.599     albertel  964:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew   965:     }
                    966:     #
                    967:     # Presumedly there will be few matching roles from the above
                    968:     # loop and the sorting time will be negligible.
                    969:     if (scalar(keys(%Pending))) {
                    970:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel  971:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew   972:     } 
                    973:     if (scalar(keys(%Expired))) {
                    974:         my @sorted = sort {$a <=> $b} keys(%Expired);
                    975:         my $time = pop(@sorted);
1.599     albertel  976:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew   977:     }
1.599     albertel  978:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew   979: }
1.70      www       980: 
1.599     albertel  981: sub save_cache {
                    982:     &purge_remembered();
1.722     albertel  983:     #&Apache::loncommon::validate_page();
1.620     albertel  984:     undef(%env);
1.780     albertel  985:     undef($env_loaded);
1.599     albertel  986: }
1.452     albertel  987: 
1.599     albertel  988: my $to_remember=-1;
                    989: my %remembered;
                    990: my %accessed;
                    991: my $kicks=0;
                    992: my $hits=0;
1.824.2.3  albertel  993: sub make_key {
                    994:     my ($name,$id) = @_;
                    995:     if (length($id) > 200) { $id=length($id).':'.&Digest::MD5::md5_hex($id); }
                    996:     return &escape($name.':'.$id);
                    997: }
                    998: 
1.599     albertel  999: sub devalidate_cache_new {
                   1000:     my ($name,$id,$debug) = @_;
                   1001:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.824.2.3  albertel 1002:     $id=&make_key($name,$id);
1.599     albertel 1003:     $memcache->delete($id);
                   1004:     delete($remembered{$id});
                   1005:     delete($accessed{$id});
                   1006: }
                   1007: 
                   1008: sub is_cached_new {
                   1009:     my ($name,$id,$debug) = @_;
1.824.2.3  albertel 1010:     $id=&make_key($name,$id);
1.599     albertel 1011:     if (exists($remembered{$id})) {
                   1012: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                   1013: 	$accessed{$id}=[&gettimeofday()];
                   1014: 	$hits++;
                   1015: 	return ($remembered{$id},1);
                   1016:     }
                   1017:     my $value = $memcache->get($id);
                   1018:     if (!(defined($value))) {
                   1019: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 1020: 	return (undef,undef);
1.416     albertel 1021:     }
1.599     albertel 1022:     if ($value eq '__undef__') {
                   1023: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   1024: 	$value=undef;
                   1025:     }
                   1026:     &make_room($id,$value,$debug);
                   1027:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   1028:     return ($value,1);
                   1029: }
                   1030: 
                   1031: sub do_cache_new {
                   1032:     my ($name,$id,$value,$time,$debug) = @_;
1.824.2.3  albertel 1033:     $id=&make_key($name,$id);
1.599     albertel 1034:     my $setvalue=$value;
                   1035:     if (!defined($setvalue)) {
                   1036: 	$setvalue='__undef__';
                   1037:     }
1.623     albertel 1038:     if (!defined($time) ) {
                   1039: 	$time=600;
                   1040:     }
1.599     albertel 1041:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.600     albertel 1042:     $memcache->set($id,$setvalue,$time);
                   1043:     # need to make a copy of $value
                   1044:     #&make_room($id,$value,$debug);
1.599     albertel 1045:     return $value;
                   1046: }
                   1047: 
                   1048: sub make_room {
                   1049:     my ($id,$value,$debug)=@_;
                   1050:     $remembered{$id}=$value;
                   1051:     if ($to_remember<0) { return; }
                   1052:     $accessed{$id}=[&gettimeofday()];
                   1053:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   1054:     my $to_kick;
                   1055:     my $max_time=0;
                   1056:     foreach my $other (keys(%accessed)) {
                   1057: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   1058: 	    $to_kick=$other;
                   1059: 	    $max_time=&tv_interval($accessed{$other});
                   1060: 	}
                   1061:     }
                   1062:     delete($remembered{$to_kick});
                   1063:     delete($accessed{$to_kick});
                   1064:     $kicks++;
                   1065:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 1066:     return;
                   1067: }
                   1068: 
1.599     albertel 1069: sub purge_remembered {
1.604     albertel 1070:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   1071:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 1072:     undef(%remembered);
                   1073:     undef(%accessed);
1.428     albertel 1074: }
1.70      www      1075: # ------------------------------------- Read an entry from a user's environment
                   1076: 
                   1077: sub userenvironment {
                   1078:     my ($udom,$unam,@what)=@_;
                   1079:     my %returnhash=();
                   1080:     my @answer=split(/\&/,
                   1081:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
                   1082:                       &homeserver($unam,$udom)));
                   1083:     my $i;
                   1084:     for ($i=0;$i<=$#what;$i++) {
                   1085: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                   1086:     }
                   1087:     return %returnhash;
1.1       albertel 1088: }
                   1089: 
1.617     albertel 1090: # ---------------------------------------------------------- Get a studentphoto
                   1091: sub studentphoto {
                   1092:     my ($udom,$unam,$ext) = @_;
                   1093:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1094:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1095:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1096:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1097:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1098:             } else {
                   1099:                 my ($result,$perm_reqd)=
1.707     albertel 1100: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1101:                 if ($result eq 'ok') {
                   1102:                     if (!($perm_reqd eq 'yes')) {
                   1103:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1104:                     }
                   1105:                 }
                   1106:             }
                   1107:         }
                   1108:     } else {
                   1109:         my ($result,$perm_reqd) = 
1.707     albertel 1110: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1111:         if ($result eq 'ok') {
                   1112:             if (!($perm_reqd eq 'yes')) {
                   1113:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1114:             }
                   1115:         }
                   1116:     }
                   1117:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1118: }
                   1119: 
                   1120: sub retrievestudentphoto {
                   1121:     my ($udom,$unam,$ext,$type) = @_;
                   1122:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1123:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1124:     if ($ret eq 'ok') {
                   1125:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1126:         if ($type eq 'thumbnail') {
                   1127:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1128:         }
                   1129:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1130:         return $tokenurl;
                   1131:     } else {
                   1132:         if ($type eq 'thumbnail') {
                   1133:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1134:         } else { 
                   1135:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1136:         }
1.617     albertel 1137:     }
                   1138: }
                   1139: 
1.263     www      1140: # -------------------------------------------------------------------- New chat
                   1141: 
                   1142: sub chatsend {
1.724     raeburn  1143:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1144:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1145:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1146:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1147:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1148: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1149: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1150: }
                   1151: 
                   1152: # ------------------------------------------ Find current version of a resource
                   1153: 
                   1154: sub getversion {
                   1155:     my $fname=&clutter(shift);
                   1156:     unless ($fname=~/^\/res\//) { return -1; }
                   1157:     return &currentversion(&filelocation('',$fname));
                   1158: }
                   1159: 
                   1160: sub currentversion {
                   1161:     my $fname=shift;
1.599     albertel 1162:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1163:     if (defined($cached)) { return $result; }
1.292     www      1164:     my $author=$fname;
                   1165:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1166:     my ($udom,$uname)=split(/\//,$author);
                   1167:     my $home=homeserver($uname,$udom);
                   1168:     if ($home eq 'no_host') { 
                   1169:         return -1; 
                   1170:     }
                   1171:     my $answer=reply("currentversion:$fname",$home);
                   1172:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1173: 	return -1;
                   1174:     }
1.599     albertel 1175:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1176: }
                   1177: 
1.1       albertel 1178: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1179: 
1.1       albertel 1180: sub subscribe {
                   1181:     my $fname=shift;
1.761     raeburn  1182:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1183:     $fname=~s/[\n\r]//g;
1.1       albertel 1184:     my $author=$fname;
                   1185:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1186:     my ($udom,$uname)=split(/\//,$author);
                   1187:     my $home=homeserver($uname,$udom);
1.335     albertel 1188:     if ($home eq 'no_host') {
                   1189:         return 'not_found';
1.1       albertel 1190:     }
                   1191:     my $answer=reply("sub:$fname",$home);
1.64      www      1192:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1193: 	$answer.=' by '.$home;
                   1194:     }
1.1       albertel 1195:     return $answer;
                   1196: }
                   1197:     
1.8       www      1198: # -------------------------------------------------------------- Replicate file
                   1199: 
                   1200: sub repcopy {
                   1201:     my $filename=shift;
1.23      www      1202:     $filename=~s/\/+/\//g;
1.607     raeburn  1203:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1204:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1205:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1206: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1207: 	return &repcopy_userfile($filename);
                   1208:     }
1.532     albertel 1209:     $filename=~s/[\n\r]//g;
1.8       www      1210:     my $transname="$filename.in.transfer";
1.607     raeburn  1211:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1212:     my $remoteurl=subscribe($filename);
1.64      www      1213:     if ($remoteurl =~ /^con_lost by/) {
                   1214: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1215:            return 'unavailable';
1.8       www      1216:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1217: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1218: 	   return 'not_found';
1.64      www      1219:     } elsif ($remoteurl =~ /^rejected by/) {
                   1220: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1221:            return 'forbidden';
1.20      www      1222:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1223:            return 'ok';
1.8       www      1224:     } else {
1.290     www      1225:         my $author=$filename;
                   1226:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1227:         my ($udom,$uname)=split(/\//,$author);
                   1228:         my $home=homeserver($uname,$udom);
                   1229:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1230:            my @parts=split(/\//,$filename);
                   1231:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1232:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1233:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1234: 	       return 'bad_request';
1.8       www      1235:            }
                   1236:            my $count;
                   1237:            for ($count=5;$count<$#parts;$count++) {
                   1238:                $path.="/$parts[$count]";
                   1239:                if ((-e $path)!=1) {
                   1240: 		   mkdir($path,0777);
                   1241:                }
                   1242:            }
                   1243:            my $ua=new LWP::UserAgent;
                   1244:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1245:            my $response=$ua->request($request,$transname);
                   1246:            if ($response->is_error()) {
                   1247: 	       unlink($transname);
                   1248:                my $message=$response->status_line;
1.672     albertel 1249:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      1250:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1251:                return 'unavailable';
1.8       www      1252:            } else {
1.16      www      1253: 	       if ($remoteurl!~/\.meta$/) {
                   1254:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1255:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1256:                   if ($mresponse->is_error()) {
                   1257: 		      unlink($filename.'.meta');
                   1258:                       &logthis(
1.672     albertel 1259:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      1260:                   }
                   1261: 	       }
1.8       www      1262:                rename($transname,$filename);
1.607     raeburn  1263:                return 'ok';
1.8       www      1264:            }
1.290     www      1265:        }
1.8       www      1266:     }
1.330     www      1267: }
                   1268: 
                   1269: # ------------------------------------------------ Get server side include body
                   1270: sub ssi_body {
1.381     albertel 1271:     my ($filelink,%form)=@_;
1.606     matthew  1272:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1273:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1274:     }
1.330     www      1275:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
1.381     albertel 1276:                                      &ssi($filelink,%form));
1.778     albertel 1277:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1278:     $output=~s/^.*?\<body[^\>]*\>//si;
                   1279:     $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
1.330     www      1280:     return $output;
1.8       www      1281: }
                   1282: 
1.15      www      1283: # --------------------------------------------------------- Server Side Include
                   1284: 
1.782     albertel 1285: sub absolute_url {
                   1286:     my ($host_name) = @_;
                   1287:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   1288:     if ($host_name eq '') {
                   1289: 	$host_name = $ENV{'SERVER_NAME'};
                   1290:     }
                   1291:     return $protocol.$host_name;
                   1292: }
                   1293: 
1.15      www      1294: sub ssi {
                   1295: 
1.23      www      1296:     my ($fn,%form)=@_;
1.15      www      1297: 
                   1298:     my $ua=new LWP::UserAgent;
1.23      www      1299:     
                   1300:     my $request;
1.711     albertel 1301: 
                   1302:     $form{'no_update_last_known'}=1;
                   1303: 
1.23      www      1304:     if (%form) {
1.782     albertel 1305:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.201     albertel 1306:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www      1307:     } else {
1.782     albertel 1308:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      1309:     }
                   1310: 
1.15      www      1311:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1312:     my $response=$ua->request($request);
                   1313: 
1.324     www      1314:     return $response->content;
                   1315: }
                   1316: 
                   1317: sub externalssi {
                   1318:     my ($url)=@_;
                   1319:     my $ua=new LWP::UserAgent;
                   1320:     my $request=new HTTP::Request('GET',$url);
                   1321:     my $response=$ua->request($request);
1.15      www      1322:     return $response->content;
                   1323: }
1.254     www      1324: 
1.492     albertel 1325: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1326: 
                   1327: sub allowuploaded {
                   1328:     my ($srcurl,$url)=@_;
                   1329:     $url=&clutter(&declutter($url));
                   1330:     my $dir=$url;
                   1331:     $dir=~s/\/[^\/]+$//;
                   1332:     my %httpref=();
                   1333:     my $httpurl=&hreflocation('',$url);
                   1334:     $httpref{'httpref.'.$httpurl}=$srcurl;
                   1335:     &Apache::lonnet::appenv(%httpref);
1.254     www      1336: }
1.477     raeburn  1337: 
1.478     albertel 1338: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 1339: # input: action, courseID, current domain, intended
1.637     raeburn  1340: #        path to file, source of file, instruction to parse file for objects,
                   1341: #        ref to hash for embedded objects,
                   1342: #        ref to hash for codebase of java objects.
                   1343: #
1.485     raeburn  1344: # output: url to file (if action was uploaddoc), 
                   1345: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  1346: #
1.478     albertel 1347: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   1348: # course.
1.477     raeburn  1349: #
1.478     albertel 1350: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1351: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   1352: #          course's home server.
1.477     raeburn  1353: #
1.478     albertel 1354: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   1355: #          be copied from $source (current location) to 
                   1356: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1357: #         and will then be copied to
                   1358: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   1359: #         course's home server.
1.485     raeburn  1360: #
1.481     raeburn  1361: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 1362: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  1363: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1364: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   1365: #         in course's home server.
1.637     raeburn  1366: #
1.477     raeburn  1367: 
                   1368: sub process_coursefile {
1.638     albertel 1369:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  1370:     my $fetchresult;
1.638     albertel 1371:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  1372:     if ($action eq 'propagate') {
1.638     albertel 1373:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1374: 			     $home);
1.481     raeburn  1375:     } else {
1.477     raeburn  1376:         my $fpath = '';
                   1377:         my $fname = $file;
1.478     albertel 1378:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  1379:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  1380:         my $filepath = &build_filepath($fpath);
1.481     raeburn  1381:         if ($action eq 'copy') {
                   1382:             if ($source eq '') {
                   1383:                 $fetchresult = 'no source file';
                   1384:                 return $fetchresult;
                   1385:             } else {
                   1386:                 my $destination = $filepath.'/'.$fname;
                   1387:                 rename($source,$destination);
                   1388:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1389:                                  $home);
1.481     raeburn  1390:             }
                   1391:         } elsif ($action eq 'uploaddoc') {
                   1392:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 1393:             print $fh $env{'form.'.$source};
1.481     raeburn  1394:             close($fh);
1.637     raeburn  1395:             if ($parser eq 'parse') {
                   1396:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
                   1397:                 unless ($parse_result eq 'ok') {
                   1398:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   1399:                 }
                   1400:             }
1.477     raeburn  1401:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1402:                                  $home);
1.481     raeburn  1403:             if ($fetchresult eq 'ok') {
                   1404:                 return '/uploaded/'.$fpath.'/'.$fname;
                   1405:             } else {
                   1406:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1407:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  1408:                 return '/adm/notfound.html';
                   1409:             }
1.477     raeburn  1410:         }
                   1411:     }
1.485     raeburn  1412:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  1413:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1414:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  1415:     }
                   1416:     return $fetchresult;
                   1417: }
                   1418: 
1.637     raeburn  1419: sub build_filepath {
                   1420:     my ($fpath) = @_;
                   1421:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   1422:     unless ($fpath eq '') {
                   1423:         my @parts=split('/',$fpath);
                   1424:         foreach my $part (@parts) {
                   1425:             $filepath.= '/'.$part;
                   1426:             if ((-e $filepath)!=1) {
                   1427:                 mkdir($filepath,0777);
                   1428:             }
                   1429:         }
                   1430:     }
                   1431:     return $filepath;
                   1432: }
                   1433: 
                   1434: sub store_edited_file {
1.638     albertel 1435:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  1436:     my $file = $primary_url;
                   1437:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   1438:     my $fpath = '';
                   1439:     my $fname = $file;
                   1440:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   1441:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   1442:     my $filepath = &build_filepath($fpath);
                   1443:     open(my $fh,'>'.$filepath.'/'.$fname);
                   1444:     print $fh $content;
                   1445:     close($fh);
1.638     albertel 1446:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  1447:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1448: 			  $home);
1.637     raeburn  1449:     if ($$fetchresult eq 'ok') {
                   1450:         return '/uploaded/'.$fpath.'/'.$fname;
                   1451:     } else {
1.638     albertel 1452:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   1453: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  1454:         return '/adm/notfound.html';
                   1455:     }
                   1456: }
                   1457: 
1.531     albertel 1458: sub clean_filename {
                   1459:     my ($fname)=@_;
1.315     www      1460: # Replace Windows backslashes by forward slashes
1.257     www      1461:     $fname=~s/\\/\//g;
1.315     www      1462: # Get rid of everything but the actual filename
1.257     www      1463:     $fname=~s/^.*\/([^\/]+)$/$1/;
1.315     www      1464: # Replace spaces by underscores
                   1465:     $fname=~s/\s+/\_/g;
                   1466: # Replace all other weird characters by nothing
1.317     www      1467:     $fname=~s/[^\w\.\-]//g;
1.540     albertel 1468: # Replace all .\d. sequences with _\d. so they no longer look like version
                   1469: # numbers
                   1470:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 1471:     return $fname;
                   1472: }
                   1473: 
1.608     albertel 1474: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 1475: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 1476: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 1477: #        $coursedoc - if true up to the current course
                   1478: #                     if false
                   1479: #        $subdir - directory in userfile to store the file into
                   1480: #        $parser, $allfiles, $codebase - unknown
                   1481: #
                   1482: # output: url of file in userspace, or error: <message> 
                   1483: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 1484: 
                   1485: 
1.531     albertel 1486: sub userfileupload {
1.719     banghart 1487:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,$destudom)=@_;
1.531     albertel 1488:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 1489:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 1490:     $fname=&clean_filename($fname);
1.315     www      1491: # See if there is anything left
1.257     www      1492:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 1493:     chop($env{'form.'.$formname});
1.523     raeburn  1494:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   1495:         my $now = time;
                   1496:         my $filepath = 'tmp/helprequests/'.$now;
                   1497:         my @parts=split(/\//,$filepath);
                   1498:         my $fullpath = $perlvar{'lonDaemons'};
                   1499:         for (my $i=0;$i<@parts;$i++) {
                   1500:             $fullpath .= '/'.$parts[$i];
                   1501:             if ((-e $fullpath)!=1) {
                   1502:                 mkdir($fullpath,0777);
                   1503:             }
                   1504:         }
                   1505:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 1506:         print $fh $env{'form.'.$formname};
1.523     raeburn  1507:         close($fh);
1.741     raeburn  1508:         return $fullpath.'/'.$fname;
                   1509:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   1510:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   1511:                        '_'.$env{'user.domain'}.'/pending';
                   1512:         my @parts=split(/\//,$filepath);
                   1513:         my $fullpath = $perlvar{'lonDaemons'};
                   1514:         for (my $i=0;$i<@parts;$i++) {
                   1515:             $fullpath .= '/'.$parts[$i];
                   1516:             if ((-e $fullpath)!=1) {
                   1517:                 mkdir($fullpath,0777);
                   1518:             }
                   1519:         }
                   1520:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   1521:         print $fh $env{'form.'.$formname};
                   1522:         close($fh);
                   1523:         return $fullpath.'/'.$fname;
1.523     raeburn  1524:     }
1.719     banghart 1525:     
1.258     www      1526: # Create the directory if not present
1.493     albertel 1527:     $fname="$subdir/$fname";
1.259     www      1528:     if ($coursedoc) {
1.638     albertel 1529: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1530: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  1531:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 1532:             return &finishuserfileupload($docuname,$docudom,
                   1533: 					 $formname,$fname,$parser,$allfiles,
                   1534: 					 $codebase);
1.481     raeburn  1535:         } else {
1.620     albertel 1536:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 1537:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   1538: 				       $fname,$formname,$parser,
                   1539: 				       $allfiles,$codebase);
1.481     raeburn  1540:         }
1.719     banghart 1541:     } elsif (defined($destuname)) {
                   1542:         my $docuname=$destuname;
                   1543:         my $docudom=$destudom;
                   1544: 	return &finishuserfileupload($docuname,$docudom,$formname,
                   1545: 				     $fname,$parser,$allfiles,$codebase);
                   1546:         
1.259     www      1547:     } else {
1.638     albertel 1548:         my $docuname=$env{'user.name'};
                   1549:         my $docudom=$env{'user.domain'};
1.714     raeburn  1550:         if (exists($env{'form.group'})) {
                   1551:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1552:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1553:         }
1.638     albertel 1554: 	return &finishuserfileupload($docuname,$docudom,$formname,
                   1555: 				     $fname,$parser,$allfiles,$codebase);
1.259     www      1556:     }
1.271     www      1557: }
                   1558: 
                   1559: sub finishuserfileupload {
1.638     albertel 1560:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase) = @_;
1.477     raeburn  1561:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      1562:     my $filepath=$perlvar{'lonDocRoot'};
1.494     albertel 1563:     my ($fnamepath,$file);
                   1564:     $file=$fname;
                   1565:     if ($fname=~m|/|) {
                   1566:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   1567: 	$path.=$fnamepath.'/';
                   1568:     }
1.259     www      1569:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      1570:     my $count;
                   1571:     for ($count=4;$count<=$#parts;$count++) {
                   1572:         $filepath.="/$parts[$count]";
                   1573:         if ((-e $filepath)!=1) {
                   1574: 	    mkdir($filepath,0777);
                   1575:         }
                   1576:     }
                   1577: # Save the file
                   1578:     {
1.701     albertel 1579: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   1580: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   1581: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   1582: 	    return '/adm/notfound.html';
                   1583: 	}
                   1584: 	if (!print FH ($env{'form.'.$formname})) {
                   1585: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   1586: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   1587: 	    return '/adm/notfound.html';
                   1588: 	}
1.570     albertel 1589: 	close(FH);
1.258     www      1590:     }
1.637     raeburn  1591:     if ($parser eq 'parse') {
1.638     albertel 1592:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
                   1593: 						   $codebase);
1.637     raeburn  1594:         unless ($parse_result eq 'ok') {
1.638     albertel 1595:             &logthis('Failed to parse '.$filepath.$file.
                   1596: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  1597:         }
                   1598:     }
1.259     www      1599: # Notify homeserver to grep it
                   1600: #
1.638     albertel 1601:     my $docuhome=&homeserver($docuname,$docudom);
1.494     albertel 1602:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      1603:     if ($fetchresult eq 'ok') {
1.259     www      1604: #
1.258     www      1605: # Return the URL to it
1.494     albertel 1606:         return '/uploaded/'.$path.$file;
1.263     www      1607:     } else {
1.494     albertel 1608:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   1609: 		 ': '.$fetchresult);
1.263     www      1610:         return '/adm/notfound.html';
                   1611:     }    
1.493     albertel 1612: }
                   1613: 
1.637     raeburn  1614: sub extract_embedded_items {
1.648     raeburn  1615:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
1.637     raeburn  1616:     my @state = ();
                   1617:     my %javafiles = (
                   1618:                       codebase => '',
                   1619:                       code => '',
                   1620:                       archive => ''
                   1621:                     );
                   1622:     my %mediafiles = (
                   1623:                       src => '',
                   1624:                       movie => '',
                   1625:                      );
1.648     raeburn  1626:     my $p;
                   1627:     if ($content) {
                   1628:         $p = HTML::LCParser->new($content);
                   1629:     } else {
                   1630:         $p = HTML::LCParser->new($filepath.'/'.$file);
                   1631:     }
1.641     albertel 1632:     while (my $t=$p->get_token()) {
1.640     albertel 1633: 	if ($t->[0] eq 'S') {
                   1634: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
                   1635: 	    push (@state, $tagname);
1.648     raeburn  1636:             if (lc($tagname) eq 'allow') {
                   1637:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   1638:             }
1.640     albertel 1639: 	    if (lc($tagname) eq 'img') {
                   1640: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   1641: 	    }
1.645     raeburn  1642:             if (lc($tagname) eq 'script') {
                   1643:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   1644:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   1645:                 } else {
                   1646:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   1647:                 }
                   1648:             }
                   1649:             if (lc($tagname) eq 'link') {
                   1650:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   1651:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   1652:                 }
                   1653:             }
1.640     albertel 1654: 	    if (lc($tagname) eq 'object' ||
                   1655: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   1656: 		foreach my $item (keys(%javafiles)) {
                   1657: 		    $javafiles{$item} = '';
                   1658: 		}
                   1659: 	    }
                   1660: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   1661: 		my $name = lc($attr->{'name'});
                   1662: 		foreach my $item (keys(%javafiles)) {
                   1663: 		    if ($name eq $item) {
                   1664: 			$javafiles{$item} = $attr->{'value'};
                   1665: 			last;
                   1666: 		    }
                   1667: 		}
                   1668: 		foreach my $item (keys(%mediafiles)) {
                   1669: 		    if ($name eq $item) {
                   1670: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   1671: 			last;
                   1672: 		    }
                   1673: 		}
                   1674: 	    }
                   1675: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   1676: 		foreach my $item (keys(%javafiles)) {
                   1677: 		    if ($attr->{$item}) {
                   1678: 			$javafiles{$item} = $attr->{$item};
                   1679: 			last;
                   1680: 		    }
                   1681: 		}
                   1682: 		foreach my $item (keys(%mediafiles)) {
                   1683: 		    if ($attr->{$item}) {
                   1684: 			&add_filetype($allfiles,$attr->{$item},$item);
                   1685: 			last;
                   1686: 		    }
                   1687: 		}
                   1688: 	    }
                   1689: 	} elsif ($t->[0] eq 'E') {
                   1690: 	    my ($tagname) = ($t->[1]);
                   1691: 	    if ($javafiles{'codebase'} ne '') {
                   1692: 		$javafiles{'codebase'} .= '/';
                   1693: 	    }  
                   1694: 	    if (lc($tagname) eq 'applet' ||
                   1695: 		lc($tagname) eq 'object' ||
                   1696: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   1697: 		) {
                   1698: 		foreach my $item (keys(%javafiles)) {
                   1699: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   1700: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   1701: 			&add_filetype($allfiles,$file,$item);
                   1702: 		    }
                   1703: 		}
                   1704: 	    } 
                   1705: 	    pop @state;
                   1706: 	}
                   1707:     }
1.637     raeburn  1708:     return 'ok';
                   1709: }
                   1710: 
1.639     albertel 1711: sub add_filetype {
                   1712:     my ($allfiles,$file,$type)=@_;
                   1713:     if (exists($allfiles->{$file})) {
                   1714: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   1715: 	    push(@{$allfiles->{$file}}, &escape($type));
                   1716: 	}
                   1717:     } else {
                   1718: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  1719:     }
                   1720: }
                   1721: 
1.493     albertel 1722: sub removeuploadedurl {
                   1723:     my ($url)=@_;
                   1724:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613     albertel 1725:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 1726: }
                   1727: 
                   1728: sub removeuserfile {
                   1729:     my ($docuname,$docudom,$fname)=@_;
                   1730:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  1731:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
                   1732:     if ($result eq 'ok') {
                   1733:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   1734:             my $metafile = $fname.'.meta';
                   1735:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 1736: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
                   1737:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  1738:             my $sqlresult = 
1.823     albertel 1739:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  1740:                                         'portfolio_metadata',$group,
                   1741:                                         'delete');
1.798     raeburn  1742:         }
                   1743:     }
                   1744:     return $result;
1.257     www      1745: }
1.15      www      1746: 
1.530     albertel 1747: sub mkdiruserfile {
                   1748:     my ($docuname,$docudom,$dir)=@_;
                   1749:     my $home=&homeserver($docuname,$docudom);
                   1750:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   1751: }
                   1752: 
1.531     albertel 1753: sub renameuserfile {
                   1754:     my ($docuname,$docudom,$old,$new)=@_;
                   1755:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  1756:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   1757:                         &escape("$old").':'.&escape("$new"),$home);
                   1758:     if ($result eq 'ok') {
                   1759:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   1760:             my $oldmeta = $old.'.meta';
                   1761:             my $newmeta = $new.'.meta';
                   1762:             my $metaresult = 
                   1763:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 1764: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   1765:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  1766:             my $sqlresult = 
1.823     albertel 1767:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  1768:                                         'portfolio_metadata',$group,
                   1769:                                         'delete');
1.798     raeburn  1770:         }
                   1771:     }
                   1772:     return $result;
1.531     albertel 1773: }
                   1774: 
1.14      www      1775: # ------------------------------------------------------------------------- Log
                   1776: 
                   1777: sub log {
                   1778:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      1779:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      1780: }
                   1781: 
                   1782: # ------------------------------------------------------------------ Course Log
1.352     www      1783: #
                   1784: # This routine flushes several buffers of non-mission-critical nature
                   1785: #
1.157     www      1786: 
                   1787: sub flushcourselogs {
1.352     www      1788:     &logthis('Flushing log buffers');
                   1789: #
                   1790: # course logs
                   1791: # This is a log of all transactions in a course, which can be used
                   1792: # for data mining purposes
                   1793: #
                   1794: # It also collects the courseid database, which lists last transaction
                   1795: # times and course titles for all courseids
                   1796: #
                   1797:     my %courseidbuffer=();
1.800     albertel 1798:     foreach my $crsid (keys %courselogs) {
1.352     www      1799:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      1800: 		          &escape($courselogs{$crsid}),
                   1801: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      1802: 	    delete $courselogs{$crsid};
                   1803:         } else {
                   1804:             &logthis('Failed to flush log buffer for '.$crsid);
                   1805:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 1806:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      1807:                         " exceeded maximum size, deleting.</font>");
                   1808:                delete $courselogs{$crsid};
                   1809:             }
1.352     www      1810:         }
                   1811:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
                   1812:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
1.516     raeburn  1813: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  1814:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.352     www      1815:         } else {
                   1816:            $courseidbuffer{$coursehombuf{$crsid}}=
1.516     raeburn  1817: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  1818:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.571     raeburn  1819:         }
1.191     harris41 1820:     }
1.352     www      1821: #
                   1822: # Write course id database (reverse lookup) to homeserver of courses 
                   1823: # Is used in pickcourse
                   1824: #
1.800     albertel 1825:     foreach my $crsid (keys(%courseidbuffer)) {
                   1826:         &courseidput($hostdom{$crsid},$courseidbuffer{$crsid},$crsid);
1.352     www      1827:     }
                   1828: #
                   1829: # File accesses
                   1830: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   1831: #
1.449     matthew  1832:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  1833:         if ($entry =~ /___count$/) {
                   1834:             my ($dom,$name);
1.807     albertel 1835:             ($dom,$name,undef)=
1.811     albertel 1836: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  1837:             if (! defined($dom) || $dom eq '' || 
                   1838:                 ! defined($name) || $name eq '') {
1.620     albertel 1839:                 my $cid = $env{'request.course.id'};
                   1840:                 $dom  = $env{'request.'.$cid.'.domain'};
                   1841:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  1842:             }
1.450     matthew  1843:             my $value = $accesshash{$entry};
                   1844:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   1845:             my %temphash=($url => $value);
1.449     matthew  1846:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   1847:             if ($result eq 'ok') {
                   1848:                 delete $accesshash{$entry};
                   1849:             } elsif ($result eq 'unknown_cmd') {
                   1850:                 # Target server has old code running on it.
1.450     matthew  1851:                 my %temphash=($entry => $value);
1.449     matthew  1852:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1853:                     delete $accesshash{$entry};
                   1854:                 }
                   1855:             }
                   1856:         } else {
1.811     albertel 1857:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  1858:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  1859:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1860:                 delete $accesshash{$entry};
                   1861:             }
1.185     www      1862:         }
1.191     harris41 1863:     }
1.352     www      1864: #
                   1865: # Roles
                   1866: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   1867: #
1.800     albertel 1868:     foreach my $entry (keys(%userrolehash)) {
1.351     www      1869:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      1870: 	    split(/\:/,$entry);
                   1871:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      1872:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      1873:                 $rudom,$runame) eq 'ok') {
                   1874: 	    delete $userrolehash{$entry};
                   1875:         }
                   1876:     }
1.662     raeburn  1877: #
                   1878: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   1879: #
                   1880:     my %domrolebuffer = ();
                   1881:     foreach my $entry (keys %domainrolehash) {
                   1882:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split/:/,$entry;
                   1883:         if ($domrolebuffer{$rudom}) {
                   1884:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   1885:                       '='.&escape($domainrolehash{$entry});
                   1886:         } else {
                   1887:             $domrolebuffer{$rudom}.=&escape($entry).
                   1888:                       '='.&escape($domainrolehash{$entry});
                   1889:         }
                   1890:         delete $domainrolehash{$entry};
                   1891:     }
                   1892:     foreach my $dom (keys(%domrolebuffer)) {
                   1893:         foreach my $tryserver (keys %libserv) {
                   1894:             if ($hostdom{$tryserver} eq $dom) {
                   1895:                 unless (&reply('domroleput:'.$dom.':'.
                   1896:                   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   1897:                     &logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   1898:                 }
                   1899:             }
                   1900:         }
                   1901:     }
1.186     www      1902:     $dumpcount++;
1.157     www      1903: }
                   1904: 
                   1905: sub courselog {
                   1906:     my $what=shift;
1.158     www      1907:     $what=time.':'.$what;
1.620     albertel 1908:     unless ($env{'request.course.id'}) { return ''; }
                   1909:     $coursedombuf{$env{'request.course.id'}}=
                   1910:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   1911:     $coursenumbuf{$env{'request.course.id'}}=
                   1912:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   1913:     $coursehombuf{$env{'request.course.id'}}=
                   1914:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   1915:     $coursedescrbuf{$env{'request.course.id'}}=
                   1916:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   1917:     $courseinstcodebuf{$env{'request.course.id'}}=
                   1918:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   1919:     $courseownerbuf{$env{'request.course.id'}}=
                   1920:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  1921:     $coursetypebuf{$env{'request.course.id'}}=
                   1922:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 1923:     if (defined $courselogs{$env{'request.course.id'}}) {
                   1924: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      1925:     } else {
1.620     albertel 1926: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      1927:     }
1.620     albertel 1928:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      1929: 	&flushcourselogs();
                   1930:     }
1.158     www      1931: }
                   1932: 
                   1933: sub courseacclog {
                   1934:     my $fnsymb=shift;
1.620     albertel 1935:     unless ($env{'request.course.id'}) { return ''; }
                   1936:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 1937:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      1938:         $what.=':POST';
1.583     matthew  1939:         # FIXME: Probably ought to escape things....
1.800     albertel 1940: 	foreach my $key (keys(%env)) {
                   1941:             if ($key=~/^form\.(.*)/) {
                   1942: 		$what.=':'.$1.'='.$env{$key};
1.158     www      1943:             }
1.191     harris41 1944:         }
1.583     matthew  1945:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   1946:         # FIXME: We should not be depending on a form parameter that someone
                   1947:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 1948:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  1949:             $what.= ':POST';
                   1950:             # FIXME: Probably ought to escape things....
                   1951:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   1952:                                  'crsdiscuss') {
1.620     albertel 1953:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  1954:             }
                   1955:         }
1.158     www      1956:     }
                   1957:     &courselog($what);
1.149     www      1958: }
                   1959: 
1.185     www      1960: sub countacc {
                   1961:     my $url=&declutter(shift);
1.458     matthew  1962:     return if (! defined($url) || $url eq '');
1.620     albertel 1963:     unless ($env{'request.course.id'}) { return ''; }
                   1964:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      1965:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  1966:     $accesshash{$key}++;
1.185     www      1967: }
1.349     www      1968: 
1.361     www      1969: sub linklog {
                   1970:     my ($from,$to)=@_;
                   1971:     $from=&declutter($from);
                   1972:     $to=&declutter($to);
                   1973:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   1974:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   1975: }
                   1976:   
1.349     www      1977: sub userrolelog {
                   1978:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  1979:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  1980:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  1981:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   1982:         ($trole=~/^ta/)) {
1.350     www      1983:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   1984:        $userrolehash
                   1985:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      1986:                     =$tend.':'.$tstart;
1.662     raeburn  1987:     }
                   1988:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   1989:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   1990:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   1991:         ($trole=~/^sc/)) {
                   1992:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   1993:        $domainrolehash
                   1994:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   1995:                     = $tend.':'.$tstart;
                   1996:     }
1.351     www      1997: }
                   1998: 
                   1999: sub get_course_adv_roles {
                   2000:     my $cid=shift;
1.620     albertel 2001:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      2002:     my %coursehash=&coursedescription($cid);
1.470     www      2003:     my %nothide=();
1.800     albertel 2004:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2005: 	$nothide{join(':',split(/[\@\:]/,$user))}=1;
1.470     www      2006:     }
1.351     www      2007:     my %returnhash=();
                   2008:     my %dumphash=
                   2009:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   2010:     my $now=time;
1.800     albertel 2011:     foreach my $entry (keys %dumphash) {
                   2012: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      2013:         if (($tstart) && ($tstart<0)) { next; }
                   2014:         if (($tend) && ($tend<$now)) { next; }
                   2015:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 2016:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 2017: 	if ($username eq '' || $domain eq '') { next; }
1.470     www      2018: 	if ((&privileged($username,$domain)) && 
                   2019: 	    (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 2020: 	if ($role eq 'cr') { next; }
1.351     www      2021:         my $key=&plaintext($role);
                   2022:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
                   2023:         if ($returnhash{$key}) {
                   2024: 	    $returnhash{$key}.=','.$username.':'.$domain;
                   2025:         } else {
                   2026:             $returnhash{$key}=$username.':'.$domain;
                   2027:         }
1.400     www      2028:      }
                   2029:     return %returnhash;
                   2030: }
                   2031: 
                   2032: sub get_my_roles {
                   2033:     my ($uname,$udom)=@_;
1.620     albertel 2034:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   2035:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.400     www      2036:     my %dumphash=
                   2037:             &dump('nohist_userroles',$udom,$uname);
                   2038:     my %returnhash=();
                   2039:     my $now=time;
1.800     albertel 2040:     foreach my $entry (keys(%dumphash)) {
                   2041: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.400     www      2042:         if (($tstart) && ($tstart<0)) { next; }
                   2043:         if (($tend) && ($tend<$now)) { next; }
                   2044:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 2045:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.400     www      2046: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
1.373     www      2047:      }
                   2048:     return %returnhash;
1.399     www      2049: }
                   2050: 
                   2051: # ----------------------------------------------------- Frontpage Announcements
                   2052: #
                   2053: #
                   2054: 
                   2055: sub postannounce {
                   2056:     my ($server,$text)=@_;
                   2057:     unless (&allowed('psa',$hostdom{$server})) { return 'refused'; }
                   2058:     unless ($text=~/\w/) { $text=''; }
                   2059:     return &reply('setannounce:'.&escape($text),$server);
                   2060: }
                   2061: 
                   2062: sub getannounce {
1.448     albertel 2063: 
                   2064:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      2065: 	my $announcement='';
1.800     albertel 2066: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 2067: 	close($fh);
1.399     www      2068: 	if ($announcement=~/\w/) { 
                   2069: 	    return 
                   2070:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 2071:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      2072: 	} else {
                   2073: 	    return '';
                   2074: 	}
                   2075:     } else {
                   2076: 	return '';
                   2077:     }
1.351     www      2078: }
1.353     www      2079: 
                   2080: # ---------------------------------------------------------- Course ID routines
                   2081: # Deal with domain's nohist_courseid.db files
                   2082: #
                   2083: 
                   2084: sub courseidput {
                   2085:     my ($domain,$what,$coursehome)=@_;
                   2086:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   2087: }
                   2088: 
                   2089: sub courseiddump {
1.791     raeburn  2090:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok)=@_;
1.353     www      2091:     my %returnhash=();
1.355     www      2092:     unless ($domfilter) { $domfilter=''; }
1.353     www      2093:     foreach my $tryserver (keys %libserv) {
1.511     raeburn  2094:         if ( ($hostidflag == 1 && grep/^$tryserver$/,@{$hostidref}) || (!defined($hostidflag)) ) {
1.506     raeburn  2095: 	    if ((!$domfilter) || ($hostdom{$tryserver} eq $domfilter)) {
1.800     albertel 2096: 	        foreach my $line (
1.506     raeburn  2097:                  split(/\&/,&reply('courseiddump:'.$hostdom{$tryserver}.':'.
1.571     raeburn  2098: 			       $sincefilter.':'.&escape($descfilter).':'.
1.791     raeburn  2099:                                &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter).':'.&escape($typefilter).':'.&escape($regexp_ok),
1.354     www      2100:                                $tryserver))) {
1.800     albertel 2101: 		    my ($key,$value)=split(/\=/,$line,2);
1.506     raeburn  2102:                     if (($key) && ($value)) {
1.516     raeburn  2103: 		        $returnhash{&unescape($key)}=$value;
1.506     raeburn  2104:                     }
1.353     www      2105:                 }
                   2106:             }
                   2107:         }
                   2108:     }
                   2109:     return %returnhash;
                   2110: }
                   2111: 
1.658     raeburn  2112: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  2113: 
                   2114: sub dcmailput {
1.685     raeburn  2115:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  2116:     my $status = &Apache::lonnet::critical(
1.740     www      2117:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   2118:        &escape($message),$server);
1.662     raeburn  2119:     return $status;
                   2120: }
                   2121: 
1.658     raeburn  2122: sub dcmaildump {
                   2123:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  2124:     my %returnhash=();
                   2125:     if (exists($domain_primary{$dom})) {
                   2126:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   2127:                                                          &escape($enddate).':';
                   2128: 	my @esc_senders=map { &escape($_)} @$senders;
                   2129: 	$cmd.=&escape(join('&',@esc_senders));
1.800     albertel 2130: 	foreach my $line (split(/\&/,&reply($cmd,$domain_primary{$dom}))) {
                   2131:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  2132:             if (($key) && ($value)) {
                   2133:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  2134:             }
                   2135:         }
                   2136:     }
                   2137:     return %returnhash;
                   2138: }
1.662     raeburn  2139: # ---------------------------------------------------------- Domain roles
                   2140: 
                   2141: sub get_domain_roles {
                   2142:     my ($dom,$roles,$startdate,$enddate)=@_;
                   2143:     if (undef($startdate) || $startdate eq '') {
                   2144:         $startdate = '.';
                   2145:     }
                   2146:     if (undef($enddate) || $enddate eq '') {
                   2147:         $enddate = '.';
                   2148:     }
                   2149:     my $rolelist = join(':',@{$roles});
                   2150:     my %personnel = ();
                   2151:     foreach my $tryserver (keys(%libserv)) {
                   2152:         if ($hostdom{$tryserver} eq $dom) {
                   2153:             %{$personnel{$tryserver}}=();
1.800     albertel 2154:             foreach my $line (
1.662     raeburn  2155:                 split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   2156:                    &escape($startdate).':'.&escape($enddate).':'.
                   2157:                    &escape($rolelist), $tryserver))) {
1.800     albertel 2158:                 my ($key,$value) = split(/\=/,$line,2);
1.662     raeburn  2159:                 if (($key) && ($value)) {
                   2160:                     $personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   2161:                 }
                   2162:             }
                   2163:         }
                   2164:     }
                   2165:     return %personnel;
                   2166: }
1.658     raeburn  2167: 
1.149     www      2168: # ----------------------------------------------------------- Check out an item
                   2169: 
1.504     albertel 2170: sub get_first_access {
                   2171:     my ($type,$argsymb)=@_;
1.790     albertel 2172:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2173:     if ($argsymb) { $symb=$argsymb; }
                   2174:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2175:     if ($type eq 'map') {
                   2176: 	$res=&symbread($map);
                   2177:     } else {
                   2178: 	$res=$symb;
                   2179:     }
                   2180:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   2181:     return $times{"$courseid\0$res"};
1.504     albertel 2182: }
                   2183: 
                   2184: sub set_first_access {
                   2185:     my ($type)=@_;
1.790     albertel 2186:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2187:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2188:     if ($type eq 'map') {
                   2189: 	$res=&symbread($map);
                   2190:     } else {
                   2191: 	$res=$symb;
                   2192:     }
                   2193:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 2194:     if (!$firstaccess) {
1.588     albertel 2195: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 2196:     }
                   2197:     return 'already_set';
1.504     albertel 2198: }
                   2199: 
1.149     www      2200: sub checkout {
                   2201:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   2202:     my $now=time;
                   2203:     my $lonhost=$perlvar{'lonHostID'};
                   2204:     my $infostr=&escape(
1.234     www      2205:                  'CHECKOUTTOKEN&'.
1.149     www      2206:                  $tuname.'&'.
                   2207:                  $tudom.'&'.
                   2208:                  $tcrsid.'&'.
                   2209:                  $symb.'&'.
                   2210: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   2211:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      2212:     if ($token=~/^error\:/) { 
1.672     albertel 2213:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2214:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2215:                  "</font>");
                   2216:         return ''; 
                   2217:     }
                   2218: 
1.149     www      2219:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   2220:     $token=~tr/a-z/A-Z/;
                   2221: 
1.153     www      2222:     my %infohash=('resource.0.outtoken' => $token,
                   2223:                   'resource.0.checkouttime' => $now,
                   2224:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      2225: 
                   2226:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2227:        return '';
1.151     www      2228:     } else {
1.672     albertel 2229:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2230:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2231:                  "</font>");
1.149     www      2232:     }    
                   2233: 
                   2234:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2235:                          &escape('Checkout '.$infostr.' - '.
                   2236:                                                  $token)) ne 'ok') {
                   2237: 	return '';
1.151     www      2238:     } else {
1.672     albertel 2239:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2240:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2241:                  "</font>");
1.149     www      2242:     }
1.151     www      2243:     return $token;
1.149     www      2244: }
                   2245: 
                   2246: # ------------------------------------------------------------ Check in an item
                   2247: 
                   2248: sub checkin {
                   2249:     my $token=shift;
1.150     www      2250:     my $now=time;
                   2251:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   2252:     $lonhost=~tr/A-Z/a-z/;
1.595     albertel 2253:     my $dtoken=$ta.'_'.$hostname{$lonhost}.'_'.$tb;
1.150     www      2254:     $dtoken=~s/\W/\_/g;
1.234     www      2255:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      2256:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   2257: 
1.154     www      2258:     unless (($tuname) && ($tudom)) {
                   2259:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   2260:         return '';
                   2261:     }
                   2262:     
                   2263:     unless (&allowed('mgr',$tcrsid)) {
                   2264:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 2265:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      2266:         return '';
                   2267:     }
                   2268: 
1.153     www      2269:     my %infohash=('resource.0.intoken' => $token,
                   2270:                   'resource.0.checkintime' => $now,
                   2271:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      2272: 
                   2273:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2274:        return '';
                   2275:     }    
                   2276: 
                   2277:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2278:                          &escape('Checkin - '.$token)) ne 'ok') {
                   2279: 	return '';
                   2280:     }
                   2281: 
                   2282:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      2283: }
                   2284: 
                   2285: # --------------------------------------------- Set Expire Date for Spreadsheet
                   2286: 
                   2287: sub expirespread {
                   2288:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 2289:     my $cid=$env{'request.course.id'}; 
1.110     www      2290:     if ($cid) {
                   2291:        my $now=time;
                   2292:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 2293:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   2294:                             $env{'course.'.$cid.'.num'}.
1.110     www      2295: 	        	    ':nohist_expirationdates:'.
                   2296:                             &escape($key).'='.$now,
1.620     albertel 2297:                             $env{'course.'.$cid.'.home'})
1.110     www      2298:     }
                   2299:     return 'ok';
1.14      www      2300: }
                   2301: 
1.109     www      2302: # ----------------------------------------------------- Devalidate Spreadsheets
                   2303: 
                   2304: sub devalidate {
1.325     www      2305:     my ($symb,$uname,$udom)=@_;
1.620     albertel 2306:     my $cid=$env{'request.course.id'}; 
1.109     www      2307:     if ($cid) {
1.391     matthew  2308:         # delete the stored spreadsheets for
                   2309:         # - the student level sheet of this user in course's homespace
                   2310:         # - the assessment level sheet for this resource 
                   2311:         #   for this user in user's homespace
1.553     albertel 2312: 	# - current conditional state info
1.325     www      2313: 	my $key=$uname.':'.$udom.':';
1.109     www      2314:         my $status=
1.299     matthew  2315: 	    &del('nohist_calculatedsheets',
1.391     matthew  2316: 		 [$key.'studentcalc:'],
1.620     albertel 2317: 		 $env{'course.'.$cid.'.domain'},
                   2318: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 2319: 		.' '.
                   2320: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  2321: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      2322:         unless ($status eq 'ok ok') {
                   2323:            &logthis('Could not devalidate spreadsheet '.
1.325     www      2324:                     $uname.' at '.$udom.' for '.
1.109     www      2325: 		    $symb.': '.$status);
1.133     albertel 2326:         }
1.553     albertel 2327: 	&delenv('user.state.'.$cid);
1.109     www      2328:     }
                   2329: }
                   2330: 
1.265     albertel 2331: sub get_scalar {
                   2332:     my ($string,$end) = @_;
                   2333:     my $value;
                   2334:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   2335: 	$value = $1;
                   2336:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   2337: 	$value = $1;
                   2338:     }
                   2339:     return &unescape($value);
                   2340: }
                   2341: 
                   2342: sub array2str {
                   2343:   my (@array) = @_;
                   2344:   my $result=&arrayref2str(\@array);
                   2345:   $result=~s/^__ARRAY_REF__//;
                   2346:   $result=~s/__END_ARRAY_REF__$//;
                   2347:   return $result;
                   2348: }
                   2349: 
1.204     albertel 2350: sub arrayref2str {
                   2351:   my ($arrayref) = @_;
1.265     albertel 2352:   my $result='__ARRAY_REF__';
1.204     albertel 2353:   foreach my $elem (@$arrayref) {
1.265     albertel 2354:     if(ref($elem) eq 'ARRAY') {
                   2355:       $result.=&arrayref2str($elem).'&';
                   2356:     } elsif(ref($elem) eq 'HASH') {
                   2357:       $result.=&hashref2str($elem).'&';
                   2358:     } elsif(ref($elem)) {
                   2359:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 2360:     } else {
                   2361:       $result.=&escape($elem).'&';
                   2362:     }
                   2363:   }
                   2364:   $result=~s/\&$//;
1.265     albertel 2365:   $result .= '__END_ARRAY_REF__';
1.204     albertel 2366:   return $result;
                   2367: }
                   2368: 
1.168     albertel 2369: sub hash2str {
1.204     albertel 2370:   my (%hash) = @_;
                   2371:   my $result=&hashref2str(\%hash);
1.265     albertel 2372:   $result=~s/^__HASH_REF__//;
                   2373:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 2374:   return $result;
                   2375: }
                   2376: 
                   2377: sub hashref2str {
                   2378:   my ($hashref)=@_;
1.265     albertel 2379:   my $result='__HASH_REF__';
1.800     albertel 2380:   foreach my $key (sort(keys(%$hashref))) {
                   2381:     if (ref($key) eq 'ARRAY') {
                   2382:       $result.=&arrayref2str($key).'=';
                   2383:     } elsif (ref($key) eq 'HASH') {
                   2384:       $result.=&hashref2str($key).'=';
                   2385:     } elsif (ref($key)) {
1.265     albertel 2386:       $result.='=';
1.800     albertel 2387:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 2388:     } else {
1.800     albertel 2389: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 2390:     }
                   2391: 
1.800     albertel 2392:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   2393:       $result.=&arrayref2str($hashref->{$key}).'&';
                   2394:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   2395:       $result.=&hashref2str($hashref->{$key}).'&';
                   2396:     } elsif(ref($hashref->{$key})) {
1.265     albertel 2397:        $result.='&';
1.800     albertel 2398:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 2399:     } else {
1.800     albertel 2400:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 2401:     }
                   2402:   }
1.168     albertel 2403:   $result=~s/\&$//;
1.265     albertel 2404:   $result .= '__END_HASH_REF__';
1.168     albertel 2405:   return $result;
                   2406: }
                   2407: 
                   2408: sub str2hash {
1.265     albertel 2409:     my ($string)=@_;
                   2410:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   2411:     return %$hash;
                   2412: }
                   2413: 
                   2414: sub str2hashref {
1.168     albertel 2415:   my ($string) = @_;
1.265     albertel 2416: 
                   2417:   my %hash;
                   2418: 
                   2419:   if($string !~ /^__HASH_REF__/) {
                   2420:       if (! ($string eq '' || !defined($string))) {
                   2421: 	  $hash{'error'}='Not hash reference';
                   2422:       }
                   2423:       return (\%hash, $string);
                   2424:   }
                   2425: 
                   2426:   $string =~ s/^__HASH_REF__//;
                   2427: 
                   2428:   while($string !~ /^__END_HASH_REF__/) {
                   2429:       #key
                   2430:       my $key='';
                   2431:       if($string =~ /^__HASH_REF__/) {
                   2432:           ($key, $string)=&str2hashref($string);
                   2433:           if(defined($key->{'error'})) {
                   2434:               $hash{'error'}='Bad data';
                   2435:               return (\%hash, $string);
                   2436:           }
                   2437:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2438:           ($key, $string)=&str2arrayref($string);
                   2439:           if($key->[0] eq 'Array reference error') {
                   2440:               $hash{'error'}='Bad data';
                   2441:               return (\%hash, $string);
                   2442:           }
                   2443:       } else {
                   2444:           $string =~ s/^(.*?)=//;
1.267     albertel 2445: 	  $key=&unescape($1);
1.265     albertel 2446:       }
                   2447:       $string =~ s/^=//;
                   2448: 
                   2449:       #value
                   2450:       my $value='';
                   2451:       if($string =~ /^__HASH_REF__/) {
                   2452:           ($value, $string)=&str2hashref($string);
                   2453:           if(defined($value->{'error'})) {
                   2454:               $hash{'error'}='Bad data';
                   2455:               return (\%hash, $string);
                   2456:           }
                   2457:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2458:           ($value, $string)=&str2arrayref($string);
                   2459:           if($value->[0] eq 'Array reference error') {
                   2460:               $hash{'error'}='Bad data';
                   2461:               return (\%hash, $string);
                   2462:           }
                   2463:       } else {
                   2464: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   2465:       }
                   2466:       $string =~ s/^&//;
                   2467: 
                   2468:       $hash{$key}=$value;
1.204     albertel 2469:   }
1.265     albertel 2470: 
                   2471:   $string =~ s/^__END_HASH_REF__//;
                   2472: 
                   2473:   return (\%hash, $string);
1.204     albertel 2474: }
                   2475: 
                   2476: sub str2array {
1.265     albertel 2477:     my ($string)=@_;
                   2478:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   2479:     return @$array;
                   2480: }
                   2481: 
                   2482: sub str2arrayref {
1.204     albertel 2483:   my ($string) = @_;
1.265     albertel 2484:   my @array;
                   2485: 
                   2486:   if($string !~ /^__ARRAY_REF__/) {
                   2487:       if (! ($string eq '' || !defined($string))) {
                   2488: 	  $array[0]='Array reference error';
                   2489:       }
                   2490:       return (\@array, $string);
                   2491:   }
                   2492: 
                   2493:   $string =~ s/^__ARRAY_REF__//;
                   2494: 
                   2495:   while($string !~ /^__END_ARRAY_REF__/) {
                   2496:       my $value='';
                   2497:       if($string =~ /^__HASH_REF__/) {
                   2498:           ($value, $string)=&str2hashref($string);
                   2499:           if(defined($value->{'error'})) {
                   2500:               $array[0] ='Array reference error';
                   2501:               return (\@array, $string);
                   2502:           }
                   2503:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2504:           ($value, $string)=&str2arrayref($string);
                   2505:           if($value->[0] eq 'Array reference error') {
                   2506:               $array[0] ='Array reference error';
                   2507:               return (\@array, $string);
                   2508:           }
                   2509:       } else {
                   2510: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   2511:       }
                   2512:       $string =~ s/^&//;
                   2513: 
                   2514:       push(@array, $value);
1.191     harris41 2515:   }
1.265     albertel 2516: 
                   2517:   $string =~ s/^__END_ARRAY_REF__//;
                   2518: 
                   2519:   return (\@array, $string);
1.168     albertel 2520: }
                   2521: 
1.167     albertel 2522: # -------------------------------------------------------------------Temp Store
                   2523: 
1.168     albertel 2524: sub tmpreset {
                   2525:   my ($symb,$namespace,$domain,$stuname) = @_;
                   2526:   if (!$symb) {
                   2527:     $symb=&symbread();
1.620     albertel 2528:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2529:   }
                   2530:   $symb=escape($symb);
                   2531: 
1.620     albertel 2532:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 2533:   $namespace=~s/\//\_/g;
                   2534:   $namespace=~s/\W//g;
                   2535: 
1.620     albertel 2536:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2537:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2538:   if ($domain eq 'public' && $stuname eq 'public') {
                   2539:       $stuname=$ENV{'REMOTE_ADDR'};
                   2540:   }
1.168     albertel 2541:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2542:   my %hash;
                   2543:   if (tie(%hash,'GDBM_File',
                   2544: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2545: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2546:     foreach my $key (keys %hash) {
1.180     albertel 2547:       if ($key=~ /:$symb/) {
1.168     albertel 2548: 	delete($hash{$key});
                   2549:       }
                   2550:     }
                   2551:   }
                   2552: }
                   2553: 
1.167     albertel 2554: sub tmpstore {
1.168     albertel 2555:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2556: 
                   2557:   if (!$symb) {
                   2558:     $symb=&symbread();
1.620     albertel 2559:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2560:   }
                   2561:   $symb=escape($symb);
                   2562: 
                   2563:   if (!$namespace) {
                   2564:     # I don't think we would ever want to store this for a course.
                   2565:     # it seems this will only be used if we don't have a course.
1.620     albertel 2566:     #$namespace=$env{'request.course.id'};
1.168     albertel 2567:     #if (!$namespace) {
1.620     albertel 2568:       $namespace=$env{'request.state'};
1.168     albertel 2569:     #}
                   2570:   }
                   2571:   $namespace=~s/\//\_/g;
                   2572:   $namespace=~s/\W//g;
1.620     albertel 2573:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2574:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2575:   if ($domain eq 'public' && $stuname eq 'public') {
                   2576:       $stuname=$ENV{'REMOTE_ADDR'};
                   2577:   }
1.168     albertel 2578:   my $now=time;
                   2579:   my %hash;
                   2580:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2581:   if (tie(%hash,'GDBM_File',
                   2582: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2583: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2584:     $hash{"version:$symb"}++;
                   2585:     my $version=$hash{"version:$symb"};
                   2586:     my $allkeys=''; 
                   2587:     foreach my $key (keys(%$storehash)) {
                   2588:       $allkeys.=$key.':';
1.591     albertel 2589:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 2590:     }
                   2591:     $hash{"$version:$symb:timestamp"}=$now;
                   2592:     $allkeys.='timestamp';
                   2593:     $hash{"$version:keys:$symb"}=$allkeys;
                   2594:     if (untie(%hash)) {
                   2595:       return 'ok';
                   2596:     } else {
                   2597:       return "error:$!";
                   2598:     }
                   2599:   } else {
                   2600:     return "error:$!";
                   2601:   }
                   2602: }
1.167     albertel 2603: 
1.168     albertel 2604: # -----------------------------------------------------------------Temp Restore
1.167     albertel 2605: 
1.168     albertel 2606: sub tmprestore {
                   2607:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 2608: 
1.168     albertel 2609:   if (!$symb) {
                   2610:     $symb=&symbread();
1.620     albertel 2611:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2612:   }
                   2613:   $symb=escape($symb);
                   2614: 
1.620     albertel 2615:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 2616: 
1.620     albertel 2617:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2618:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2619:   if ($domain eq 'public' && $stuname eq 'public') {
                   2620:       $stuname=$ENV{'REMOTE_ADDR'};
                   2621:   }
1.168     albertel 2622:   my %returnhash;
                   2623:   $namespace=~s/\//\_/g;
                   2624:   $namespace=~s/\W//g;
                   2625:   my %hash;
                   2626:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2627:   if (tie(%hash,'GDBM_File',
                   2628: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2629: 	  &GDBM_READER(),0640)) {
1.168     albertel 2630:     my $version=$hash{"version:$symb"};
                   2631:     $returnhash{'version'}=$version;
                   2632:     my $scope;
                   2633:     for ($scope=1;$scope<=$version;$scope++) {
                   2634:       my $vkeys=$hash{"$scope:keys:$symb"};
                   2635:       my @keys=split(/:/,$vkeys);
                   2636:       my $key;
                   2637:       $returnhash{"$scope:keys"}=$vkeys;
                   2638:       foreach $key (@keys) {
1.591     albertel 2639: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   2640: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 2641:       }
                   2642:     }
1.168     albertel 2643:     if (!(untie(%hash))) {
                   2644:       return "error:$!";
                   2645:     }
                   2646:   } else {
                   2647:     return "error:$!";
                   2648:   }
                   2649:   return %returnhash;
1.167     albertel 2650: }
                   2651: 
1.9       www      2652: # ----------------------------------------------------------------------- Store
                   2653: 
                   2654: sub store {
1.124     www      2655:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2656:     my $home='';
                   2657: 
1.168     albertel 2658:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2659: 
1.213     www      2660:     $symb=&symbclean($symb);
1.122     albertel 2661:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2662: 
1.620     albertel 2663:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2664:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2665: 
                   2666:     &devalidate($symb,$stuname,$domain);
1.109     www      2667: 
                   2668:     $symb=escape($symb);
1.187     www      2669:     if (!$namespace) { 
1.620     albertel 2670:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2671:           return ''; 
                   2672:        } 
                   2673:     }
1.620     albertel 2674:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2675: 
                   2676:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2677:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   2678: 
1.12      www      2679:     my $namevalue='';
1.800     albertel 2680:     foreach my $key (keys(%$storehash)) {
                   2681:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 2682:     }
1.12      www      2683:     $namevalue=~s/\&$//;
1.187     www      2684:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      2685:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      2686: }
                   2687: 
1.47      www      2688: # -------------------------------------------------------------- Critical Store
                   2689: 
                   2690: sub cstore {
1.124     www      2691:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2692:     my $home='';
                   2693: 
1.168     albertel 2694:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2695: 
1.213     www      2696:     $symb=&symbclean($symb);
1.122     albertel 2697:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2698: 
1.620     albertel 2699:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2700:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2701: 
                   2702:     &devalidate($symb,$stuname,$domain);
1.109     www      2703: 
                   2704:     $symb=escape($symb);
1.187     www      2705:     if (!$namespace) { 
1.620     albertel 2706:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2707:           return ''; 
                   2708:        } 
                   2709:     }
1.620     albertel 2710:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2711: 
                   2712:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2713:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 2714: 
1.47      www      2715:     my $namevalue='';
1.800     albertel 2716:     foreach my $key (keys(%$storehash)) {
                   2717:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 2718:     }
1.47      www      2719:     $namevalue=~s/\&$//;
1.187     www      2720:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      2721:     return critical
                   2722:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      2723: }
                   2724: 
1.9       www      2725: # --------------------------------------------------------------------- Restore
                   2726: 
                   2727: sub restore {
1.124     www      2728:     my ($symb,$namespace,$domain,$stuname) = @_;
                   2729:     my $home='';
                   2730: 
1.168     albertel 2731:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2732: 
1.122     albertel 2733:     if (!$symb) {
                   2734:       unless ($symb=escape(&symbread())) { return ''; }
                   2735:     } else {
1.213     www      2736:       $symb=&escape(&symbclean($symb));
1.122     albertel 2737:     }
1.188     www      2738:     if (!$namespace) { 
1.620     albertel 2739:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      2740:           return ''; 
                   2741:        } 
                   2742:     }
1.620     albertel 2743:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2744:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   2745:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 2746:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   2747: 
1.12      www      2748:     my %returnhash=();
1.800     albertel 2749:     foreach my $line (split(/\&/,$answer)) {
                   2750: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 2751:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 2752:     }
1.75      www      2753:     my $version;
                   2754:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 2755:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   2756:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 2757:        }
1.75      www      2758:     }
1.13      www      2759:     return %returnhash;
1.34      www      2760: }
                   2761: 
                   2762: # ---------------------------------------------------------- Course Description
                   2763: 
                   2764: sub coursedescription {
1.731     albertel 2765:     my ($courseid,$args)=@_;
1.34      www      2766:     $courseid=~s/^\///;
1.49      www      2767:     $courseid=~s/\_/\//g;
1.34      www      2768:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 2769:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 2770:     my $normalid=$cdomain.'_'.$cnum;
                   2771:     # need to always cache even if we get errors otherwise we keep 
                   2772:     # trying and trying and trying to get the course description.
                   2773:     my %envhash=();
                   2774:     my %returnhash=();
1.731     albertel 2775:     
                   2776:     my $expiretime=600;
                   2777:     if ($env{'request.course.id'} eq $normalid) {
                   2778: 	$expiretime=120;
                   2779:     }
                   2780: 
                   2781:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   2782:     if (!$args->{'freshen_cache'}
                   2783: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   2784: 	foreach my $key (keys(%env)) {
                   2785: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   2786: 	    my ($setting) = $1;
                   2787: 	    $returnhash{$setting} = $env{$key};
                   2788: 	}
                   2789: 	return %returnhash;
                   2790:     }
                   2791: 
                   2792:     # get the data agin
                   2793:     if (!$args->{'one_time'}) {
                   2794: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   2795:     }
1.811     albertel 2796: 
1.34      www      2797:     if ($chome ne 'no_host') {
1.302     albertel 2798:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 2799:        if (!exists($returnhash{'con_lost'})) {
                   2800:            $returnhash{'home'}= $chome;
                   2801: 	   $returnhash{'domain'} = $cdomain;
                   2802: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  2803:            if (!defined($returnhash{'type'})) {
                   2804:                $returnhash{'type'} = 'Course';
                   2805:            }
1.130     albertel 2806:            while (my ($name,$value) = each %returnhash) {
1.53      www      2807:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 2808:            }
1.270     www      2809:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      2810:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 2811: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      2812:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   2813:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   2814:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      2815:        }
                   2816:     }
1.731     albertel 2817:     if (!$args->{'one_time'}) {
                   2818: 	&appenv(%envhash);
                   2819:     }
1.302     albertel 2820:     return %returnhash;
1.461     www      2821: }
                   2822: 
                   2823: # -------------------------------------------------See if a user is privileged
                   2824: 
                   2825: sub privileged {
                   2826:     my ($username,$domain)=@_;
                   2827:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   2828: 			&homeserver($username,$domain));
                   2829:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   2830:     my $now=time;
                   2831:     if ($rolesdump ne '') {
1.800     albertel 2832:         foreach my $entry (split(/&/,$rolesdump)) {
                   2833: 	    if ($entry!~/^rolesdef_/) {
                   2834: 		my ($area,$role)=split(/=/,$entry);
1.461     www      2835: 		$area=~s/\_\w\w$//;
                   2836: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   2837: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   2838: 		    my $active=1;
                   2839: 		    if ($tend) {
                   2840: 			if ($tend<$now) { $active=0; }
                   2841: 		    }
                   2842: 		    if ($tstart) {
                   2843: 			if ($tstart>$now) { $active=0; }
                   2844: 		    }
                   2845: 		    if ($active) { return 1; }
                   2846: 		}
                   2847: 	    }
                   2848: 	}
                   2849:     }
                   2850:     return 0;
1.9       www      2851: }
1.1       albertel 2852: 
1.103     harris41 2853: # -------------------------------------------------------- Get user privileges
1.11      www      2854: 
                   2855: sub rolesinit {
                   2856:     my ($domain,$username,$authhost)=@_;
                   2857:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12      www      2858:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11      www      2859:     my %allroles=();
1.678     raeburn  2860:     my %allgroups=();   
1.11      www      2861:     my $now=time;
1.743     albertel 2862:     my %userroles = ('user.login.time' => $now);
1.678     raeburn  2863:     my $group_privs;
1.11      www      2864: 
                   2865:     if ($rolesdump ne '') {
1.800     albertel 2866:         foreach my $entry (split(/&/,$rolesdump)) {
                   2867: 	  if ($entry!~/^rolesdef_/) {
                   2868:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 2869: 	    $area=~s/\_\w\w$//;
1.678     raeburn  2870:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 2871: 	    if ($role=~/^cr/) { 
1.807     albertel 2872: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   2873: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 2874: 		    ($tend,$tstart)=split('_',$trest);
                   2875: 		} else {
                   2876: 		    $trole=$role;
                   2877: 		}
1.678     raeburn  2878:             } elsif ($role =~ m|^gr/|) {
                   2879:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   2880:                 ($trole,$group_privs) = split(/\//,$trole);
                   2881:                 $group_privs = &unescape($group_privs);
1.587     albertel 2882: 	    } else {
                   2883: 		($trole,$tend,$tstart)=split(/_/,$role);
                   2884: 	    }
1.743     albertel 2885: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   2886: 					 $username);
                   2887: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  2888:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   2889:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      2890:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 2891: 		my $spec=$trole.'.'.$area;
                   2892: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   2893: 		if ($trole =~ /^cr\//) {
1.567     raeburn  2894:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  2895:                 } elsif ($trole eq 'gr') {
                   2896:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 2897: 		} else {
1.567     raeburn  2898:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 2899: 		}
1.12      www      2900:             }
1.662     raeburn  2901:           }
1.191     harris41 2902:         }
1.743     albertel 2903:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   2904:         $userroles{'user.adv'}    = $adv;
                   2905: 	$userroles{'user.author'} = $author;
1.620     albertel 2906:         $env{'user.adv'}=$adv;
1.11      www      2907:     }
1.743     albertel 2908:     return \%userroles;  
1.11      www      2909: }
                   2910: 
1.567     raeburn  2911: sub set_arearole {
                   2912:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   2913: # log the associated role with the area
                   2914:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 2915:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  2916: }
                   2917: 
                   2918: sub custom_roleprivs {
                   2919:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   2920:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   2921:     my $homsvr=homeserver($rauthor,$rdomain);
                   2922:     if ($hostname{$homsvr} ne '') {
                   2923:         my ($rdummy,$roledef)=
                   2924:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   2925:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   2926:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   2927:             if (defined($syspriv)) {
                   2928:                 $$allroles{'cm./'}.=':'.$syspriv;
                   2929:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   2930:             }
                   2931:             if ($tdomain ne '') {
                   2932:                 if (defined($dompriv)) {
                   2933:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   2934:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   2935:                 }
                   2936:                 if (($trest ne '') && (defined($coursepriv))) {
                   2937:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   2938:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   2939:                 }
                   2940:             }
                   2941:         }
                   2942:     }
                   2943: }
                   2944: 
1.678     raeburn  2945: sub group_roleprivs {
                   2946:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   2947:     my $access = 1;
                   2948:     my $now = time;
                   2949:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   2950:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   2951:     if ($access) {
1.811     albertel 2952:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  2953:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   2954:     }
                   2955: }
1.567     raeburn  2956: 
                   2957: sub standard_roleprivs {
                   2958:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   2959:     if (defined($pr{$trole.':s'})) {
                   2960:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   2961:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   2962:     }
                   2963:     if ($tdomain ne '') {
                   2964:         if (defined($pr{$trole.':d'})) {
                   2965:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   2966:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   2967:         }
                   2968:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   2969:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   2970:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   2971:         }
                   2972:     }
                   2973: }
                   2974: 
                   2975: sub set_userprivs {
1.678     raeburn  2976:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  2977:     my $author=0;
                   2978:     my $adv=0;
1.678     raeburn  2979:     my %grouproles = ();
                   2980:     if (keys(%{$allgroups}) > 0) {
                   2981:         foreach my $role (keys %{$allroles}) {
1.681     raeburn  2982:             my ($trole,$area,$sec,$extendedarea);
1.811     albertel 2983:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)-) {
1.678     raeburn  2984:                 $trole = $1;
                   2985:                 $area = $2;
1.681     raeburn  2986:                 $sec = $3;
                   2987:                 $extendedarea = $area.$sec;
                   2988:                 if (exists($$allgroups{$area})) {
                   2989:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   2990:                         my $spec = $trole.'.'.$extendedarea;
                   2991:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   2992:                                                 $$allgroups{$area}{$group};
1.678     raeburn  2993:                     }
                   2994:                 }
                   2995:             }
                   2996:         }
                   2997:     }
1.800     albertel 2998:     foreach my $group (keys(%grouproles)) {
                   2999:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  3000:     }
1.800     albertel 3001:     foreach my $role (keys(%{$allroles})) {
                   3002:         my %thesepriv;
                   3003:         if (($role=~/^au/) || ($role=~/^ca/)) { $author=1; }
                   3004:         foreach my $item (split(/:/,$$allroles{$role})) {
                   3005:             if ($item ne '') {
                   3006:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  3007:                 if ($restrictions eq '') {
                   3008:                     $thesepriv{$privilege}='F';
                   3009:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   3010:                     $thesepriv{$privilege}.=$restrictions;
                   3011:                 }
                   3012:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   3013:             }
                   3014:         }
                   3015:         my $thesestr='';
1.800     albertel 3016:         foreach my $priv (keys(%thesepriv)) {
                   3017: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   3018: 	}
                   3019:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  3020:     }
                   3021:     return ($author,$adv);
                   3022: }
                   3023: 
1.12      www      3024: # --------------------------------------------------------------- get interface
                   3025: 
                   3026: sub get {
1.131     albertel 3027:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3028:    my $items='';
1.800     albertel 3029:    foreach my $item (@$storearr) {
                   3030:        $items.=&escape($item).'&';
1.191     harris41 3031:    }
1.12      www      3032:    $items=~s/\&$//;
1.620     albertel 3033:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3034:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 3035:    my $uhome=&homeserver($uname,$udomain);
                   3036: 
1.133     albertel 3037:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3038:    my @pairs=split(/\&/,$rep);
1.273     albertel 3039:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   3040:      return @pairs;
                   3041:    }
1.15      www      3042:    my %returnhash=();
1.42      www      3043:    my $i=0;
1.800     albertel 3044:    foreach my $item (@$storearr) {
                   3045:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3046:       $i++;
1.191     harris41 3047:    }
1.15      www      3048:    return %returnhash;
1.27      www      3049: }
                   3050: 
                   3051: # --------------------------------------------------------------- del interface
                   3052: 
                   3053: sub del {
1.133     albertel 3054:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      3055:    my $items='';
1.800     albertel 3056:    foreach my $item (@$storearr) {
                   3057:        $items.=&escape($item).'&';
1.191     harris41 3058:    }
1.27      www      3059:    $items=~s/\&$//;
1.620     albertel 3060:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3061:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3062:    my $uhome=&homeserver($uname,$udomain);
                   3063: 
                   3064:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3065: }
                   3066: 
                   3067: # -------------------------------------------------------------- dump interface
                   3068: 
                   3069: sub dump {
1.755     albertel 3070:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   3071:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3072:     if (!$uname) { $uname=$env{'user.name'}; }
                   3073:     my $uhome=&homeserver($uname,$udomain);
                   3074:     if ($regexp) {
                   3075: 	$regexp=&escape($regexp);
                   3076:     } else {
                   3077: 	$regexp='.';
                   3078:     }
                   3079:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3080:     my @pairs=split(/\&/,$rep);
                   3081:     my %returnhash=();
                   3082:     foreach my $item (@pairs) {
                   3083: 	my ($key,$value)=split(/=/,$item,2);
                   3084: 	$key = &unescape($key);
                   3085: 	next if ($key =~ /^error: 2 /);
                   3086: 	$returnhash{$key}=&thaw_unescape($value);
                   3087:     }
                   3088:     return %returnhash;
1.407     www      3089: }
                   3090: 
1.717     albertel 3091: # --------------------------------------------------------- dumpstore interface
                   3092: 
                   3093: sub dumpstore {
                   3094:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 3095:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3096:    if (!$uname) { $uname=$env{'user.name'}; }
                   3097:    my $uhome=&homeserver($uname,$udomain);
                   3098:    if ($regexp) {
                   3099:        $regexp=&escape($regexp);
                   3100:    } else {
                   3101:        $regexp='.';
                   3102:    }
                   3103:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3104:    my @pairs=split(/\&/,$rep);
                   3105:    my %returnhash=();
                   3106:    foreach my $item (@pairs) {
                   3107:        my ($key,$value)=split(/=/,$item,2);
                   3108:        next if ($key =~ /^error: 2 /);
                   3109:        $returnhash{$key}=&thaw_unescape($value);
                   3110:    }
                   3111:    return %returnhash;
1.717     albertel 3112: }
                   3113: 
1.407     www      3114: # -------------------------------------------------------------- keys interface
                   3115: 
                   3116: sub getkeys {
                   3117:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 3118:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3119:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      3120:    my $uhome=&homeserver($uname,$udomain);
                   3121:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   3122:    my @keyarray=();
1.800     albertel 3123:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  3124:       next if ($key =~ /^error: 2 /);
1.800     albertel 3125:       push(@keyarray,&unescape($key));
1.407     www      3126:    }
                   3127:    return @keyarray;
1.318     matthew  3128: }
                   3129: 
1.319     matthew  3130: # --------------------------------------------------------------- currentdump
                   3131: sub currentdump {
1.328     matthew  3132:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 3133:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   3134:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   3135:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  3136:    my $uhome = &homeserver($sname,$sdom);
                   3137:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  3138:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  3139:    #
1.318     matthew  3140:    my %returnhash=();
1.319     matthew  3141:    #
                   3142:    if ($rep eq "unknown_cmd") { 
                   3143:        # an old lond will not know currentdump
                   3144:        # Do a dump and make it look like a currentdump
1.822     albertel 3145:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  3146:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   3147:        my %hash = @tmp;
                   3148:        @tmp=();
1.424     matthew  3149:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  3150:    } else {
                   3151:        my @pairs=split(/\&/,$rep);
1.800     albertel 3152:        foreach my $pair (@pairs) {
                   3153:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  3154:            my ($symb,$param) = split(/:/,$key);
                   3155:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 3156:                                                         &thaw_unescape($value);
1.319     matthew  3157:        }
1.191     harris41 3158:    }
1.12      www      3159:    return %returnhash;
1.424     matthew  3160: }
                   3161: 
                   3162: sub convert_dump_to_currentdump{
                   3163:     my %hash = %{shift()};
                   3164:     my %returnhash;
                   3165:     # Code ripped from lond, essentially.  The only difference
                   3166:     # here is the unescaping done by lonnet::dump().  Conceivably
                   3167:     # we might run in to problems with parameter names =~ /^v\./
                   3168:     while (my ($key,$value) = each(%hash)) {
                   3169:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 3170: 	$symb  = &unescape($symb);
                   3171: 	$param = &unescape($param);
1.424     matthew  3172:         next if ($v eq 'version' || $symb eq 'keys');
                   3173:         next if (exists($returnhash{$symb}) &&
                   3174:                  exists($returnhash{$symb}->{$param}) &&
                   3175:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   3176:         $returnhash{$symb}->{$param}=$value;
                   3177:         $returnhash{$symb}->{'v.'.$param}=$v;
                   3178:     }
                   3179:     #
                   3180:     # Remove all of the keys in the hashes which keep track of
                   3181:     # the version of the parameter.
                   3182:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   3183:         # use a foreach because we are going to delete from the hash.
                   3184:         foreach my $key (keys(%$param_hash)) {
                   3185:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   3186:         }
                   3187:     }
                   3188:     return \%returnhash;
1.12      www      3189: }
                   3190: 
1.627     albertel 3191: # ------------------------------------------------------ critical inc interface
                   3192: 
                   3193: sub cinc {
                   3194:     return &inc(@_,'critical');
                   3195: }
                   3196: 
1.449     matthew  3197: # --------------------------------------------------------------- inc interface
                   3198: 
                   3199: sub inc {
1.627     albertel 3200:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 3201:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3202:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  3203:     my $uhome=&homeserver($uname,$udomain);
                   3204:     my $items='';
                   3205:     if (! ref($store)) {
                   3206:         # got a single value, so use that instead
                   3207:         $items = &escape($store).'=&';
                   3208:     } elsif (ref($store) eq 'SCALAR') {
                   3209:         $items = &escape($$store).'=&';        
                   3210:     } elsif (ref($store) eq 'ARRAY') {
                   3211:         $items = join('=&',map {&escape($_);} @{$store});
                   3212:     } elsif (ref($store) eq 'HASH') {
                   3213:         while (my($key,$value) = each(%{$store})) {
                   3214:             $items.= &escape($key).'='.&escape($value).'&';
                   3215:         }
                   3216:     }
                   3217:     $items=~s/\&$//;
1.627     albertel 3218:     if ($critical) {
                   3219: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3220:     } else {
                   3221: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3222:     }
1.449     matthew  3223: }
                   3224: 
1.12      www      3225: # --------------------------------------------------------------- put interface
                   3226: 
                   3227: sub put {
1.134     albertel 3228:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3229:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3230:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3231:    my $uhome=&homeserver($uname,$udomain);
1.12      www      3232:    my $items='';
1.800     albertel 3233:    foreach my $item (keys(%$storehash)) {
                   3234:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3235:    }
1.12      www      3236:    $items=~s/\&$//;
1.134     albertel 3237:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      3238: }
                   3239: 
1.631     albertel 3240: # ------------------------------------------------------------ newput interface
                   3241: 
                   3242: sub newput {
                   3243:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   3244:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3245:    if (!$uname) { $uname=$env{'user.name'}; }
                   3246:    my $uhome=&homeserver($uname,$udomain);
                   3247:    my $items='';
                   3248:    foreach my $key (keys(%$storehash)) {
                   3249:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   3250:    }
                   3251:    $items=~s/\&$//;
                   3252:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   3253: }
                   3254: 
                   3255: # ---------------------------------------------------------  putstore interface
                   3256: 
1.524     raeburn  3257: sub putstore {
1.715     albertel 3258:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 3259:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3260:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  3261:    my $uhome=&homeserver($uname,$udomain);
                   3262:    my $items='';
1.715     albertel 3263:    foreach my $key (keys(%$storehash)) {
                   3264:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  3265:    }
1.715     albertel 3266:    $items=~s/\&$//;
1.716     albertel 3267:    my $esc_symb=&escape($symb);
                   3268:    my $esc_v=&escape($version);
1.715     albertel 3269:    my $reply =
1.716     albertel 3270:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 3271: 	      $uhome);
                   3272:    if ($reply eq 'unknown_cmd') {
1.716     albertel 3273:        # gfall back to way things use to be done
1.715     albertel 3274:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   3275: 			    $uname);
1.524     raeburn  3276:    }
1.715     albertel 3277:    return $reply;
                   3278: }
                   3279: 
                   3280: sub old_putstore {
1.716     albertel 3281:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   3282:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3283:     if (!$uname) { $uname=$env{'user.name'}; }
                   3284:     my $uhome=&homeserver($uname,$udomain);
                   3285:     my %newstorehash;
1.800     albertel 3286:     foreach my $item (keys(%$storehash)) {
                   3287: 	my $key = $version.':'.&escape($symb).':'.$item;
                   3288: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 3289:     }
                   3290:     my $items='';
                   3291:     my %allitems = ();
1.800     albertel 3292:     foreach my $item (keys(%newstorehash)) {
                   3293: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 3294: 	    my $key = $1.':keys:'.$2;
                   3295: 	    $allitems{$key} .= $3.':';
                   3296: 	}
1.800     albertel 3297: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 3298:     }
1.800     albertel 3299:     foreach my $item (keys(%allitems)) {
                   3300: 	$allitems{$item} =~ s/\:$//;
                   3301: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 3302:     }
                   3303:     $items=~s/\&$//;
                   3304:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  3305: }
                   3306: 
1.47      www      3307: # ------------------------------------------------------ critical put interface
                   3308: 
                   3309: sub cput {
1.134     albertel 3310:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3311:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3312:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3313:    my $uhome=&homeserver($uname,$udomain);
1.47      www      3314:    my $items='';
1.800     albertel 3315:    foreach my $item (keys(%$storehash)) {
                   3316:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3317:    }
1.47      www      3318:    $items=~s/\&$//;
1.134     albertel 3319:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3320: }
                   3321: 
                   3322: # -------------------------------------------------------------- eget interface
                   3323: 
                   3324: sub eget {
1.133     albertel 3325:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3326:    my $items='';
1.800     albertel 3327:    foreach my $item (@$storearr) {
                   3328:        $items.=&escape($item).'&';
1.191     harris41 3329:    }
1.12      www      3330:    $items=~s/\&$//;
1.620     albertel 3331:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3332:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3333:    my $uhome=&homeserver($uname,$udomain);
                   3334:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3335:    my @pairs=split(/\&/,$rep);
                   3336:    my %returnhash=();
1.42      www      3337:    my $i=0;
1.800     albertel 3338:    foreach my $item (@$storearr) {
                   3339:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3340:       $i++;
1.191     harris41 3341:    }
1.12      www      3342:    return %returnhash;
                   3343: }
                   3344: 
1.667     albertel 3345: # ------------------------------------------------------------ tmpput interface
                   3346: sub tmpput {
1.802     raeburn  3347:     my ($storehash,$server,$context)=@_;
1.667     albertel 3348:     my $items='';
1.800     albertel 3349:     foreach my $item (keys(%$storehash)) {
                   3350: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 3351:     }
                   3352:     $items=~s/\&$//;
1.802     raeburn  3353:     if (defined($context)) {
                   3354:         $items .= ':'.&escape($context);
                   3355:     }
1.667     albertel 3356:     return &reply("tmpput:$items",$server);
                   3357: }
                   3358: 
                   3359: # ------------------------------------------------------------ tmpget interface
                   3360: sub tmpget {
1.688     albertel 3361:     my ($token,$server)=@_;
                   3362:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3363:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 3364:     my %returnhash;
                   3365:     foreach my $item (split(/\&/,$rep)) {
                   3366: 	my ($key,$value)=split(/=/,$item);
                   3367: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   3368:     }
                   3369:     return %returnhash;
                   3370: }
                   3371: 
1.688     albertel 3372: # ------------------------------------------------------------ tmpget interface
                   3373: sub tmpdel {
                   3374:     my ($token,$server)=@_;
                   3375:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3376:     return &reply("tmpdel:$token",$server);
                   3377: }
                   3378: 
1.765     albertel 3379: # -------------------------------------------------- portfolio access checking
                   3380: 
                   3381: sub portfolio_access {
1.766     albertel 3382:     my ($requrl) = @_;
1.765     albertel 3383:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   3384:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  3385:     if ($result) {
                   3386:         my %setters;
                   3387:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3388:             my ($startblock,$endblock) =
                   3389:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   3390:             if ($startblock && $endblock) {
                   3391:                 return 'B';
                   3392:             }
                   3393:         } else {
                   3394:             my ($startblock,$endblock) =
                   3395:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   3396:             if ($startblock && $endblock) {
                   3397:                 return 'B';
                   3398:             }
                   3399:         }
                   3400:     }
1.765     albertel 3401:     if ($result eq 'ok') {
1.766     albertel 3402:        return 'F';
1.765     albertel 3403:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 3404:        return 'A';
1.765     albertel 3405:     }
1.766     albertel 3406:     return '';
1.765     albertel 3407: }
                   3408: 
                   3409: sub get_portfolio_access {
1.767     albertel 3410:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   3411: 
                   3412:     if (!ref($access_hash)) {
                   3413: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   3414: 	my %access_controls = &get_access_controls($current_perms,$group,
                   3415: 						   $file_name);
                   3416: 	$access_hash = $access_controls{$file_name};
                   3417:     }
                   3418: 
1.765     albertel 3419:     my ($public,$guest,@domains,@users,@courses,@groups);
                   3420:     my $now = time;
                   3421:     if (ref($access_hash) eq 'HASH') {
                   3422:         foreach my $key (keys(%{$access_hash})) {
                   3423:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   3424:             if ($start > $now) {
                   3425:                 next;
                   3426:             }
                   3427:             if ($end && $end<$now) {
                   3428:                 next;
                   3429:             }
                   3430:             if ($scope eq 'public') {
                   3431:                 $public = $key;
                   3432:                 last;
                   3433:             } elsif ($scope eq 'guest') {
                   3434:                 $guest = $key;
                   3435:             } elsif ($scope eq 'domains') {
                   3436:                 push(@domains,$key);
                   3437:             } elsif ($scope eq 'users') {
                   3438:                 push(@users,$key);
                   3439:             } elsif ($scope eq 'course') {
                   3440:                 push(@courses,$key);
                   3441:             } elsif ($scope eq 'group') {
                   3442:                 push(@groups,$key);
                   3443:             }
                   3444:         }
                   3445:         if ($public) {
                   3446:             return 'ok';
                   3447:         }
                   3448:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3449:             if ($guest) {
                   3450:                 return $guest;
                   3451:             }
                   3452:         } else {
                   3453:             if (@domains > 0) {
                   3454:                 foreach my $domkey (@domains) {
                   3455:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   3456:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   3457:                             return 'ok';
                   3458:                         }
                   3459:                     }
                   3460:                 }
                   3461:             }
                   3462:             if (@users > 0) {
                   3463:                 foreach my $userkey (@users) {
1.824.2.4! albertel 3464:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
        !          3465:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
        !          3466:                             if (ref($item) eq 'HASH') {
        !          3467:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
        !          3468:                                     ($item->{'udom'} eq $env{'user.domain'})) {
        !          3469:                                     return 'ok';
        !          3470:                                 }
        !          3471:                             }
        !          3472:                         }
        !          3473:                     } 
1.765     albertel 3474:                 }
                   3475:             }
                   3476:             my %roleshash;
                   3477:             my @courses_and_groups = @courses;
                   3478:             push(@courses_and_groups,@groups); 
                   3479:             if (@courses_and_groups > 0) {
                   3480:                 my (%allgroups,%allroles); 
                   3481:                 my ($start,$end,$role,$sec,$group);
                   3482:                 foreach my $envkey (%env) {
1.811     albertel 3483:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 3484:                         my $cid = $2.'_'.$3; 
                   3485:                         if ($1 eq 'gr') {
                   3486:                             $group = $4;
                   3487:                             $allgroups{$cid}{$group} = $env{$envkey};
                   3488:                         } else {
                   3489:                             if ($4 eq '') {
                   3490:                                 $sec = 'none';
                   3491:                             } else {
                   3492:                                 $sec = $4;
                   3493:                             }
                   3494:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3495:                         }
1.811     albertel 3496:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 3497:                         my $cid = $2.'_'.$3;
                   3498:                         if ($4 eq '') {
                   3499:                             $sec = 'none';
                   3500:                         } else {
                   3501:                             $sec = $4;
                   3502:                         }
                   3503:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3504:                     }
                   3505:                 }
                   3506:                 if (keys(%allroles) == 0) {
                   3507:                     return;
                   3508:                 }
                   3509:                 foreach my $key (@courses_and_groups) {
                   3510:                     my %content = %{$$access_hash{$key}};
                   3511:                     my $cnum = $content{'number'};
                   3512:                     my $cdom = $content{'domain'};
                   3513:                     my $cid = $cdom.'_'.$cnum;
                   3514:                     if (!exists($allroles{$cid})) {
                   3515:                         next;
                   3516:                     }    
                   3517:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   3518:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   3519:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   3520:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   3521:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   3522:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   3523:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   3524:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   3525:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   3526:                                         if (grep/^all$/,@sections) {
                   3527:                                             return 'ok';
                   3528:                                         } else {
                   3529:                                             if (grep/^$sec$/,@sections) {
                   3530:                                                 return 'ok';
                   3531:                                             }
                   3532:                                         }
                   3533:                                     }
                   3534:                                 }
                   3535:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   3536:                                     if (grep/^none$/,@groups) {
                   3537:                                         return 'ok';
                   3538:                                     }
                   3539:                                 } else {
                   3540:                                     if (grep/^all$/,@groups) {
                   3541:                                         return 'ok';
                   3542:                                     } 
                   3543:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   3544:                                         if (grep/^$group$/,@groups) {
                   3545:                                             return 'ok';
                   3546:                                         }
                   3547:                                     }
                   3548:                                 } 
                   3549:                             }
                   3550:                         }
                   3551:                     }
                   3552:                 }
                   3553:             }
                   3554:             if ($guest) {
                   3555:                 return $guest;
                   3556:             }
                   3557:         }
                   3558:     }
                   3559:     return;
                   3560: }
                   3561: 
                   3562: sub course_group_datechecker {
                   3563:     my ($dates,$now,$status) = @_;
                   3564:     my ($start,$end) = split(/\./,$dates);
                   3565:     if (!$start && !$end) {
                   3566:         return 'ok';
                   3567:     }
                   3568:     if (grep/^active$/,@{$status}) {
                   3569:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   3570:             return 'ok';
                   3571:         }
                   3572:     }
                   3573:     if (grep/^previous$/,@{$status}) {
                   3574:         if ($end > $now ) {
                   3575:             return 'ok';
                   3576:         }
                   3577:     }
                   3578:     if (grep/^future$/,@{$status}) {
                   3579:         if ($start > $now) {
                   3580:             return 'ok';
                   3581:         }
                   3582:     }
                   3583:     return; 
                   3584: }
                   3585: 
                   3586: sub parse_portfolio_url {
                   3587:     my ($url) = @_;
                   3588: 
                   3589:     my ($type,$udom,$unum,$group,$file_name);
                   3590:     
1.823     albertel 3591:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 3592: 	$type = 1;
                   3593:         $udom = $1;
                   3594:         $unum = $2;
                   3595:         $file_name = $3;
1.823     albertel 3596:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 3597: 	$type = 2;
                   3598:         $udom = $1;
                   3599:         $unum = $2;
                   3600:         $group = $3;
                   3601:         $file_name = $3.'/'.$4;
                   3602:     }
                   3603:     if (wantarray) {
                   3604: 	return ($type,$udom,$unum,$file_name,$group);
                   3605:     }
                   3606:     return $type;
                   3607: }
                   3608: 
                   3609: sub is_portfolio_url {
                   3610:     my ($url) = @_;
                   3611:     return scalar(&parse_portfolio_url($url));
                   3612: }
                   3613: 
1.798     raeburn  3614: sub is_portfolio_file {
                   3615:     my ($file) = @_;
1.820     raeburn  3616:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  3617:         return 1;
                   3618:     }
                   3619:     return;
                   3620: }
                   3621: 
                   3622: 
1.341     www      3623: # ---------------------------------------------- Custom access rule evaluation
                   3624: 
                   3625: sub customaccess {
                   3626:     my ($priv,$uri)=@_;
1.807     albertel 3627:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      3628:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 3629:     $udom = &LONCAPA::clean_domain($udom);
                   3630:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      3631:     my $access=0;
1.800     albertel 3632:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
                   3633: 	my ($effect,$realm,$role)=split(/\:/,$right);
1.343     www      3634:         if ($role) {
                   3635: 	   if ($role ne $urole) { next; }
                   3636:         }
1.800     albertel 3637:         foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   3638:             my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
1.343     www      3639:             if ($tdom) {
                   3640: 		if ($tdom ne $udom) { next; }
                   3641:             }
                   3642:             if ($tcrs) {
                   3643: 		if ($tcrs ne $ucrs) { next; }
                   3644:             }
                   3645:             if ($tsec) {
                   3646: 		if ($tsec ne $usec) { next; }
                   3647:             }
                   3648:             $access=($effect eq 'allow');
                   3649:             last;
1.342     www      3650:         }
1.402     bowersj2 3651: 	if ($realm eq '' && $role eq '') {
                   3652:             $access=($effect eq 'allow');
                   3653: 	}
1.341     www      3654:     }
                   3655:     return $access;
                   3656: }
                   3657: 
1.103     harris41 3658: # ------------------------------------------------- Check for a user privilege
1.12      www      3659: 
                   3660: sub allowed {
1.810     raeburn  3661:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 3662:     my $ver_orguri=$uri;
1.439     www      3663:     $uri=&deversion($uri);
1.152     www      3664:     my $orguri=$uri;
1.52      www      3665:     $uri=&declutter($uri);
1.809     raeburn  3666: 
1.810     raeburn  3667:     if ($priv eq 'evb') {
                   3668: # Evade communication block restrictions for specified role in a course
                   3669:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   3670:             return $1;
                   3671:         } else {
                   3672:             return;
                   3673:         }
                   3674:     }
                   3675: 
1.620     albertel 3676:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      3677: # Free bre access to adm and meta resources
1.775     albertel 3678:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 3679: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   3680: 	&& ($priv eq 'bre')) {
1.14      www      3681: 	return 'F';
1.159     www      3682:     }
                   3683: 
1.545     banghart 3684: # Free bre access to user's own portfolio contents
1.714     raeburn  3685:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  3686:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  3687: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  3688:         my %setters;
                   3689:         my ($startblock,$endblock) = 
                   3690:             &Apache::loncommon::blockcheck(\%setters,'port');
                   3691:         if ($startblock && $endblock) {
                   3692:             return 'B';
                   3693:         } else {
                   3694:             return 'F';
                   3695:         }
1.545     banghart 3696:     }
                   3697: 
1.762     raeburn  3698: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  3699:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   3700:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   3701:         if (exists($env{'request.course.id'})) {
                   3702:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3703:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3704:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   3705:                 my $courseprivid=$env{'request.course.id'};
                   3706:                 $courseprivid=~s/\_/\//;
                   3707:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   3708:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   3709:                     return $1; 
1.762     raeburn  3710:                 } else {
                   3711:                     if ($env{'request.course.sec'}) {
                   3712:                         $courseprivid.='/'.$env{'request.course.sec'};
                   3713:                     }
                   3714:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   3715:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   3716:                         return $2;
                   3717:                     }
1.714     raeburn  3718:                 }
                   3719:             }
                   3720:         }
                   3721:     }
                   3722: 
1.159     www      3723: # Free bre to public access
                   3724: 
                   3725:     if ($priv eq 'bre') {
1.238     www      3726:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 3727: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      3728:            return 'F'; 
                   3729:         }
1.238     www      3730:         if ($copyright eq 'priv') {
                   3731:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3732: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      3733: 		return '';
                   3734:             }
                   3735:         }
                   3736:         if ($copyright eq 'domain') {
                   3737:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3738: 	    unless (($env{'user.domain'} eq $1) ||
                   3739:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      3740: 		return '';
                   3741:             }
1.262     matthew  3742:         }
1.620     albertel 3743:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  3744:             # Library role, so allow browsing of resources in this domain.
                   3745:             return 'F';
1.238     www      3746:         }
1.341     www      3747:         if ($copyright eq 'custom') {
                   3748: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   3749:         }
1.14      www      3750:     }
1.264     matthew  3751:     # Domain coordinator is trying to create a course
1.620     albertel 3752:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  3753:         # uri is the requested domain in this case.
                   3754:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  3755:         # a role of dc for the domain in question.
1.620     albertel 3756:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  3757:     }
1.29      www      3758: 
1.52      www      3759:     my $thisallowed='';
                   3760:     my $statecond=0;
                   3761:     my $courseprivid='';
                   3762: 
                   3763: # Course
                   3764: 
1.620     albertel 3765:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3766:        $thisallowed.=$1;
                   3767:     }
1.29      www      3768: 
1.52      www      3769: # Domain
                   3770: 
1.620     albertel 3771:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 3772:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3773:        $thisallowed.=$1;
                   3774:     }
1.52      www      3775: 
                   3776: # Course: uri itself is a course
1.66      www      3777:     my $courseuri=$uri;
                   3778:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      3779:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      3780: 
1.620     albertel 3781:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 3782:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3783:        $thisallowed.=$1;
                   3784:     }
1.29      www      3785: 
1.665     albertel 3786: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 3787: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 3788:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 3789: 	$thisallowed='';
1.671     raeburn  3790:         my ($match)=&is_on_map($uri);
                   3791:         if ($match) {
                   3792:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   3793:                   =~/\Q$priv\E\&([^\:]*)/) {
                   3794:                 $thisallowed.=$1;
                   3795:             }
                   3796:         } else {
1.705     albertel 3797:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  3798:             if ($refuri) {
                   3799:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  3800:                     $thisallowed='F';
1.671     raeburn  3801:                 } else {
                   3802:                     $refuri=&declutter($refuri);
                   3803:                     my ($match) = &is_on_map($refuri);
                   3804:                     if ($match) {
                   3805:                         $thisallowed='F';
                   3806:                     }
1.669     raeburn  3807:                 }
1.671     raeburn  3808:             }
                   3809:         }
1.314     www      3810:     }
1.492     albertel 3811: 
1.766     albertel 3812:     if ($priv eq 'bre'
                   3813: 	&& $thisallowed ne 'F' 
                   3814: 	&& $thisallowed ne '2'
                   3815: 	&& &is_portfolio_url($uri)) {
                   3816: 	$thisallowed = &portfolio_access($uri);
                   3817:     }
                   3818:     
1.52      www      3819: # Full access at system, domain or course-wide level? Exit.
1.29      www      3820: 
                   3821:     if ($thisallowed=~/F/) {
                   3822: 	return 'F';
                   3823:     }
                   3824: 
1.52      www      3825: # If this is generating or modifying users, exit with special codes
1.29      www      3826: 
1.643     www      3827:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   3828: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 3829: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      3830: # no author name given, so this just checks on the general right to make a co-author in this domain
                   3831: 	    unless ($auname) { return $thisallowed; }
                   3832: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 3833: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   3834: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   3835: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   3836: 	}
1.52      www      3837: 	return $thisallowed;
                   3838:     }
                   3839: #
1.103     harris41 3840: # Gathered so far: system, domain and course wide privileges
1.52      www      3841: #
                   3842: # Course: See if uri or referer is an individual resource that is part of 
                   3843: # the course
                   3844: 
1.620     albertel 3845:     if ($env{'request.course.id'}) {
1.232     www      3846: 
1.620     albertel 3847:        $courseprivid=$env{'request.course.id'};
                   3848:        if ($env{'request.course.sec'}) {
                   3849:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      3850:        }
                   3851:        $courseprivid=~s/\_/\//;
                   3852:        my $checkreferer=1;
1.232     www      3853:        my ($match,$cond)=&is_on_map($uri);
                   3854:        if ($match) {
                   3855:            $statecond=$cond;
1.620     albertel 3856:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 3857:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3858:                $thisallowed.=$1;
                   3859:                $checkreferer=0;
                   3860:            }
1.29      www      3861:        }
1.83      www      3862:        
1.148     www      3863:        if ($checkreferer) {
1.620     albertel 3864: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      3865:             unless ($refuri) {
1.800     albertel 3866:                 foreach my $key (keys(%env)) {
                   3867: 		    if ($key=~/^httpref\..*\*/) {
                   3868: 			my $pattern=$key;
1.156     www      3869:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      3870:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   3871:                         $pattern=~s/\//\\\//g;
1.152     www      3872:                         if ($orguri=~/$pattern/) {
1.800     albertel 3873: 			    $refuri=$env{$key};
1.148     www      3874:                         }
                   3875:                     }
1.191     harris41 3876:                 }
1.148     www      3877:             }
1.232     www      3878: 
1.148     www      3879:          if ($refuri) { 
1.152     www      3880: 	  $refuri=&declutter($refuri);
1.232     www      3881:           my ($match,$cond)=&is_on_map($refuri);
                   3882:             if ($match) {
                   3883:               my $refstatecond=$cond;
1.620     albertel 3884:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 3885:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3886:                   $thisallowed.=$1;
1.53      www      3887:                   $uri=$refuri;
                   3888:                   $statecond=$refstatecond;
1.52      www      3889:               }
                   3890:           }
1.148     www      3891:         }
1.29      www      3892:        }
1.52      www      3893:    }
1.29      www      3894: 
1.52      www      3895: #
1.103     harris41 3896: # Gathered now: all privileges that could apply, and condition number
1.52      www      3897: # 
                   3898: #
                   3899: # Full or no access?
                   3900: #
1.29      www      3901: 
1.52      www      3902:     if ($thisallowed=~/F/) {
                   3903: 	return 'F';
                   3904:     }
1.29      www      3905: 
1.52      www      3906:     unless ($thisallowed) {
                   3907:         return '';
                   3908:     }
1.29      www      3909: 
1.52      www      3910: # Restrictions exist, deal with them
                   3911: #
                   3912: #   C:according to course preferences
                   3913: #   R:according to resource settings
                   3914: #   L:unless locked
                   3915: #   X:according to user session state
                   3916: #
                   3917: 
                   3918: # Possibly locked functionality, check all courses
1.54      www      3919: # Locks might take effect only after 10 minutes cache expiration for other
                   3920: # courses, and 2 minutes for current course
1.52      www      3921: 
                   3922:     my $envkey;
                   3923:     if ($thisallowed=~/L/) {
1.620     albertel 3924:         foreach $envkey (keys %env) {
1.54      www      3925:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   3926:                my $courseid=$2;
                   3927:                my $roleid=$1.'.'.$2;
1.92      www      3928:                $courseid=~s/^\///;
1.54      www      3929:                my $expiretime=600;
1.620     albertel 3930:                if ($env{'request.role'} eq $roleid) {
1.54      www      3931: 		  $expiretime=120;
                   3932:                }
                   3933: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   3934:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 3935:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 3936: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      3937:                }
1.620     albertel 3938:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   3939:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   3940: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   3941:                        &log($env{'user.domain'},$env{'user.name'},
                   3942:                             $env{'user.home'},
1.57      www      3943:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      3944:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 3945:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      3946: 		       return '';
                   3947:                    }
                   3948:                }
1.620     albertel 3949:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   3950:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   3951: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   3952:                        &log($env{'user.domain'},$env{'user.name'},
                   3953:                             $env{'user.home'},
1.57      www      3954:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      3955:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 3956:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      3957: 		       return '';
                   3958:                    }
                   3959:                }
                   3960: 	   }
1.29      www      3961:        }
1.52      www      3962:     }
                   3963:    
                   3964: #
                   3965: # Rest of the restrictions depend on selected course
                   3966: #
                   3967: 
1.620     albertel 3968:     unless ($env{'request.course.id'}) {
1.766     albertel 3969: 	if ($thisallowed eq 'A') {
                   3970: 	    return 'A';
1.814     raeburn  3971:         } elsif ($thisallowed eq 'B') {
                   3972:             return 'B';
1.766     albertel 3973: 	} else {
                   3974: 	    return '1';
                   3975: 	}
1.52      www      3976:     }
1.29      www      3977: 
1.52      www      3978: #
                   3979: # Now user is definitely in a course
                   3980: #
1.53      www      3981: 
                   3982: 
                   3983: # Course preferences
                   3984: 
                   3985:    if ($thisallowed=~/C/) {
1.620     albertel 3986:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   3987:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   3988:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 3989: 	   =~/\Q$rolecode\E/) {
1.689     albertel 3990: 	   if ($priv ne 'pch') { 
                   3991: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   3992: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   3993: 			$env{'request.course.id'});
                   3994: 	   }
1.237     www      3995:            return '';
                   3996:        }
                   3997: 
1.620     albertel 3998:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 3999: 	   =~/\Q$unamedom\E/) {
1.689     albertel 4000: 	   if ($priv ne 'pch') { 
                   4001: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   4002: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   4003: 			$env{'request.course.id'});
                   4004: 	   }
1.54      www      4005:            return '';
                   4006:        }
1.53      www      4007:    }
                   4008: 
                   4009: # Resource preferences
                   4010: 
                   4011:    if ($thisallowed=~/R/) {
1.620     albertel 4012:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 4013:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 4014: 	   if ($priv ne 'pch') { 
                   4015: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4016: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   4017: 	   }
                   4018: 	   return '';
1.54      www      4019:        }
1.53      www      4020:    }
1.30      www      4021: 
1.246     www      4022: # Restricted by state or randomout?
1.30      www      4023: 
1.52      www      4024:    if ($thisallowed=~/X/) {
1.620     albertel 4025:       if ($env{'acc.randomout'}) {
1.579     albertel 4026: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 4027:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      4028:             return ''; 
                   4029:          }
1.247     www      4030:       }
                   4031:       if (&condval($statecond)) {
1.52      www      4032: 	 return '2';
                   4033:       } else {
                   4034:          return '';
                   4035:       }
                   4036:    }
1.30      www      4037: 
1.766     albertel 4038:     if ($thisallowed eq 'A') {
                   4039: 	return 'A';
1.814     raeburn  4040:     } elsif ($thisallowed eq 'B') {
                   4041:         return 'B';
1.766     albertel 4042:     }
1.52      www      4043:    return 'F';
1.232     www      4044: }
                   4045: 
1.710     albertel 4046: sub split_uri_for_cond {
                   4047:     my $uri=&deversion(&declutter(shift));
                   4048:     my @uriparts=split(/\//,$uri);
                   4049:     my $filename=pop(@uriparts);
                   4050:     my $pathname=join('/',@uriparts);
                   4051:     return ($pathname,$filename);
                   4052: }
1.232     www      4053: # --------------------------------------------------- Is a resource on the map?
                   4054: 
                   4055: sub is_on_map {
1.710     albertel 4056:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 4057:     #Trying to find the conditional for the file
1.620     albertel 4058:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 4059: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      4060:     if ($match) {
1.289     bowersj2 4061: 	return (1,$1);
                   4062:     } else {
1.434     www      4063: 	return (0,0);
1.289     bowersj2 4064:     }
1.12      www      4065: }
                   4066: 
1.427     www      4067: # --------------------------------------------------------- Get symb from alias
                   4068: 
                   4069: sub get_symb_from_alias {
                   4070:     my $symb=shift;
                   4071:     my ($map,$resid,$url)=&decode_symb($symb);
                   4072: # Already is a symb
                   4073:     if ($url) { return $symb; }
                   4074: # Must be an alias
                   4075:     my $aliassymb='';
                   4076:     my %bighash;
1.620     albertel 4077:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      4078:                             &GDBM_READER(),0640)) {
                   4079:         my $rid=$bighash{'mapalias_'.$symb};
                   4080: 	if ($rid) {
                   4081: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 4082: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   4083: 				    $resid,$bighash{'src_'.$rid});
1.427     www      4084: 	}
                   4085:         untie %bighash;
                   4086:     }
                   4087:     return $aliassymb;
                   4088: }
                   4089: 
1.12      www      4090: # ----------------------------------------------------------------- Define Role
                   4091: 
                   4092: sub definerole {
                   4093:   if (allowed('mcr','/')) {
                   4094:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 4095:     foreach my $role (split(':',$sysrole)) {
                   4096: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4097:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   4098:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   4099: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4100:                return "refused:s:$crole&$cqual"; 
                   4101:             }
                   4102:         }
1.191     harris41 4103:     }
1.800     albertel 4104:     foreach my $role (split(':',$domrole)) {
                   4105: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4106:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   4107:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   4108: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      4109:                return "refused:d:$crole&$cqual"; 
                   4110:             }
                   4111:         }
1.191     harris41 4112:     }
1.800     albertel 4113:     foreach my $role (split(':',$courole)) {
                   4114: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4115:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   4116:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   4117: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4118:                return "refused:c:$crole&$cqual"; 
                   4119:             }
                   4120:         }
1.191     harris41 4121:     }
1.620     albertel 4122:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   4123:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4124: 	        "rolesdef_$rolename=".
                   4125:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 4126:     return reply($command,$env{'user.home'});
1.12      www      4127:   } else {
                   4128:     return 'refused';
                   4129:   }
1.105     harris41 4130: }
                   4131: 
                   4132: # ---------------- Make a metadata query against the network of library servers
                   4133: 
                   4134: sub metadata_query {
1.244     matthew  4135:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 4136:     my %rhash;
1.244     matthew  4137:     my @server_list = (defined($server_array) ? @$server_array
                   4138:                                               : keys(%libserv) );
                   4139:     for my $server (@server_list) {
1.118     harris41 4140: 	unless ($custom or $customshow) {
                   4141: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   4142: 	    $rhash{$server}=$reply;
                   4143: 	}
                   4144: 	else {
                   4145: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   4146: 			     &escape($custom).':'.&escape($customshow),
                   4147: 			     $server);
                   4148: 	    $rhash{$server}=$reply;
                   4149: 	}
1.112     harris41 4150:     }
1.118     harris41 4151:     return \%rhash;
1.240     www      4152: }
                   4153: 
                   4154: # ----------------------------------------- Send log queries and wait for reply
                   4155: 
                   4156: sub log_query {
                   4157:     my ($uname,$udom,$query,%filters)=@_;
                   4158:     my $uhome=&homeserver($uname,$udom);
                   4159:     if ($uhome eq 'no_host') { return 'error: no_host'; }
                   4160:     my $uhost=$hostname{$uhome};
1.800     albertel 4161:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      4162:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   4163:                        $uhome);
1.479     albertel 4164:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      4165:     return get_query_reply($queryid);
                   4166: }
                   4167: 
1.818     raeburn  4168: # -------------------------- Update MySQL table for portfolio file
                   4169: 
                   4170: sub update_portfolio_table {
1.821     raeburn  4171:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.818     raeburn  4172:     my $homeserver = &homeserver($uname,$udom);
                   4173:     my $queryid=
1.821     raeburn  4174:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   4175:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  4176:     my $reply = &get_query_reply($queryid);
                   4177:     return $reply;
                   4178: }
                   4179: 
1.508     raeburn  4180: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  4181: 
                   4182: sub fetch_enrollment_query {
1.511     raeburn  4183:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  4184:     my $homeserver;
1.547     raeburn  4185:     my $maxtries = 1;
1.508     raeburn  4186:     if ($context eq 'automated') {
                   4187:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  4188:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  4189:     } else {
                   4190:         $homeserver = &homeserver($cnum,$dom);
                   4191:     }
1.506     raeburn  4192:     my $host=$hostname{$homeserver};
                   4193:     my $cmd = '';
1.800     albertel 4194:     foreach my $affiliate (keys %{$affiliatesref}) {
                   4195:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  4196:     }
                   4197:     $cmd =~ s/%%$//;
                   4198:     $cmd = &escape($cmd);
                   4199:     my $query = 'fetchenrollment';
1.620     albertel 4200:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  4201:     unless ($queryid=~/^\Q$host\E\_/) { 
                   4202:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   4203:         return 'error: '.$queryid;
                   4204:     }
1.506     raeburn  4205:     my $reply = &get_query_reply($queryid);
1.547     raeburn  4206:     my $tries = 1;
                   4207:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4208:         $reply = &get_query_reply($queryid);
                   4209:         $tries ++;
                   4210:     }
1.526     raeburn  4211:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 4212:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  4213:     } else {
1.515     raeburn  4214:         my @responses = split/:/,$reply;
                   4215:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 4216:             foreach my $line (@responses) {
                   4217:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  4218:                 $$replyref{$key} = $value;
                   4219:             }
                   4220:         } else {
1.506     raeburn  4221:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 4222:             foreach my $line (@responses) {
                   4223:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  4224:                 $$replyref{$key} = $value;
                   4225:                 if ($value > 0) {
1.800     albertel 4226:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   4227:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  4228:                         my $destname = $pathname.'/'.$filename;
                   4229:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  4230:                         if ($xml_classlist =~ /^error/) {
                   4231:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   4232:                         } else {
1.506     raeburn  4233:                             if ( open(FILE,">$destname") ) {
                   4234:                                 print FILE &unescape($xml_classlist);
                   4235:                                 close(FILE);
1.526     raeburn  4236:                             } else {
                   4237:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  4238:                             }
                   4239:                         }
                   4240:                     }
                   4241:                 }
                   4242:             }
                   4243:         }
                   4244:         return 'ok';
                   4245:     }
                   4246:     return 'error';
                   4247: }
                   4248: 
1.242     www      4249: sub get_query_reply {
                   4250:     my $queryid=shift;
1.240     www      4251:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   4252:     my $reply='';
                   4253:     for (1..100) {
                   4254: 	sleep 2;
                   4255:         if (-e $replyfile.'.end') {
1.448     albertel 4256: 	    if (open(my $fh,$replyfile)) {
1.240     www      4257:                $reply.=<$fh>;
1.448     albertel 4258:                close($fh);
1.240     www      4259: 	   } else { return 'error: reply_file_error'; }
1.242     www      4260:            return &unescape($reply);
                   4261: 	}
1.240     www      4262:     }
1.242     www      4263:     return 'timeout:'.$queryid;
1.240     www      4264: }
                   4265: 
                   4266: sub courselog_query {
1.241     www      4267: #
                   4268: # possible filters:
                   4269: # url: url or symb
                   4270: # username
                   4271: # domain
                   4272: # action: view, submit, grade
                   4273: # start: timestamp
                   4274: # end: timestamp
                   4275: #
1.240     www      4276:     my (%filters)=@_;
1.620     albertel 4277:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      4278:     if ($filters{'url'}) {
                   4279: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   4280:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   4281:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   4282:     }
1.620     albertel 4283:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4284:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      4285:     return &log_query($cname,$cdom,'courselog',%filters);
                   4286: }
                   4287: 
                   4288: sub userlog_query {
                   4289:     my ($uname,$udom,%filters)=@_;
                   4290:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      4291: }
                   4292: 
1.506     raeburn  4293: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   4294: 
                   4295: sub auto_run {
1.508     raeburn  4296:     my ($cnum,$cdom) = @_;
                   4297:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4298:     my $response = &reply('autorun:'.$cdom,$homeserver);
1.506     raeburn  4299:     return $response;
                   4300: }
1.776     albertel 4301: 
1.506     raeburn  4302: sub auto_get_sections {
1.508     raeburn  4303:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   4304:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  4305:     my @secs = ();
1.511     raeburn  4306:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  4307:     unless ($response eq 'refused') {
                   4308:         @secs = split/:/,$response;
                   4309:     }
                   4310:     return @secs;
                   4311: }
1.776     albertel 4312: 
1.506     raeburn  4313: sub auto_new_course {
1.508     raeburn  4314:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   4315:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  4316:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  4317:     return $response;
                   4318: }
1.776     albertel 4319: 
1.506     raeburn  4320: sub auto_validate_courseID {
1.508     raeburn  4321:     my ($cnum,$cdom,$inst_course_id) = @_;
                   4322:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4323:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  4324:     return $response;
                   4325: }
1.776     albertel 4326: 
1.506     raeburn  4327: sub auto_create_password {
1.508     raeburn  4328:     my ($cnum,$cdom,$authparam) = @_;
                   4329:     my $homeserver = &homeserver($cnum,$cdom); 
1.506     raeburn  4330:     my $create_passwd = 0;
                   4331:     my $authchk = '';
1.511     raeburn  4332:     my $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
1.506     raeburn  4333:     if ($response eq 'refused') {
                   4334:         $authchk = 'refused';
                   4335:     } else {
                   4336:         ($authparam,$create_passwd,$authchk) = split/:/,$response;
                   4337:     }
                   4338:     return ($authparam,$create_passwd,$authchk);
                   4339: }
                   4340: 
1.706     raeburn  4341: sub auto_photo_permission {
                   4342:     my ($cnum,$cdom,$students) = @_;
                   4343:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 4344:     my ($outcome,$perm_reqd,$conditions) = 
                   4345: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 4346:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4347: 	return (undef,undef);
                   4348:     }
1.706     raeburn  4349:     return ($outcome,$perm_reqd,$conditions);
                   4350: }
                   4351: 
                   4352: sub auto_checkphotos {
                   4353:     my ($uname,$udom,$pid) = @_;
                   4354:     my $homeserver = &homeserver($uname,$udom);
                   4355:     my ($result,$resulttype);
                   4356:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 4357: 				   &escape($uname).':'.&escape($pid),
                   4358: 				   $homeserver));
1.709     albertel 4359:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4360: 	return (undef,undef);
                   4361:     }
1.706     raeburn  4362:     if ($outcome) {
                   4363:         ($result,$resulttype) = split(/:/,$outcome);
                   4364:     } 
                   4365:     return ($result,$resulttype);
                   4366: }
                   4367: 
                   4368: sub auto_photochoice {
                   4369:     my ($cnum,$cdom) = @_;
                   4370:     my $homeserver = &homeserver($cnum,$cdom);
                   4371:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 4372: 						       &escape($cdom),
                   4373: 						       $homeserver)));
1.709     albertel 4374:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4375: 	return (undef,undef);
                   4376:     }
1.706     raeburn  4377:     return ($update,$comment);
                   4378: }
                   4379: 
                   4380: sub auto_photoupdate {
                   4381:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   4382:     my $homeserver = &homeserver($cnum,$dom);
                   4383:     my $host=$hostname{$homeserver};
                   4384:     my $cmd = '';
                   4385:     my $maxtries = 1;
1.800     albertel 4386:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   4387:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  4388:     }
                   4389:     $cmd =~ s/%%$//;
                   4390:     $cmd = &escape($cmd);
                   4391:     my $query = 'institutionalphotos';
                   4392:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   4393:     unless ($queryid=~/^\Q$host\E\_/) {
                   4394:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   4395:         return 'error: '.$queryid;
                   4396:     }
                   4397:     my $reply = &get_query_reply($queryid);
                   4398:     my $tries = 1;
                   4399:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4400:         $reply = &get_query_reply($queryid);
                   4401:         $tries ++;
                   4402:     }
                   4403:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   4404:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   4405:     } else {
                   4406:         my @responses = split(/:/,$reply);
                   4407:         my $outcome = shift(@responses); 
                   4408:         foreach my $item (@responses) {
                   4409:             my ($key,$value) = split(/=/,$item);
                   4410:             $$photo{$key} = $value;
                   4411:         }
                   4412:         return $outcome;
                   4413:     }
                   4414:     return 'error';
                   4415: }
                   4416: 
1.521     raeburn  4417: sub auto_instcode_format {
1.793     albertel 4418:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   4419: 	$cat_order) = @_;
1.521     raeburn  4420:     my $courses = '';
1.772     raeburn  4421:     my @homeservers;
1.521     raeburn  4422:     if ($caller eq 'global') {
1.793     albertel 4423:         foreach my $tryserver (keys(%libserv)) {
1.584     raeburn  4424:             if ($hostdom{$tryserver} eq $codedom) {
1.793     albertel 4425:                 if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
1.772     raeburn  4426:                     push(@homeservers,$tryserver);
                   4427:                 }
1.584     raeburn  4428:             }
                   4429:         }
1.521     raeburn  4430:     } else {
1.772     raeburn  4431:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  4432:     }
1.793     albertel 4433:     foreach my $code (keys(%{$instcodes})) {
                   4434:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  4435:     }
                   4436:     chop($courses);
1.772     raeburn  4437:     my $ok_response = 0;
                   4438:     my $response;
                   4439:     while (@homeservers > 0 && $ok_response == 0) {
                   4440:         my $server = shift(@homeservers); 
                   4441:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   4442:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   4443:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.793     albertel 4444: 		split/:/,$response;
1.772     raeburn  4445:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   4446:             push(@{$codetitles},&str2array($codetitles_str));
                   4447:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   4448:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   4449:             $ok_response = 1;
                   4450:         }
                   4451:     }
                   4452:     if ($ok_response) {
1.521     raeburn  4453:         return 'ok';
1.772     raeburn  4454:     } else {
                   4455:         return $response;
1.521     raeburn  4456:     }
                   4457: }
                   4458: 
1.792     raeburn  4459: sub auto_instcode_defaults {
                   4460:     my ($domain,$returnhash,$code_order) = @_;
                   4461:     my @homeservers;
1.793     albertel 4462:     foreach my $tryserver (keys(%libserv)) {
1.792     raeburn  4463:         if ($hostdom{$tryserver} eq $domain) {
1.793     albertel 4464:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
1.792     raeburn  4465:                 push(@homeservers,$tryserver);
                   4466:             }
                   4467:         }
                   4468:     }
                   4469:     my $ok_response = 0;
                   4470:     my $response;
                   4471:     while (@homeservers > 0 && $ok_response == 0) {
                   4472:         my $server = shift(@homeservers);
                   4473:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
                   4474:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
1.793     albertel 4475:             foreach my $pair (split(/\&/,$response)) {
                   4476:                 my ($name,$value)=split(/\=/,$pair);
1.792     raeburn  4477:                 if ($name eq 'code_order') {
1.796     raeburn  4478:                     @{$code_order} = split(/\&/,&unescape($value));
1.792     raeburn  4479:                 } else {
1.796     raeburn  4480:                     $returnhash->{&unescape($name)}=&unescape($value);
1.792     raeburn  4481:                 }
                   4482:             }
1.804     raeburn  4483:             $ok_response = 1;
1.792     raeburn  4484:         }
                   4485:     }
                   4486:     if ($ok_response) {
                   4487:         return 'ok';
                   4488:     } else {
                   4489:         return $response;
                   4490:     }
                   4491: } 
                   4492: 
1.777     albertel 4493: sub auto_validate_class_sec {
1.773     raeburn  4494:     my ($cdom,$cnum,$owner,$inst_class) = @_;
                   4495:     my $homeserver = &homeserver($cnum,$cdom);
                   4496:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.774     banghart 4497:                         &escape($owner).':'.$cdom,$homeserver);
1.773     raeburn  4498:     return $response;
                   4499: }
                   4500: 
1.679     raeburn  4501: # ------------------------------------------------------- Course Group routines
                   4502: 
                   4503: sub get_coursegroups {
1.809     raeburn  4504:     my ($cdom,$cnum,$group,$namespace) = @_;
                   4505:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  4506: }
                   4507: 
1.679     raeburn  4508: sub modify_coursegroup {
                   4509:     my ($cdom,$cnum,$groupsettings) = @_;
                   4510:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   4511: }
                   4512: 
1.809     raeburn  4513: sub toggle_coursegroup_status {
                   4514:     my ($cdom,$cnum,$group,$action) = @_;
                   4515:     my ($from_namespace,$to_namespace);
                   4516:     if ($action eq 'delete') {
                   4517:         $from_namespace = 'coursegroups';
                   4518:         $to_namespace = 'deleted_groups';
                   4519:     } else {
                   4520:         $from_namespace = 'deleted_groups';
                   4521:         $to_namespace = 'coursegroups';
                   4522:     }
                   4523:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  4524:     if (my $tmp = &error(%curr_group)) {
                   4525:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   4526:         return ('read error',$tmp);
                   4527:     } else {
                   4528:         my %savedsettings = %curr_group; 
1.809     raeburn  4529:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  4530:         my $deloutcome;
                   4531:         if ($result eq 'ok') {
1.809     raeburn  4532:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  4533:         } else {
                   4534:             return ('write error',$result);
                   4535:         }
                   4536:         if ($deloutcome eq 'ok') {
                   4537:             return 'ok';
                   4538:         } else {
                   4539:             return ('delete error',$deloutcome);
                   4540:         }
                   4541:     }
                   4542: }
                   4543: 
1.679     raeburn  4544: sub modify_group_roles {
                   4545:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
                   4546:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   4547:     my $role = 'gr/'.&escape($userprivs);
                   4548:     my ($uname,$udom) = split(/:/,$user);
                   4549:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
1.684     raeburn  4550:     if ($result eq 'ok') {
                   4551:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   4552:     }
1.679     raeburn  4553:     return $result;
                   4554: }
                   4555: 
                   4556: sub modify_coursegroup_membership {
                   4557:     my ($cdom,$cnum,$membership) = @_;
                   4558:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   4559:     return $result;
                   4560: }
                   4561: 
1.682     raeburn  4562: sub get_active_groups {
                   4563:     my ($udom,$uname,$cdom,$cnum) = @_;
                   4564:     my $now = time;
                   4565:     my %groups = ();
                   4566:     foreach my $key (keys(%env)) {
1.811     albertel 4567:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  4568:             my ($start,$end) = split(/\./,$env{$key});
                   4569:             if (($end!=0) && ($end<$now)) { next; }
                   4570:             if (($start!=0) && ($start>$now)) { next; }
                   4571:             if ($1 eq $cdom && $2 eq $cnum) {
                   4572:                 $groups{$3} = $env{$key} ;
                   4573:             }
                   4574:         }
                   4575:     }
                   4576:     return %groups;
                   4577: }
                   4578: 
1.683     raeburn  4579: sub get_group_membership {
                   4580:     my ($cdom,$cnum,$group) = @_;
                   4581:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   4582: }
                   4583: 
                   4584: sub get_users_groups {
                   4585:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  4586:     my @usersgroups;
1.683     raeburn  4587:     my $cachetime=1800;
                   4588: 
                   4589:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  4590:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   4591:     if (defined($cached)) {
1.734     albertel 4592:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  4593:     } else {  
                   4594:         $grouplist = '';
1.816     raeburn  4595:         my $courseurl = &courseid_to_courseurl($courseid);
                   4596:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  4597:         my $access_end = $env{'course.'.$courseid.
                   4598:                               '.default_enrollment_end_date'};
                   4599:         my $now = time;
                   4600:         foreach my $key (keys(%roleshash)) {
                   4601:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   4602:                 my $group = $1;
                   4603:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   4604:                     my $start = $2;
                   4605:                     my $end = $1;
                   4606:                     if ($start == -1) { next; } # deleted from group
                   4607:                     if (($start!=0) && ($start>$now)) { next; }
                   4608:                     if (($end!=0) && ($end<$now)) {
                   4609:                         if ($access_end && $access_end < $now) {
                   4610:                             if ($access_end - $end < 86400) {
                   4611:                                 push(@usersgroups,$group);
1.733     raeburn  4612:                             }
                   4613:                         }
1.817     raeburn  4614:                         next;
1.733     raeburn  4615:                     }
1.817     raeburn  4616:                     push(@usersgroups,$group);
1.683     raeburn  4617:                 }
                   4618:             }
                   4619:         }
1.817     raeburn  4620:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   4621:         $grouplist = join(':',@usersgroups);
                   4622:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  4623:     }
1.733     raeburn  4624:     return @usersgroups;
1.683     raeburn  4625: }
                   4626: 
                   4627: sub devalidate_getgroups_cache {
                   4628:     my ($udom,$uname,$cdom,$cnum)=@_;
                   4629:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 4630: 
1.683     raeburn  4631:     my $hashid="$udom:$uname:$courseid";
                   4632:     &devalidate_cache_new('getgroups',$hashid);
                   4633: }
                   4634: 
1.12      www      4635: # ------------------------------------------------------------------ Plain Text
                   4636: 
                   4637: sub plaintext {
1.742     raeburn  4638:     my ($short,$type,$cid) = @_;
1.758     albertel 4639:     if ($short =~ /^cr/) {
                   4640: 	return (split('/',$short))[-1];
                   4641:     }
1.742     raeburn  4642:     if (!defined($cid)) {
                   4643:         $cid = $env{'request.course.id'};
                   4644:     }
                   4645:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
                   4646:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
                   4647:                                           '.plaintext'});
                   4648:     }
                   4649:     my %rolenames = (
                   4650:                       Course => 'std',
                   4651:                       Group => 'alt1',
                   4652:                     );
                   4653:     if (defined($type) && 
                   4654:          defined($rolenames{$type}) && 
                   4655:          defined($prp{$short}{$rolenames{$type}})) {
                   4656:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   4657:     } else {
                   4658:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   4659:     }
1.12      www      4660: }
                   4661: 
                   4662: # ----------------------------------------------------------------- Assign Role
                   4663: 
                   4664: sub assignrole {
1.357     www      4665:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
1.21      www      4666:     my $mrole;
                   4667:     if ($role =~ /^cr\//) {
1.393     www      4668:         my $cwosec=$url;
1.811     albertel 4669:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      4670: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      4671:            &logthis('Refused custom assignrole: '.
                   4672:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4673: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4674:            return 'refused'; 
                   4675:         }
1.21      www      4676:         $mrole='cr';
1.678     raeburn  4677:     } elsif ($role =~ /^gr\//) {
                   4678:         my $cwogrp=$url;
1.811     albertel 4679:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  4680:         unless (&allowed('mdg',$cwogrp)) {
                   4681:             &logthis('Refused group assignrole: '.
                   4682:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   4683:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   4684:             return 'refused';
                   4685:         }
                   4686:         $mrole='gr';
1.21      www      4687:     } else {
1.82      www      4688:         my $cwosec=$url;
1.811     albertel 4689:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.373     www      4690:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
1.104     www      4691:            &logthis('Refused assignrole: '.
                   4692:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4693: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4694:            return 'refused'; 
                   4695:         }
1.21      www      4696:         $mrole=$role;
                   4697:     }
1.620     albertel 4698:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4699:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      4700:     if ($end) { $command.='_'.$end; }
1.21      www      4701:     if ($start) {
                   4702: 	if ($end) { 
1.81      www      4703:            $command.='_'.$start; 
1.21      www      4704:         } else {
1.81      www      4705:            $command.='_0_'.$start;
1.21      www      4706:         }
                   4707:     }
1.739     raeburn  4708:     my $origstart = $start;
                   4709:     my $origend = $end;
1.357     www      4710: # actually delete
                   4711:     if ($deleteflag) {
1.373     www      4712: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      4713: # modify command to delete the role
1.620     albertel 4714:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      4715:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 4716: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      4717: # set start and finish to negative values for userrolelog
                   4718:            $start=-1;
                   4719:            $end=-1;
                   4720:         }
                   4721:     }
                   4722: # send command
1.349     www      4723:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      4724: # log new user role if status is ok
1.349     www      4725:     if ($answer eq 'ok') {
1.663     raeburn  4726: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  4727: # for course roles, perform group memberships changes triggered by role change.
                   4728:         unless ($role =~ /^gr/) {
                   4729:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   4730:                                              $origstart);
                   4731:         }
1.349     www      4732:     }
                   4733:     return $answer;
1.169     harris41 4734: }
                   4735: 
                   4736: # -------------------------------------------------- Modify user authentication
1.197     www      4737: # Overrides without validation
                   4738: 
1.169     harris41 4739: sub modifyuserauth {
                   4740:     my ($udom,$uname,$umode,$upass)=@_;
                   4741:     my $uhome=&homeserver($uname,$udom);
1.197     www      4742:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   4743:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 4744:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4745:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 4746:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   4747: 		     &escape($upass),$uhome);
1.620     albertel 4748:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      4749:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   4750:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   4751:     &log($udom,,$uname,$uhome,
1.620     albertel 4752:         'Authentication changed by '.$env{'user.domain'}.', '.
                   4753:                                      $env{'user.name'}.', '.$umode.
1.197     www      4754:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 4755:     unless ($reply eq 'ok') {
1.197     www      4756:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 4757: 	return 'error: '.$reply;
                   4758:     }   
1.170     harris41 4759:     return 'ok';
1.80      www      4760: }
                   4761: 
1.81      www      4762: # --------------------------------------------------------------- Modify a user
1.80      www      4763: 
1.81      www      4764: sub modifyuser {
1.206     matthew  4765:     my ($udom,    $uname, $uid,
                   4766:         $umode,   $upass, $first,
                   4767:         $middle,  $last,  $gene,
1.387     www      4768:         $forceid, $desiredhome, $email)=@_;
1.807     albertel 4769:     $udom= &LONCAPA::clean_domain($udom);
                   4770:     $uname=&LONCAPA::clean_username($uname);
1.81      www      4771:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4772:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  4773: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   4774:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   4775:                                      ' desiredhome not specified'). 
1.620     albertel 4776:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4777:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 4778:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      4779: # ----------------------------------------------------------------- Create User
1.406     albertel 4780:     if (($uhome eq 'no_host') && 
                   4781: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      4782:         my $unhome='';
1.209     matthew  4783:         if (defined($desiredhome) && $hostdom{$desiredhome} eq $udom) { 
                   4784:             $unhome = $desiredhome;
1.620     albertel 4785: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   4786: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  4787:         } else { # load balancing routine for determining $unhome
1.80      www      4788:             my $tryserver;
1.81      www      4789:             my $loadm=10000000;
1.80      www      4790:             foreach $tryserver (keys %libserv) {
                   4791: 	       if ($hostdom{$tryserver} eq $udom) {
                   4792:                   my $answer=reply('load',$tryserver);
                   4793:                   if (($answer=~/\d+/) && ($answer<$loadm)) {
                   4794: 		      $loadm=$answer;
                   4795:                       $unhome=$tryserver;
                   4796:                   }
                   4797: 	       }
                   4798: 	    }
                   4799:         }
                   4800:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  4801: 	    return 'error: unable to find a home server for '.$uname.
                   4802:                    ' in domain '.$udom;
1.80      www      4803:         }
                   4804:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   4805:                          &escape($upass),$unhome);
                   4806: 	unless ($reply eq 'ok') {
                   4807:             return 'error: '.$reply;
                   4808:         }   
1.230     stredwic 4809:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      4810:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  4811: 	    return 'error: unable verify users home machine.';
1.80      www      4812:         }
1.209     matthew  4813:     }   # End of creation of new user
1.80      www      4814: # ---------------------------------------------------------------------- Add ID
                   4815:     if ($uid) {
                   4816:        $uid=~tr/A-Z/a-z/;
                   4817:        my %uidhash=&idrget($udom,$uname);
1.196     www      4818:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   4819:          && (!$forceid)) {
1.80      www      4820: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  4821: 	      return 'error: user id "'.$uid.'" does not match '.
                   4822:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      4823:           }
                   4824:        } else {
                   4825: 	  &idput($udom,($uname => $uid));
                   4826:        }
                   4827:     }
                   4828: # -------------------------------------------------------------- Add names, etc
1.313     matthew  4829:     my @tmp=&get('environment',
1.134     albertel 4830: 		   ['firstname','middlename','lastname','generation'],
                   4831: 		   $udom,$uname);
1.313     matthew  4832:     my %names;
                   4833:     if ($tmp[0] =~ m/^error:.*/) { 
                   4834:         %names=(); 
                   4835:     } else {
                   4836:         %names = @tmp;
                   4837:     }
1.388     www      4838: #
                   4839: # Make sure to not trash student environment if instructor does not bother
                   4840: # to supply name and email information
                   4841: #
                   4842:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  4843:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      4844:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  4845:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      4846:     if ($email) {
                   4847:        $email=~s/[^\w\@\.\-\,]//gs;
                   4848:        if ($email=~/\@/) { $names{'notification'} = $email;
                   4849: 			   $names{'critnotification'} = $email;
                   4850: 			   $names{'permanentemail'} = $email; }
                   4851:     }
1.134     albertel 4852:     my $reply = &put('environment', \%names, $udom,$uname);
                   4853:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.680     www      4854:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.81      www      4855:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4856:              $umode.', '.$first.', '.$middle.', '.
                   4857: 	     $last.', '.$gene.' by '.
1.620     albertel 4858:              $env{'user.name'}.' at '.$env{'user.domain'});
1.134     albertel 4859:     return 'ok';
1.80      www      4860: }
                   4861: 
1.81      www      4862: # -------------------------------------------------------------- Modify student
1.80      www      4863: 
1.81      www      4864: sub modifystudent {
                   4865:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.515     raeburn  4866:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
1.455     albertel 4867:     if (!$cid) {
1.620     albertel 4868: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 4869: 	    return 'not_in_class';
                   4870: 	}
1.80      www      4871:     }
                   4872: # --------------------------------------------------------------- Make the user
1.81      www      4873:     my $reply=&modifyuser
1.209     matthew  4874: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      4875:          $desiredhome,$email);
1.80      www      4876:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  4877:     # This will cause &modify_student_enrollment to get the uid from the
                   4878:     # students environment
                   4879:     $uid = undef if (!$forceid);
1.455     albertel 4880:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.515     raeburn  4881: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
1.297     matthew  4882:     return $reply;
                   4883: }
                   4884: 
                   4885: sub modify_student_enrollment {
1.515     raeburn  4886:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
1.455     albertel 4887:     my ($cdom,$cnum,$chome);
                   4888:     if (!$cid) {
1.620     albertel 4889: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 4890: 	    return 'not_in_class';
                   4891: 	}
1.620     albertel 4892: 	$cdom=$env{'course.'.$cid.'.domain'};
                   4893: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 4894:     } else {
                   4895: 	($cdom,$cnum)=split(/_/,$cid);
                   4896:     }
1.620     albertel 4897:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 4898:     if (!$chome) {
1.457     raeburn  4899: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  4900:     }
1.455     albertel 4901:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  4902:     # Make sure the user exists
1.81      www      4903:     my $uhome=&homeserver($uname,$udom);
                   4904:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   4905: 	return 'error: no such user';
                   4906:     }
1.297     matthew  4907:     # Get student data if we were not given enough information
                   4908:     if (!defined($first)  || $first  eq '' || 
                   4909:         !defined($last)   || $last   eq '' || 
                   4910:         !defined($uid)    || $uid    eq '' || 
                   4911:         !defined($middle) || $middle eq '' || 
                   4912:         !defined($gene)   || $gene   eq '') {
1.294     matthew  4913:         # They did not supply us with enough data to enroll the student, so
                   4914:         # we need to pick up more information.
1.297     matthew  4915:         my %tmp = &get('environment',
1.294     matthew  4916:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  4917:                        ,$udom,$uname);
                   4918: 
1.800     albertel 4919:         #foreach my $key (keys(%tmp)) {
                   4920:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 4921:         #}
1.294     matthew  4922:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   4923:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   4924:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  4925:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  4926:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   4927:     }
1.556     albertel 4928:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 4929:     my $reply=cput('classlist',
                   4930: 		   {"$uname:$udom" => 
1.515     raeburn  4931: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 4932: 		   $cdom,$cnum);
1.81      www      4933:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   4934: 	return 'error: '.$reply;
1.652     albertel 4935:     } else {
                   4936: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      4937:     }
1.297     matthew  4938:     # Add student role to user
1.83      www      4939:     my $uurl='/'.$cid;
1.81      www      4940:     $uurl=~s/\_/\//g;
                   4941:     if ($usec) {
                   4942: 	$uurl.='/'.$usec;
                   4943:     }
                   4944:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21      www      4945: }
                   4946: 
1.556     albertel 4947: sub format_name {
                   4948:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   4949:     my $name;
                   4950:     if ($first ne 'lastname') {
                   4951: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   4952:     } else {
                   4953: 	if ($lastname=~/\S/) {
                   4954: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   4955: 	    $name=~s/\s+,/,/;
                   4956: 	} else {
                   4957: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   4958: 	}
                   4959:     }
                   4960:     $name=~s/^\s+//;
                   4961:     $name=~s/\s+$//;
                   4962:     $name=~s/\s+/ /g;
                   4963:     return $name;
                   4964: }
                   4965: 
1.84      www      4966: # ------------------------------------------------- Write to course preferences
                   4967: 
                   4968: sub writecoursepref {
                   4969:     my ($courseid,%prefs)=@_;
                   4970:     $courseid=~s/^\///;
                   4971:     $courseid=~s/\_/\//g;
                   4972:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   4973:     my $chome=homeserver($cnum,$cdomain);
                   4974:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   4975: 	return 'error: no such course';
                   4976:     }
                   4977:     my $cstring='';
1.800     albertel 4978:     foreach my $pref (keys(%prefs)) {
                   4979: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 4980:     }
1.84      www      4981:     $cstring=~s/\&$//;
                   4982:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   4983: }
                   4984: 
                   4985: # ---------------------------------------------------------- Make/modify course
                   4986: 
                   4987: sub createcourse {
1.741     raeburn  4988:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
                   4989:         $course_owner,$crstype)=@_;
1.84      www      4990:     $url=&declutter($url);
                   4991:     my $cid='';
1.264     matthew  4992:     unless (&allowed('ccc',$udom)) {
1.84      www      4993:         return 'refused';
                   4994:     }
                   4995: # ------------------------------------------------------------------- Create ID
1.674     www      4996:    my $uname=int(1+rand(9)).
                   4997:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   4998:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      4999:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   5000: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 5001:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      5002:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5003:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   5004:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 5005:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      5006:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5007:            return 'error: unable to generate unique course-ID';
                   5008:        } 
                   5009:    }
1.264     matthew  5010: # ------------------------------------------------ Check supplied server name
1.620     albertel 5011:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.264     matthew  5012:     if (! exists($libserv{$course_server})) {
                   5013:         return 'error:bad server name '.$course_server;
                   5014:     }
1.84      www      5015: # ------------------------------------------------------------- Make the course
                   5016:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  5017:                       $course_server);
1.84      www      5018:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 5019:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      5020:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5021: 	return 'error: no such course';
                   5022:     }
1.271     www      5023: # ----------------------------------------------------------------- Course made
1.516     raeburn  5024: # log existence
                   5025:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
1.741     raeburn  5026:                  ':'.&escape($inst_code).':'.&escape($course_owner).':'.
                   5027:                   &escape($crstype),$uhome);
1.358     www      5028:     &flushcourselogs();
                   5029: # set toplevel url
1.271     www      5030:     my $topurl=$url;
                   5031:     unless ($nonstandard) {
                   5032: # ------------------------------------------ For standard courses, make top url
                   5033:         my $mapurl=&clutter($url);
1.278     www      5034:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 5035:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      5036: <map>
                   5037: <resource id="1" type="start"></resource>
                   5038: <resource id="2" src="$mapurl"></resource>
                   5039: <resource id="3" type="finish"></resource>
                   5040: <link index="1" from="1" to="2"></link>
                   5041: <link index="2" from="2" to="3"></link>
                   5042: </map>
                   5043: ENDINITMAP
                   5044:         $topurl=&declutter(
1.638     albertel 5045:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      5046:                           );
                   5047:     }
                   5048: # ----------------------------------------------------------- Write preferences
1.84      www      5049:     &writecoursepref($udom.'_'.$uname,
                   5050:                      ('description' => $description,
1.271     www      5051:                       'url'         => $topurl));
1.84      www      5052:     return '/'.$udom.'/'.$uname;
                   5053: }
                   5054: 
1.813     albertel 5055: sub is_course {
                   5056:     my ($cdom,$cnum) = @_;
                   5057:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
                   5058: 				undef,'.');
                   5059:     if (exists($courses{$cdom.'_'.$cnum})) {
                   5060:         return 1;
                   5061:     }
                   5062:     return 0;
                   5063: }
                   5064: 
1.21      www      5065: # ---------------------------------------------------------- Assign Custom Role
                   5066: 
                   5067: sub assigncustomrole {
1.357     www      5068:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21      www      5069:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357     www      5070:                        $end,$start,$deleteflag);
1.21      www      5071: }
                   5072: 
                   5073: # ----------------------------------------------------------------- Revoke Role
                   5074: 
                   5075: sub revokerole {
1.357     www      5076:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21      www      5077:     my $now=time;
1.357     www      5078:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21      www      5079: }
                   5080: 
                   5081: # ---------------------------------------------------------- Revoke Custom Role
                   5082: 
                   5083: sub revokecustomrole {
1.357     www      5084:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21      www      5085:     my $now=time;
1.357     www      5086:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
                   5087:            $deleteflag);
1.17      www      5088: }
                   5089: 
1.533     banghart 5090: # ------------------------------------------------------------ Disk usage
1.535     albertel 5091: sub diskusage {
1.533     banghart 5092:     my ($udom,$uname,$directoryRoot)=@_;
                   5093:     $directoryRoot =~ s/\/$//;
1.535     albertel 5094:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
1.514     albertel 5095:     return $listing;
1.512     banghart 5096: }
                   5097: 
1.566     banghart 5098: sub is_locked {
                   5099:     my ($file_name, $domain, $user) = @_;
                   5100:     my @check;
                   5101:     my $is_locked;
                   5102:     push @check, $file_name;
1.613     albertel 5103:     my %locked = &get('file_permissions',\@check,
1.620     albertel 5104: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 5105:     my ($tmp)=keys(%locked);
                   5106:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  5107:     
1.566     banghart 5108:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  5109:         $is_locked = 'false';
                   5110:         foreach my $entry (@{$locked{$file_name}}) {
                   5111:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  5112:                $is_locked = 'true';
                   5113:                last;
1.745     raeburn  5114:            }
                   5115:        }
1.566     banghart 5116:     } else {
                   5117:         $is_locked = 'false';
                   5118:     }
                   5119: }
                   5120: 
1.759     albertel 5121: sub declutter_portfile {
                   5122:     my ($file) = @_;
                   5123:     &logthis("got $file");
                   5124:     $file =~ s-^(/portfolio/|portfolio/)-/-;
                   5125:     &logthis("ret $file");
                   5126:     return $file;
                   5127: }
                   5128: 
1.559     banghart 5129: # ------------------------------------------------------------- Mark as Read Only
                   5130: 
                   5131: sub mark_as_readonly {
                   5132:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 5133:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5134:     my ($tmp)=keys(%current_permissions);
                   5135:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 5136:     foreach my $file (@{$files}) {
1.759     albertel 5137: 	$file = &declutter_portfile($file);
1.561     banghart 5138:         push(@{$current_permissions{$file}},$what);
1.559     banghart 5139:     }
1.613     albertel 5140:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5141:     return;
                   5142: }
                   5143: 
1.572     banghart 5144: # ------------------------------------------------------------Save Selected Files
                   5145: 
                   5146: sub save_selected_files {
                   5147:     my ($user, $path, @files) = @_;
                   5148:     my $filename = $user."savedfiles";
1.573     banghart 5149:     my @other_files = &files_not_in_path($user, $path);
1.574     banghart 5150:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 5151:     foreach my $file (@files) {
1.620     albertel 5152:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 5153:     }
                   5154:     foreach my $file (@other_files) {
1.574     banghart 5155:         print (OUT $file."\n");
1.572     banghart 5156:     }
1.574     banghart 5157:     close (OUT);
1.572     banghart 5158:     return 'ok';
                   5159: }
                   5160: 
1.574     banghart 5161: sub clear_selected_files {
                   5162:     my ($user) = @_;
                   5163:     my $filename = $user."savedfiles";
                   5164:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5165:     print (OUT undef);
                   5166:     close (OUT);
                   5167:     return ("ok");    
                   5168: }
                   5169: 
1.572     banghart 5170: sub files_in_path {
                   5171:     my ($user, $path) = @_;
                   5172:     my $filename = $user."savedfiles";
                   5173:     my %return_files;
1.574     banghart 5174:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 5175:     while (my $line_in = <IN>) {
1.574     banghart 5176:         chomp ($line_in);
                   5177:         my @paths_and_file = split (m!/!, $line_in);
                   5178:         my $file_part = pop (@paths_and_file);
                   5179:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 5180:         $path_part.='/';
                   5181:         my $path_and_file = $path_part.$file_part;
                   5182:         if ($path_part eq $path) {
                   5183:             $return_files{$file_part}= 'selected';
                   5184:         }
                   5185:     }
1.574     banghart 5186:     close (IN);
                   5187:     return (\%return_files);
1.572     banghart 5188: }
                   5189: 
                   5190: # called in portfolio select mode, to show files selected NOT in current directory
                   5191: sub files_not_in_path {
                   5192:     my ($user, $path) = @_;
                   5193:     my $filename = $user."savedfiles";
                   5194:     my @return_files;
                   5195:     my $path_part;
1.800     albertel 5196:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5197:     while (my $line = <IN>) {
1.572     banghart 5198:         #ok, I know it's clunky, but I want it to work
1.800     albertel 5199:         my @paths_and_file = split(m|/|, $line);
                   5200:         my $file_part = pop(@paths_and_file);
                   5201:         chomp($file_part);
                   5202:         my $path_part = join('/', @paths_and_file);
1.572     banghart 5203:         $path_part .= '/';
                   5204:         my $path_and_file = $path_part.$file_part;
                   5205:         if ($path_part ne $path) {
1.800     albertel 5206:             push(@return_files, ($path_and_file));
1.572     banghart 5207:         }
                   5208:     }
1.800     albertel 5209:     close(OUT);
1.574     banghart 5210:     return (@return_files);
1.572     banghart 5211: }
                   5212: 
1.745     raeburn  5213: #----------------------------------------------Get portfolio file permissions
1.629     banghart 5214: 
1.745     raeburn  5215: sub get_portfile_permissions {
                   5216:     my ($domain,$user) = @_;
1.613     albertel 5217:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5218:     my ($tmp)=keys(%current_permissions);
                   5219:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5220:     return \%current_permissions;
                   5221: }
                   5222: 
                   5223: #---------------------------------------------Get portfolio file access controls
                   5224: 
1.749     raeburn  5225: sub get_access_controls {
1.745     raeburn  5226:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 5227:     my %access;
                   5228:     my $real_file = $file;
                   5229:     $file =~ s/\.meta$//;
1.745     raeburn  5230:     if (defined($file)) {
1.749     raeburn  5231:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   5232:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 5233:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  5234:             }
                   5235:         }
1.745     raeburn  5236:     } else {
1.749     raeburn  5237:         foreach my $key (keys(%{$current_permissions})) {
                   5238:             if ($key =~ /\0accesscontrol$/) {
                   5239:                 if (defined($group)) {
                   5240:                     if ($key !~ m-^\Q$group\E/-) {
                   5241:                         next;
                   5242:                     }
                   5243:                 }
                   5244:                 my ($fullpath) = split(/\0/,$key);
                   5245:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   5246:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   5247:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   5248:                     }
                   5249:                 }
                   5250:             }
                   5251:         }
                   5252:     }
                   5253:     return %access;
                   5254: }
                   5255: 
                   5256: sub modify_access_controls {
                   5257:     my ($file_name,$changes,$domain,$user)=@_;
                   5258:     my ($outcome,$deloutcome);
                   5259:     my %store_permissions;
                   5260:     my %new_values;
                   5261:     my %new_control;
                   5262:     my %translation;
                   5263:     my @deletions = ();
                   5264:     my $now = time;
                   5265:     if (exists($$changes{'activate'})) {
                   5266:         if (ref($$changes{'activate'}) eq 'HASH') {
                   5267:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   5268:             my $numnew = scalar(@newitems);
                   5269:             for (my $i=0; $i<$numnew; $i++) {
                   5270:                 my $newkey = $newitems[$i];
                   5271:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  5272:                 if ($newkey =~ /^\d+:/) { 
                   5273:                     $newkey =~ s/^(\d+)/$newid/;
                   5274:                     $translation{$1} = $newid;
                   5275:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   5276:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   5277:                     $translation{$1} = $newid;
                   5278:                 }
1.749     raeburn  5279:                 $new_values{$file_name."\0".$newkey} = 
                   5280:                                           $$changes{'activate'}{$newitems[$i]};
                   5281:                 $new_control{$newkey} = $now;
                   5282:             }
                   5283:         }
                   5284:     }
                   5285:     my %todelete;
                   5286:     my %changed_items;
                   5287:     foreach my $action ('delete','update') {
                   5288:         if (exists($$changes{$action})) {
                   5289:             if (ref($$changes{$action}) eq 'HASH') {
                   5290:                 foreach my $key (keys(%{$$changes{$action}})) {
                   5291:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   5292:                     if ($action eq 'delete') { 
                   5293:                         $todelete{$itemnum} = 1;
                   5294:                     } else {
                   5295:                         $changed_items{$itemnum} = $key;
                   5296:                     }
                   5297:                 }
1.745     raeburn  5298:             }
                   5299:         }
1.749     raeburn  5300:     }
                   5301:     # get lock on access controls for file.
                   5302:     my $lockhash = {
                   5303:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   5304:                                                        ':'.$env{'user.domain'},
                   5305:                    }; 
                   5306:     my $tries = 0;
                   5307:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5308:    
                   5309:     while (($gotlock ne 'ok') && $tries <3) {
                   5310:         $tries ++;
                   5311:         sleep 1;
                   5312:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5313:     }
                   5314:     if ($gotlock eq 'ok') {
                   5315:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   5316:         my ($tmp)=keys(%curr_permissions);
                   5317:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   5318:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   5319:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   5320:             if (ref($curr_controls) eq 'HASH') {
                   5321:                 foreach my $control_item (keys(%{$curr_controls})) {
                   5322:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   5323:                     if (defined($todelete{$itemnum})) {
                   5324:                         push(@deletions,$file_name."\0".$control_item);
                   5325:                     } else {
                   5326:                         if (defined($changed_items{$itemnum})) {
                   5327:                             $new_control{$changed_items{$itemnum}} = $now;
                   5328:                             push(@deletions,$file_name."\0".$control_item);
                   5329:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   5330:                         } else {
                   5331:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   5332:                         }
                   5333:                     }
1.745     raeburn  5334:                 }
                   5335:             }
                   5336:         }
1.749     raeburn  5337:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   5338:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   5339:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   5340:         #  remove lock
                   5341:         my @del_lock = ($file_name."\0".'locked_access_records');
                   5342:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  5343:         my ($file,$group);
                   5344:         if (&is_course($domain,$user)) {
                   5345:             ($group,$file) = split(/\//,$file_name,2);
                   5346:         } else {
                   5347:             $file = $file_name;
                   5348:         }
                   5349:         my $sqlresult =
                   5350:             &update_portfolio_table($user,$domain,$file,'portfolio_access',
                   5351:                                     $group);
1.749     raeburn  5352:     } else {
                   5353:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  5354:     }
1.749     raeburn  5355:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  5356: }
                   5357: 
                   5358: #------------------------------------------------------Get Marked as Read Only
                   5359: 
                   5360: sub get_marked_as_readonly {
                   5361:     my ($domain,$user,$what,$group) = @_;
                   5362:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 5363:     my @readonly_files;
1.629     banghart 5364:     my $cmp1=$what;
                   5365:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  5366:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5367:         if (defined($group)) {
                   5368:             if ($file_name !~ m-^\Q$group\E/-) {
                   5369:                 next;
                   5370:             }
                   5371:         }
1.561     banghart 5372:         if (ref($value) eq "ARRAY"){
                   5373:             foreach my $stored_what (@{$value}) {
1.629     banghart 5374:                 my $cmp2=$stored_what;
1.759     albertel 5375:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  5376:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  5377:                 }
1.629     banghart 5378:                 if ($cmp1 eq $cmp2) {
1.561     banghart 5379:                     push(@readonly_files, $file_name);
1.745     raeburn  5380:                     last;
1.563     banghart 5381:                 } elsif (!defined($what)) {
                   5382:                     push(@readonly_files, $file_name);
1.745     raeburn  5383:                     last;
1.561     banghart 5384:                 }
                   5385:             }
1.745     raeburn  5386:         }
1.561     banghart 5387:     }
                   5388:     return @readonly_files;
                   5389: }
1.577     banghart 5390: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 5391: 
1.577     banghart 5392: sub get_marked_as_readonly_hash {
1.745     raeburn  5393:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 5394:     my %readonly_files;
1.745     raeburn  5395:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5396:         if (defined($group)) {
                   5397:             if ($file_name !~ m-^\Q$group\E/-) {
                   5398:                 next;
                   5399:             }
                   5400:         }
1.577     banghart 5401:         if (ref($value) eq "ARRAY"){
                   5402:             foreach my $stored_what (@{$value}) {
1.745     raeburn  5403:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 5404:                     foreach my $lock_descriptor(@{$stored_what}) {
                   5405:                         if ($lock_descriptor eq 'graded') {
                   5406:                             $readonly_files{$file_name} = 'graded';
                   5407:                         } elsif ($lock_descriptor eq 'handback') {
                   5408:                             $readonly_files{$file_name} = 'handback';
                   5409:                         } else {
                   5410:                             if (!exists($readonly_files{$file_name})) {
                   5411:                                 $readonly_files{$file_name} = 'locked';
                   5412:                             }
                   5413:                         }
1.745     raeburn  5414:                     }
1.750     banghart 5415:                 } 
1.577     banghart 5416:             }
                   5417:         } 
                   5418:     }
                   5419:     return %readonly_files;
                   5420: }
1.559     banghart 5421: # ------------------------------------------------------------ Unmark as Read Only
                   5422: 
                   5423: sub unmark_as_readonly {
1.629     banghart 5424:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   5425:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  5426:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 5427:     $file_name = &declutter_portfile($file_name);
1.634     albertel 5428:     my $symb_crs = $what;
                   5429:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  5430:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 5431:     my ($tmp)=keys(%current_permissions);
                   5432:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5433:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 5434:     foreach my $file (@readonly_files) {
1.759     albertel 5435: 	my $clean_file = &declutter_portfile($file);
                   5436: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 5437: 	my $current_locks = $current_permissions{$file};
1.563     banghart 5438:         my @new_locks;
                   5439:         my @del_keys;
                   5440:         if (ref($current_locks) eq "ARRAY"){
                   5441:             foreach my $locker (@{$current_locks}) {
1.632     albertel 5442:                 my $compare=$locker;
1.749     raeburn  5443:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  5444:                     $compare=join('',@{$locker});
1.746     raeburn  5445:                     if ($compare ne $symb_crs) {
                   5446:                         push(@new_locks, $locker);
                   5447:                     }
1.563     banghart 5448:                 }
                   5449:             }
1.650     albertel 5450:             if (scalar(@new_locks) > 0) {
1.563     banghart 5451:                 $current_permissions{$file} = \@new_locks;
                   5452:             } else {
                   5453:                 push(@del_keys, $file);
1.613     albertel 5454:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 5455:                 delete($current_permissions{$file});
1.563     banghart 5456:             }
                   5457:         }
1.561     banghart 5458:     }
1.613     albertel 5459:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5460:     return;
                   5461: }
1.512     banghart 5462: 
1.17      www      5463: # ------------------------------------------------------------ Directory lister
                   5464: 
                   5465: sub dirlist {
1.253     stredwic 5466:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
                   5467: 
1.18      www      5468:     $uri=~s/^\///;
                   5469:     $uri=~s/\/$//;
1.253     stredwic 5470:     my ($udom, $uname);
                   5471:     (undef,$udom,$uname)=split(/\//,$uri);
                   5472:     if(defined($userdomain)) {
                   5473:         $udom = $userdomain;
                   5474:     }
                   5475:     if(defined($username)) {
                   5476:         $uname = $username;
                   5477:     }
                   5478: 
                   5479:     my $dirRoot = $perlvar{'lonDocRoot'};
                   5480:     if(defined($alternateDirectoryRoot)) {
                   5481:         $dirRoot = $alternateDirectoryRoot;
                   5482:         $dirRoot =~ s/\/$//;
1.751     banghart 5483:     }
1.253     stredwic 5484: 
                   5485:     if($udom) {
                   5486:         if($uname) {
1.800     albertel 5487:             my $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   5488: 				 &homeserver($uname,$udom));
1.605     matthew  5489:             my @listing_results;
                   5490:             if ($listing eq 'unknown_cmd') {
1.800     albertel 5491:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   5492: 				  &homeserver($uname,$udom));
1.605     matthew  5493:                 @listing_results = split(/:/,$listing);
                   5494:             } else {
                   5495:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   5496:             }
                   5497:             return @listing_results;
1.253     stredwic 5498:         } elsif(!defined($alternateDirectoryRoot)) {
1.800     albertel 5499:             my %allusers;
                   5500:             foreach my $tryserver (keys(%libserv)) {
1.253     stredwic 5501:                 if($hostdom{$tryserver} eq $udom) {
1.800     albertel 5502:                     my $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   5503: 					 $udom, $tryserver);
1.605     matthew  5504:                     my @listing_results;
                   5505:                     if ($listing eq 'unknown_cmd') {
1.800     albertel 5506:                         $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   5507: 					  $udom, $tryserver);
1.605     matthew  5508:                         @listing_results = split(/:/,$listing);
                   5509:                     } else {
                   5510:                         @listing_results =
                   5511:                             map { &unescape($_); } split(/:/,$listing);
                   5512:                     }
                   5513:                     if ($listing_results[0] ne 'no_such_dir' && 
                   5514:                         $listing_results[0] ne 'empty'       &&
                   5515:                         $listing_results[0] ne 'con_lost') {
1.800     albertel 5516:                         foreach my $line (@listing_results) {
                   5517:                             my ($entry) = split(/&/,$line,2);
                   5518:                             $allusers{$entry} = 1;
1.253     stredwic 5519:                         }
                   5520:                     }
1.191     harris41 5521:                 }
1.253     stredwic 5522:             }
                   5523:             my $alluserstr='';
1.800     albertel 5524:             foreach my $user (sort(keys(%allusers))) {
                   5525:                 $alluserstr.=$user.'&user:';
1.253     stredwic 5526:             }
                   5527:             $alluserstr=~s/:$//;
                   5528:             return split(/:/,$alluserstr);
                   5529:         } else {
1.800     albertel 5530:             return ('missing user name');
1.253     stredwic 5531:         }
                   5532:     } elsif(!defined($alternateDirectoryRoot)) {
                   5533:         my $tryserver;
                   5534:         my %alldom=();
1.800     albertel 5535:         foreach $tryserver (keys(%libserv)) {
1.253     stredwic 5536:             $alldom{$hostdom{$tryserver}}=1;
                   5537:         }
                   5538:         my $alldomstr='';
1.800     albertel 5539:         foreach my $domain (sort(keys(%alldom))) {
                   5540:             $alldomstr.=$perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain:';
1.253     stredwic 5541:         }
                   5542:         $alldomstr=~s/:$//;
                   5543:         return split(/:/,$alldomstr);       
                   5544:     } else {
1.800     albertel 5545:         return ('missing domain');
1.275     stredwic 5546:     }
                   5547: }
                   5548: 
                   5549: # --------------------------------------------- GetFileTimestamp
                   5550: # This function utilizes dirlist and returns the date stamp for
                   5551: # when it was last modified.  It will also return an error of -1
                   5552: # if an error occurs
                   5553: 
1.410     matthew  5554: ##
                   5555: ## FIXME: This subroutine assumes its caller knows something about the
                   5556: ## directory structure of the home server for the student ($root).
                   5557: ## Not a good assumption to make.  Since this is for looking up files
                   5558: ## in user directories, the full path should be constructed by lond, not
                   5559: ## whatever machine we request data from.
                   5560: ##
1.275     stredwic 5561: sub GetFileTimestamp {
                   5562:     my ($studentDomain,$studentName,$filename,$root)=@_;
1.807     albertel 5563:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   5564:     $studentName   = &LONCAPA::clean_username($studentName);
1.275     stredwic 5565:     my $subdir=$studentName.'__';
                   5566:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   5567:     my $proname="$studentDomain/$subdir/$studentName";
                   5568:     $proname .= '/'.$filename;
1.375     matthew  5569:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
                   5570:                                               $studentName, $root);
1.275     stredwic 5571:     my @stats = split('&', $fileStat);
                   5572:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  5573:         # @stats contains first the filename, then the stat output
                   5574:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 5575:     } else {
                   5576:         return -1;
1.253     stredwic 5577:     }
1.26      www      5578: }
                   5579: 
1.712     albertel 5580: sub stat_file {
                   5581:     my ($uri) = @_;
1.787     albertel 5582:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 5583: 
1.712     albertel 5584:     my ($udom,$uname,$file,$dir);
                   5585:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   5586: 	($udom,$uname,$file) =
1.811     albertel 5587: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 5588: 	$file = 'userfiles/'.$file;
1.740     www      5589: 	$dir = &propath($udom,$uname);
1.712     albertel 5590:     }
                   5591:     if ($uri =~ m-^/res/-) {
                   5592: 	($udom,$uname) = 
1.807     albertel 5593: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 5594: 	$file = $uri;
                   5595:     }
                   5596: 
                   5597:     if (!$udom || !$uname || !$file) {
                   5598: 	# unable to handle the uri
                   5599: 	return ();
                   5600:     }
                   5601: 
                   5602:     my ($result) = &dirlist($file,$udom,$uname,$dir);
                   5603:     my @stats = split('&', $result);
1.721     banghart 5604:     
1.712     albertel 5605:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   5606: 	shift(@stats); #filename is first
                   5607: 	return @stats;
                   5608:     }
                   5609:     return ();
                   5610: }
                   5611: 
1.26      www      5612: # -------------------------------------------------------- Value of a Condition
                   5613: 
1.713     albertel 5614: # gets the value of a specific preevaluated condition
                   5615: #    stored in the string  $env{user.state.<cid>}
                   5616: # or looks up a condition reference in the bighash and if if hasn't
                   5617: # already been evaluated recurses into docondval to get the value of
                   5618: # the condition, then memoizing it to 
                   5619: #   $env{user.state.<cid>.<condition>}
1.40      www      5620: sub directcondval {
                   5621:     my $number=shift;
1.620     albertel 5622:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 5623: 	&Apache::lonuserstate::evalstate();
                   5624:     }
1.713     albertel 5625:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   5626: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   5627:     } elsif ($number =~ /^_/) {
                   5628: 	my $sub_condition;
                   5629: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   5630: 		&GDBM_READER(),0640)) {
                   5631: 	    $sub_condition=$bighash{'conditions'.$number};
                   5632: 	    untie(%bighash);
                   5633: 	}
                   5634: 	my $value = &docondval($sub_condition);
                   5635: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
                   5636: 	return $value;
                   5637:     }
1.620     albertel 5638:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   5639:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      5640:     } else {
                   5641:        return 2;
                   5642:     }
                   5643: }
                   5644: 
1.713     albertel 5645: # get the collection of conditions for this resource
1.26      www      5646: sub condval {
                   5647:     my $condidx=shift;
1.54      www      5648:     my $allpathcond='';
1.713     albertel 5649:     foreach my $cond (split(/\|/,$condidx)) {
                   5650: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   5651: 	    $allpathcond.=
                   5652: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   5653: 	}
1.191     harris41 5654:     }
1.54      www      5655:     $allpathcond=~s/\|$//;
1.713     albertel 5656:     return &docondval($allpathcond);
                   5657: }
                   5658: 
                   5659: #evaluates an expression of conditions
                   5660: sub docondval {
                   5661:     my ($allpathcond) = @_;
                   5662:     my $result=0;
                   5663:     if ($env{'request.course.id'}
                   5664: 	&& defined($allpathcond)) {
                   5665: 	my $operand='|';
                   5666: 	my @stack;
                   5667: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   5668: 	    if ($chunk eq '(') {
                   5669: 		push @stack,($operand,$result);
                   5670: 	    } elsif ($chunk eq ')') {
                   5671: 		my $before=pop @stack;
                   5672: 		if (pop @stack eq '&') {
                   5673: 		    $result=$result>$before?$before:$result;
                   5674: 		} else {
                   5675: 		    $result=$result>$before?$result:$before;
                   5676: 		}
                   5677: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   5678: 		$operand=$chunk;
                   5679: 	    } else {
                   5680: 		my $new=directcondval($chunk);
                   5681: 		if ($operand eq '&') {
                   5682: 		    $result=$result>$new?$new:$result;
                   5683: 		} else {
                   5684: 		    $result=$result>$new?$result:$new;
                   5685: 		}
                   5686: 	    }
                   5687: 	}
1.26      www      5688:     }
                   5689:     return $result;
1.421     albertel 5690: }
                   5691: 
                   5692: # ---------------------------------------------------- Devalidate courseresdata
                   5693: 
                   5694: sub devalidatecourseresdata {
                   5695:     my ($coursenum,$coursedomain)=@_;
                   5696:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 5697:     &devalidate_cache_new('courseres',$hashid);
1.28      www      5698: }
                   5699: 
1.763     www      5700: 
1.200     www      5701: # --------------------------------------------------- Course Resourcedata Query
                   5702: 
1.624     albertel 5703: sub get_courseresdata {
                   5704:     my ($coursenum,$coursedomain)=@_;
1.200     www      5705:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   5706:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 5707:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 5708:     my %dumpreply;
1.417     albertel 5709:     unless (defined($cached)) {
1.624     albertel 5710: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 5711: 	$result=\%dumpreply;
1.251     albertel 5712: 	my ($tmp) = keys(%dumpreply);
                   5713: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 5714: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 5715: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   5716: 	    return $tmp;
1.416     albertel 5717: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 5718: 	    $result=undef;
1.599     albertel 5719: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 5720: 	}
                   5721:     }
1.624     albertel 5722:     return $result;
                   5723: }
                   5724: 
1.633     albertel 5725: sub devalidateuserresdata {
                   5726:     my ($uname,$udom)=@_;
                   5727:     my $hashid="$udom:$uname";
                   5728:     &devalidate_cache_new('userres',$hashid);
                   5729: }
                   5730: 
1.624     albertel 5731: sub get_userresdata {
                   5732:     my ($uname,$udom)=@_;
                   5733:     #most student don\'t have any data set, check if there is some data
                   5734:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   5735: 
                   5736:     my $hashid="$udom:$uname";
                   5737:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   5738:     if (!defined($cached)) {
                   5739: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   5740: 	$result=\%resourcedata;
                   5741: 	&do_cache_new('userres',$hashid,$result,600);
                   5742:     }
                   5743:     my ($tmp)=keys(%$result);
                   5744:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   5745: 	return $result;
                   5746:     }
                   5747:     #error 2 occurs when the .db doesn't exist
                   5748:     if ($tmp!~/error: 2 /) {
1.672     albertel 5749: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 5750: 		 " Trying to get resource data for ".
                   5751: 		 $uname." at ".$udom.": ".
                   5752: 		 $tmp."</font>");
                   5753:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 5754: 	#&EXT_cache_set($udom,$uname);
                   5755: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 5756: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 5757:     }
                   5758:     return $tmp;
                   5759: }
                   5760: 
                   5761: sub resdata {
                   5762:     my ($name,$domain,$type,@which)=@_;
                   5763:     my $result;
                   5764:     if ($type eq 'course') {
                   5765: 	$result=&get_courseresdata($name,$domain);
                   5766:     } elsif ($type eq 'user') {
                   5767: 	$result=&get_userresdata($name,$domain);
                   5768:     }
                   5769:     if (!ref($result)) { return $result; }    
1.251     albertel 5770:     foreach my $item (@which) {
1.417     albertel 5771: 	if (defined($result->{$item})) {
                   5772: 	    return $result->{$item};
1.251     albertel 5773: 	}
1.250     albertel 5774:     }
1.291     albertel 5775:     return undef;
1.200     www      5776: }
                   5777: 
1.379     matthew  5778: #
                   5779: # EXT resource caching routines
                   5780: #
                   5781: 
                   5782: sub clear_EXT_cache_status {
1.383     albertel 5783:     &delenv('cache.EXT.');
1.379     matthew  5784: }
                   5785: 
                   5786: sub EXT_cache_status {
                   5787:     my ($target_domain,$target_user) = @_;
1.383     albertel 5788:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 5789:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  5790:         # We know already the user has no data
                   5791:         return 1;
                   5792:     } else {
                   5793:         return 0;
                   5794:     }
                   5795: }
                   5796: 
                   5797: sub EXT_cache_set {
                   5798:     my ($target_domain,$target_user) = @_;
1.383     albertel 5799:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.633     albertel 5800:     #&appenv($cachename => time);
1.379     matthew  5801: }
                   5802: 
1.28      www      5803: # --------------------------------------------------------- Value of a Variable
1.58      www      5804: sub EXT {
1.715     albertel 5805: 
1.395     albertel 5806:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      5807:     unless ($varname) { return ''; }
1.218     albertel 5808:     #get real user name/domain, courseid and symb
                   5809:     my $courseid;
1.359     albertel 5810:     my $publicuser;
1.427     www      5811:     if ($symbparm) {
                   5812: 	$symbparm=&get_symb_from_alias($symbparm);
                   5813:     }
1.218     albertel 5814:     if (!($uname && $udom)) {
1.790     albertel 5815:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 5816:       if (!$symbparm) {	$symbparm=$cursymb; }
                   5817:     } else {
1.620     albertel 5818: 	$courseid=$env{'request.course.id'};
1.218     albertel 5819:     }
1.48      www      5820:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   5821:     my $rest;
1.320     albertel 5822:     if (defined($therest[0])) {
1.48      www      5823:        $rest=join('.',@therest);
                   5824:     } else {
                   5825:        $rest='';
                   5826:     }
1.320     albertel 5827: 
1.57      www      5828:     my $qualifierrest=$qualifier;
                   5829:     if ($rest) { $qualifierrest.='.'.$rest; }
                   5830:     my $spacequalifierrest=$space;
                   5831:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      5832:     if ($realm eq 'user') {
1.48      www      5833: # --------------------------------------------------------------- user.resource
                   5834: 	if ($space eq 'resource') {
1.651     albertel 5835: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   5836: 		  || defined($Apache::lonhomework::parsing_a_task))
                   5837: 		 &&
1.744     albertel 5838: 		 ($symbparm eq &symbread()) ) {	
                   5839: 		# if we are in the middle of processing the resource the
                   5840: 		# get the value we are planning on committing
                   5841:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   5842:                     return $Apache::lonhomework::results{$qualifierrest};
                   5843:                 } else {
                   5844:                     return $Apache::lonhomework::history{$qualifierrest};
                   5845:                 }
1.335     albertel 5846: 	    } else {
1.359     albertel 5847: 		my %restored;
1.620     albertel 5848: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 5849: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   5850: 		} else {
                   5851: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   5852: 		}
1.335     albertel 5853: 		return $restored{$qualifierrest};
                   5854: 	    }
1.48      www      5855: # ----------------------------------------------------------------- user.access
                   5856:         } elsif ($space eq 'access') {
1.218     albertel 5857: 	    # FIXME - not supporting calls for a specific user
1.48      www      5858:             return &allowed($qualifier,$rest);
                   5859: # ------------------------------------------ user.preferences, user.environment
                   5860:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 5861: 	    if (($uname eq $env{'user.name'}) &&
                   5862: 		($udom eq $env{'user.domain'})) {
                   5863: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 5864: 	    } else {
1.359     albertel 5865: 		my %returnhash;
                   5866: 		if (!$publicuser) {
                   5867: 		    %returnhash=&userenvironment($udom,$uname,
                   5868: 						 $qualifierrest);
                   5869: 		}
1.218     albertel 5870: 		return $returnhash{$qualifierrest};
                   5871: 	    }
1.48      www      5872: # ----------------------------------------------------------------- user.course
                   5873:         } elsif ($space eq 'course') {
1.218     albertel 5874: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 5875:             return $env{join('.',('request.course',$qualifier))};
1.48      www      5876: # ------------------------------------------------------------------- user.role
                   5877:         } elsif ($space eq 'role') {
1.218     albertel 5878: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 5879:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      5880:             if ($qualifier eq 'value') {
                   5881: 		return $role;
                   5882:             } elsif ($qualifier eq 'extent') {
                   5883:                 return $where;
                   5884:             }
                   5885: # ----------------------------------------------------------------- user.domain
                   5886:         } elsif ($space eq 'domain') {
1.218     albertel 5887:             return $udom;
1.48      www      5888: # ------------------------------------------------------------------- user.name
                   5889:         } elsif ($space eq 'name') {
1.218     albertel 5890:             return $uname;
1.48      www      5891: # ---------------------------------------------------- Any other user namespace
1.29      www      5892:         } else {
1.359     albertel 5893: 	    my %reply;
                   5894: 	    if (!$publicuser) {
                   5895: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   5896: 	    }
                   5897: 	    return $reply{$qualifierrest};
1.48      www      5898:         }
1.236     www      5899:     } elsif ($realm eq 'query') {
                   5900: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 5901:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   5902: 						[$spacequalifierrest]);
1.620     albertel 5903: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      5904:    } elsif ($realm eq 'request') {
1.48      www      5905: # ------------------------------------------------------------- request.browser
                   5906:         if ($space eq 'browser') {
1.430     www      5907: 	    if ($qualifier eq 'textremote') {
1.676     albertel 5908: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      5909: 		    return 1;
                   5910: 		} else {
                   5911: 		    return 0;
                   5912: 		}
                   5913: 	    } else {
1.620     albertel 5914: 		return $env{'browser.'.$qualifier};
1.430     www      5915: 	    }
1.57      www      5916: # ------------------------------------------------------------ request.filename
                   5917:         } else {
1.620     albertel 5918:             return $env{'request.'.$spacequalifierrest};
1.29      www      5919:         }
1.28      www      5920:     } elsif ($realm eq 'course') {
1.48      www      5921: # ---------------------------------------------------------- course.description
1.620     albertel 5922:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      5923:     } elsif ($realm eq 'resource') {
1.165     www      5924: 
1.620     albertel 5925: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 5926: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   5927: 	}
1.693     albertel 5928: 
                   5929: 	if ($space eq 'title') {
                   5930: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   5931: 	    return &gettitle($symbparm);
                   5932: 	}
                   5933: 	
                   5934: 	if ($space eq 'map') {
                   5935: 	    my ($map) = &decode_symb($symbparm);
                   5936: 	    return &symbread($map);
                   5937: 	}
                   5938: 
                   5939: 	my ($section, $group, @groups);
1.593     albertel 5940: 	my ($courselevelm,$courselevel);
1.539     albertel 5941: 	if ($symbparm && defined($courseid) && 
1.620     albertel 5942: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      5943: 
1.218     albertel 5944: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      5945: 
1.60      www      5946: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 5947: 	    my $symbp=$symbparm;
1.735     albertel 5948: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 5949: 
                   5950: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   5951: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   5952: 
1.620     albertel 5953: 	    if (($env{'user.name'} eq $uname) &&
                   5954: 		($env{'user.domain'} eq $udom)) {
                   5955: 		$section=$env{'request.course.sec'};
1.733     raeburn  5956:                 @groups = split(/:/,$env{'request.course.groups'});  
                   5957:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 5958: 	    } else {
1.539     albertel 5959: 		if (! defined($usection)) {
1.551     albertel 5960: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 5961: 		} else {
                   5962: 		    $section = $usection;
                   5963: 		}
1.733     raeburn  5964:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 5965: 	    }
                   5966: 
                   5967: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   5968: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   5969: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   5970: 
1.593     albertel 5971: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 5972: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 5973: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      5974: 
1.60      www      5975: # ----------------------------------------------------------- first, check user
1.624     albertel 5976: 
                   5977: 	    my $userreply=&resdata($uname,$udom,'user',
                   5978: 				       ($courselevelr,$courselevelm,
                   5979: 					$courselevel));
                   5980: 	    if (defined($userreply)) { return $userreply; }
1.95      www      5981: 
1.594     albertel 5982: # ------------------------------------------------ second, check some of course
1.684     raeburn  5983:             my $coursereply;
1.691     raeburn  5984:             if (@groups > 0) {
                   5985:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   5986:                                        $mapparm,$spacequalifierrest);
1.684     raeburn  5987:                 if (defined($coursereply)) { return $coursereply; }
                   5988:             }
1.96      www      5989: 
1.684     raeburn  5990: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.624     albertel 5991: 				     $env{'course.'.$courseid.'.domain'},
                   5992: 				     'course',
                   5993: 				     ($seclevelr,$seclevelm,$seclevel,
                   5994: 				      $courselevelr));
1.287     albertel 5995: 	    if (defined($coursereply)) { return $coursereply; }
1.200     www      5996: 
1.60      www      5997: # ------------------------------------------------------ third, check map parms
1.218     albertel 5998: 	    my %parmhash=();
                   5999: 	    my $thisparm='';
                   6000: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 6001: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 6002: 		    &GDBM_READER(),0640)) {
1.218     albertel 6003: 		$thisparm=$parmhash{$symbparm};
                   6004: 		untie(%parmhash);
                   6005: 	    }
                   6006: 	    if ($thisparm) { return $thisparm; }
                   6007: 	}
1.594     albertel 6008: # ------------------------------------------ fourth, look in resource metadata
1.71      www      6009: 
1.218     albertel 6010: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 6011: 	my $filename;
                   6012: 	if (!$symbparm) { $symbparm=&symbread(); }
                   6013: 	if ($symbparm) {
1.409     www      6014: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 6015: 	} else {
1.620     albertel 6016: 	    $filename=$env{'request.filename'};
1.282     albertel 6017: 	}
                   6018: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.288     albertel 6019: 	if (defined($metadata)) { return $metadata; }
1.282     albertel 6020: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.288     albertel 6021: 	if (defined($metadata)) { return $metadata; }
1.142     www      6022: 
1.594     albertel 6023: # ---------------------------------------------- fourth, look in rest pf course
1.593     albertel 6024: 	if ($symbparm && defined($courseid) && 
1.620     albertel 6025: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 6026: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   6027: 				     $env{'course.'.$courseid.'.domain'},
                   6028: 				     'course',
                   6029: 				     ($courselevelm,$courselevel));
1.593     albertel 6030: 	    if (defined($coursereply)) { return $coursereply; }
                   6031: 	}
1.145     www      6032: # ------------------------------------------------------------------ Cascade up
1.218     albertel 6033: 	unless ($space eq '0') {
1.336     albertel 6034: 	    my @parts=split(/_/,$space);
                   6035: 	    my $id=pop(@parts);
                   6036: 	    my $part=join('_',@parts);
                   6037: 	    if ($part eq '') { $part='0'; }
                   6038: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 6039: 				 $symbparm,$udom,$uname,$section,1);
1.337     albertel 6040: 	    if (defined($partgeneral)) { return $partgeneral; }
1.218     albertel 6041: 	}
1.395     albertel 6042: 	if ($recurse) { return undef; }
                   6043: 	my $pack_def=&packages_tab_default($filename,$varname);
                   6044: 	if (defined($pack_def)) { return $pack_def; }
1.71      www      6045: 
1.48      www      6046: # ---------------------------------------------------- Any other user namespace
                   6047:     } elsif ($realm eq 'environment') {
                   6048: # ----------------------------------------------------------------- environment
1.620     albertel 6049: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   6050: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 6051: 	} else {
1.770     albertel 6052: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   6053: 		return '';
                   6054: 	    }
1.219     albertel 6055: 	    my %returnhash=&userenvironment($udom,$uname,
                   6056: 					    $spacequalifierrest);
                   6057: 	    return $returnhash{$spacequalifierrest};
                   6058: 	}
1.28      www      6059:     } elsif ($realm eq 'system') {
1.48      www      6060: # ----------------------------------------------------------------- system.time
                   6061: 	if ($space eq 'time') {
                   6062: 	    return time;
                   6063:         }
1.696     albertel 6064:     } elsif ($realm eq 'server') {
                   6065: # ----------------------------------------------------------------- system.time
                   6066: 	if ($space eq 'name') {
                   6067: 	    return $ENV{'SERVER_NAME'};
                   6068:         }
1.28      www      6069:     }
1.48      www      6070:     return '';
1.61      www      6071: }
                   6072: 
1.691     raeburn  6073: sub check_group_parms {
                   6074:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   6075:     my @groupitems = ();
                   6076:     my $resultitem;
                   6077:     my @levels = ($symbparm,$mapparm,$what);
                   6078:     foreach my $group (@{$groups}) {
                   6079:         foreach my $level (@levels) {
                   6080:              my $item = $courseid.'.['.$group.'].'.$level;
                   6081:              push(@groupitems,$item);
                   6082:         }
                   6083:     }
                   6084:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   6085:                             $env{'course.'.$courseid.'.domain'},
                   6086:                                      'course',@groupitems);
                   6087:     return $coursereply;
                   6088: }
                   6089: 
                   6090: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  6091:     my ($courseid,@groups) = @_;
                   6092:     @groups = sort(@groups);
1.691     raeburn  6093:     return @groups;
                   6094: }
                   6095: 
1.395     albertel 6096: sub packages_tab_default {
                   6097:     my ($uri,$varname)=@_;
                   6098:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 6099: 
                   6100:     my (@extension,@specifics,$do_default);
                   6101:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 6102: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 6103: 	if ($pack_type eq 'default') {
                   6104: 	    $do_default=1;
                   6105: 	} elsif ($pack_type eq 'extension') {
                   6106: 	    push(@extension,[$package,$pack_type,$pack_part]);
                   6107: 	} else {
                   6108: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   6109: 	}
                   6110:     }
                   6111:     # first look for a package that matches the requested part id
                   6112:     foreach my $package (@specifics) {
                   6113: 	my (undef,$pack_type,$pack_part)=@{$package};
                   6114: 	next if ($pack_part ne $part);
                   6115: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6116: 	    return $packagetab{"$pack_type&$name&default"};
                   6117: 	}
                   6118:     }
                   6119:     # look for any possible matching non extension_ package
                   6120:     foreach my $package (@specifics) {
                   6121: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 6122: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6123: 	    return $packagetab{"$pack_type&$name&default"};
                   6124: 	}
1.585     albertel 6125: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 6126: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   6127: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 6128: 	}
                   6129:     }
1.738     albertel 6130:     # look for any posible extension_ match
                   6131:     foreach my $package (@extension) {
                   6132: 	my ($package,$pack_type)=@{$package};
                   6133: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6134: 	    return $packagetab{"$pack_type&$name&default"};
                   6135: 	}
                   6136: 	if (defined($packagetab{$package."&$name&default"})) {
                   6137: 	    return $packagetab{$package."&$name&default"};
                   6138: 	}
                   6139:     }
                   6140:     # look for a global default setting
                   6141:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   6142: 	return $packagetab{"default&$name&default"};
                   6143:     }
1.395     albertel 6144:     return undef;
                   6145: }
                   6146: 
1.334     albertel 6147: sub add_prefix_and_part {
                   6148:     my ($prefix,$part)=@_;
                   6149:     my $keyroot;
                   6150:     if (defined($prefix) && $prefix !~ /^__/) {
                   6151: 	# prefix that has a part already
                   6152: 	$keyroot=$prefix;
                   6153:     } elsif (defined($prefix)) {
                   6154: 	# prefix that is missing a part
                   6155: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   6156:     } else {
                   6157: 	# no prefix at all
                   6158: 	if (defined($part)) { $keyroot='_'.$part; }
                   6159:     }
                   6160:     return $keyroot;
                   6161: }
                   6162: 
1.71      www      6163: # ---------------------------------------------------------------- Get metadata
                   6164: 
1.599     albertel 6165: my %metaentry;
1.71      www      6166: sub metadata {
1.176     www      6167:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      6168:     $uri=&declutter($uri);
1.288     albertel 6169:     # if it is a non metadata possible uri return quickly
1.529     albertel 6170:     if (($uri eq '') || 
                   6171: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 6172: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.423     albertel 6173:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
1.807     albertel 6174: 	($uri =~ m|home/$match_username/public_html/|)) {
1.468     albertel 6175: 	return undef;
1.288     albertel 6176:     }
1.73      www      6177:     my $filename=$uri;
                   6178:     $uri=~s/\.meta$//;
1.172     www      6179: #
                   6180: # Is the metadata already cached?
1.177     www      6181: # Look at timestamp of caching
1.172     www      6182: # Everything is cached by the main uri, libraries are never directly cached
                   6183: #
1.428     albertel 6184:     if (!defined($liburi)) {
1.599     albertel 6185: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 6186: 	if (defined($cached)) { return $result->{':'.$what}; }
                   6187:     }
                   6188:     {
1.172     www      6189: #
                   6190: # Is this a recursive call for a library?
                   6191: #
1.599     albertel 6192: #	if (! exists($metacache{$uri})) {
                   6193: #	    $metacache{$uri}={};
                   6194: #	}
1.171     www      6195:         if ($liburi) {
                   6196: 	    $liburi=&declutter($liburi);
                   6197:             $filename=$liburi;
1.401     bowersj2 6198:         } else {
1.599     albertel 6199: 	    &devalidate_cache_new('meta',$uri);
                   6200: 	    undef(%metaentry);
1.401     bowersj2 6201: 	}
1.140     www      6202:         my %metathesekeys=();
1.73      www      6203:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 6204: 	my $metastring;
1.768     albertel 6205: 	if ($uri !~ m -^(editupload)/-) {
1.543     albertel 6206: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 6207: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 6208: 	    $metastring=&getfile($file);
1.489     albertel 6209: 	}
1.208     albertel 6210:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      6211:         my $token;
1.140     www      6212:         undef %metathesekeys;
1.71      www      6213:         while ($token=$parser->get_token) {
1.339     albertel 6214: 	    if ($token->[0] eq 'S') {
                   6215: 		if (defined($token->[2]->{'package'})) {
1.172     www      6216: #
                   6217: # This is a package - get package info
                   6218: #
1.339     albertel 6219: 		    my $package=$token->[2]->{'package'};
                   6220: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6221: 		    if (defined($token->[2]->{'id'})) { 
                   6222: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   6223: 		    }
1.599     albertel 6224: 		    if ($metaentry{':packages'}) {
                   6225: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 6226: 		    } else {
1.599     albertel 6227: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 6228: 		    }
1.736     albertel 6229: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 6230: 			my $part=$keyroot;
                   6231: 			$part=~s/^\_//;
1.736     albertel 6232: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   6233: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   6234: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 6235: 			    # ignore package.tab specified default values
                   6236:                             # here &package_tab_default() will fetch those
                   6237: 			    if ($subp eq 'default') { next; }
1.736     albertel 6238: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 6239: 			    my $unikey;
                   6240: 			    if ($pack =~ /_0$/) {
                   6241: 				$unikey='parameter_0_'.$name;
                   6242: 				$part=0;
                   6243: 			    } else {
                   6244: 				$unikey='parameter'.$keyroot.'_'.$name;
                   6245: 			    }
1.339     albertel 6246: 			    if ($subp eq 'display') {
                   6247: 				$value.=' [Part: '.$part.']';
                   6248: 			    }
1.599     albertel 6249: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 6250: 			    $metathesekeys{$unikey}=1;
1.599     albertel 6251: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6252: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 6253: 			    }
1.599     albertel 6254: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   6255: 				$metaentry{':'.$unikey}=
                   6256: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 6257: 			    }
1.339     albertel 6258: 			}
                   6259: 		    }
                   6260: 		} else {
1.172     www      6261: #
                   6262: # This is not a package - some other kind of start tag
1.339     albertel 6263: #
                   6264: 		    my $entry=$token->[1];
                   6265: 		    my $unikey;
                   6266: 		    if ($entry eq 'import') {
                   6267: 			$unikey='';
                   6268: 		    } else {
                   6269: 			$unikey=$entry;
                   6270: 		    }
                   6271: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6272: 
                   6273: 		    if (defined($token->[2]->{'id'})) { 
                   6274: 			$unikey.='_'.$token->[2]->{'id'}; 
                   6275: 		    }
1.175     www      6276: 
1.339     albertel 6277: 		    if ($entry eq 'import') {
1.175     www      6278: #
                   6279: # Importing a library here
1.339     albertel 6280: #
                   6281: 			if ($depthcount<20) {
                   6282: 			    my $location=$parser->get_text('/import');
                   6283: 			    my $dir=$filename;
                   6284: 			    $dir=~s|[^/]*$||;
                   6285: 			    $location=&filelocation($dir,$location);
1.736     albertel 6286: 			    my $metadata = 
                   6287: 				&metadata($uri,'keys', $location,$unikey,
                   6288: 					  $depthcount+1);
                   6289: 			    foreach my $meta (split(',',$metadata)) {
                   6290: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   6291: 				$metathesekeys{$meta}=1;
1.339     albertel 6292: 			    }
                   6293: 			}
                   6294: 		    } else { 
                   6295: 			
                   6296: 			if (defined($token->[2]->{'name'})) { 
                   6297: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   6298: 			}
                   6299: 			$metathesekeys{$unikey}=1;
1.736     albertel 6300: 			foreach my $param (@{$token->[3]}) {
                   6301: 			    $metaentry{':'.$unikey.'.'.$param} =
                   6302: 				$token->[2]->{$param};
1.339     albertel 6303: 			}
                   6304: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 6305: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 6306: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   6307: 		 # only ws inside the tag, and not in default, so use default
                   6308: 		 # as value
1.599     albertel 6309: 			    $metaentry{':'.$unikey}=$default;
1.339     albertel 6310: 			} else {
1.321     albertel 6311: 		  # either something interesting inside the tag or default
                   6312:                   # uninteresting
1.599     albertel 6313: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 6314: 			}
1.172     www      6315: # end of not-a-package not-a-library import
1.339     albertel 6316: 		    }
1.172     www      6317: # end of not-a-package start tag
1.339     albertel 6318: 		}
1.172     www      6319: # the next is the end of "start tag"
1.339     albertel 6320: 	    }
                   6321: 	}
1.483     albertel 6322: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.737     albertel 6323: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 6324: 	    #no specific packages #how's our extension
                   6325: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 6326: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 6327: 					 \%metathesekeys);
                   6328: 	}
1.599     albertel 6329: 	if (!exists($metaentry{':packages'})) {
1.737     albertel 6330: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 6331: 		#no specific packages well let's get default then
                   6332: 		if ($key!~/^default&/) { next; }
1.488     albertel 6333: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 6334: 					     \%metathesekeys);
                   6335: 	    }
                   6336: 	}
1.338     www      6337: # are there custom rights to evaluate
1.599     albertel 6338: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 6339: 
1.338     www      6340:     #
                   6341:     # Importing a rights file here
1.339     albertel 6342:     #
                   6343: 	    unless ($depthcount) {
1.599     albertel 6344: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 6345: 		my $dir=$filename;
                   6346: 		$dir=~s|[^/]*$||;
                   6347: 		$location=&filelocation($dir,$location);
1.736     albertel 6348: 		my $rights_metadata =
                   6349: 		    &metadata($uri,'keys',$location,'_rights',
                   6350: 			      $depthcount+1);
                   6351: 		foreach my $rights (split(',',$rights_metadata)) {
                   6352: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   6353: 		    $metathesekeys{$rights}=1;
1.339     albertel 6354: 		}
                   6355: 	    }
                   6356: 	}
1.737     albertel 6357: 	# uniqifiy package listing
                   6358: 	my %seen;
                   6359: 	my @uniq_packages =
                   6360: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   6361: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   6362: 
                   6363: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 6364: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   6365: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.699     albertel 6366: 	&do_cache_new('meta',$uri,\%metaentry,60*60);
1.177     www      6367: # this is the end of "was not already recently cached
1.71      www      6368:     }
1.599     albertel 6369:     return $metaentry{':'.$what};
1.261     albertel 6370: }
                   6371: 
1.488     albertel 6372: sub metadata_create_package_def {
1.483     albertel 6373:     my ($uri,$key,$package,$metathesekeys)=@_;
                   6374:     my ($pack,$name,$subp)=split(/\&/,$key);
                   6375:     if ($subp eq 'default') { next; }
                   6376:     
1.599     albertel 6377:     if (defined($metaentry{':packages'})) {
                   6378: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 6379:     } else {
1.599     albertel 6380: 	$metaentry{':packages'}=$package;
1.483     albertel 6381:     }
                   6382:     my $value=$packagetab{$key};
                   6383:     my $unikey;
                   6384:     $unikey='parameter_0_'.$name;
1.599     albertel 6385:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 6386:     $$metathesekeys{$unikey}=1;
1.599     albertel 6387:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6388: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 6389:     }
1.599     albertel 6390:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   6391: 	$metaentry{':'.$unikey}=
                   6392: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 6393:     }
                   6394: }
                   6395: 
1.261     albertel 6396: sub metadata_generate_part0 {
                   6397:     my ($metadata,$metacache,$uri) = @_;
                   6398:     my %allnames;
1.737     albertel 6399:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 6400: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 6401: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   6402: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 6403: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 6404: 	    $allnames{$name}=$part;
                   6405: 	  }
                   6406: 	}
                   6407:     }
                   6408:     foreach my $name (keys(%allnames)) {
                   6409:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 6410:       my $key=":parameter_0_$name";
1.261     albertel 6411:       $$metacache{"$key.part"}='0';
                   6412:       $$metacache{"$key.name"}=$name;
1.428     albertel 6413:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 6414: 					   $allnames{$name}.'_'.$name.
                   6415: 					   '.type'};
1.428     albertel 6416:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 6417: 			     '.display'};
1.644     www      6418:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 6419:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 6420:       $$metacache{"$key.display"}=$olddis;
                   6421:     }
1.71      www      6422: }
                   6423: 
1.764     albertel 6424: # ------------------------------------------------------ Devalidate title cache
                   6425: 
                   6426: sub devalidate_title_cache {
                   6427:     my ($url)=@_;
                   6428:     if (!$env{'request.course.id'}) { return; }
                   6429:     my $symb=&symbread($url);
                   6430:     if (!$symb) { return; }
                   6431:     my $key=$env{'request.course.id'}."\0".$symb;
                   6432:     &devalidate_cache_new('title',$key);
                   6433: }
                   6434: 
1.301     www      6435: # ------------------------------------------------- Get the title of a resource
                   6436: 
                   6437: sub gettitle {
                   6438:     my $urlsymb=shift;
                   6439:     my $symb=&symbread($urlsymb);
1.534     albertel 6440:     if ($symb) {
1.620     albertel 6441: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 6442: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 6443: 	if (defined($cached)) { 
                   6444: 	    return $result;
                   6445: 	}
1.534     albertel 6446: 	my ($map,$resid,$url)=&decode_symb($symb);
                   6447: 	my $title='';
                   6448: 	my %bighash;
1.620     albertel 6449: 	if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.534     albertel 6450: 		&GDBM_READER(),0640)) {
                   6451: 	    my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   6452: 	    $title=$bighash{'title_'.$mapid.'.'.$resid};
                   6453: 	    untie %bighash;
                   6454: 	}
                   6455: 	$title=~s/\&colon\;/\:/gs;
                   6456: 	if ($title) {
1.599     albertel 6457: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 6458: 	}
                   6459: 	$urlsymb=$url;
                   6460:     }
                   6461:     my $title=&metadata($urlsymb,'title');
                   6462:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   6463:     return $title;
1.301     www      6464: }
1.613     albertel 6465: 
1.614     albertel 6466: sub get_slot {
                   6467:     my ($which,$cnum,$cdom)=@_;
                   6468:     if (!$cnum || !$cdom) {
1.790     albertel 6469: 	(undef,my $courseid)=&whichuser();
1.620     albertel 6470: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   6471: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 6472:     }
1.703     albertel 6473:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   6474:     my %slotinfo;
                   6475:     if (exists($remembered{$key})) {
                   6476: 	$slotinfo{$which} = $remembered{$key};
                   6477:     } else {
                   6478: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   6479: 	&Apache::lonhomework::showhash(%slotinfo);
                   6480: 	my ($tmp)=keys(%slotinfo);
                   6481: 	if ($tmp=~/^error:/) { return (); }
                   6482: 	$remembered{$key} = $slotinfo{$which};
                   6483:     }
1.616     albertel 6484:     if (ref($slotinfo{$which}) eq 'HASH') {
                   6485: 	return %{$slotinfo{$which}};
                   6486:     }
                   6487:     return $slotinfo{$which};
1.614     albertel 6488: }
1.31      www      6489: # ------------------------------------------------- Update symbolic store links
                   6490: 
                   6491: sub symblist {
                   6492:     my ($mapname,%newhash)=@_;
1.438     www      6493:     $mapname=&deversion(&declutter($mapname));
1.31      www      6494:     my %hash;
1.620     albertel 6495:     if (($env{'request.course.fn'}) && (%newhash)) {
                   6496:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6497:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 6498: 	    foreach my $url (keys %newhash) {
                   6499: 		next if ($url eq 'last_known'
                   6500: 			 && $env{'form.no_update_last_known'});
                   6501: 		$hash{declutter($url)}=&encode_symb($mapname,
                   6502: 						    $newhash{$url}->[1],
                   6503: 						    $newhash{$url}->[0]);
1.191     harris41 6504:             }
1.31      www      6505:             if (untie(%hash)) {
                   6506: 		return 'ok';
                   6507:             }
                   6508:         }
                   6509:     }
                   6510:     return 'error';
1.212     www      6511: }
                   6512: 
                   6513: # --------------------------------------------------------------- Verify a symb
                   6514: 
                   6515: sub symbverify {
1.510     www      6516:     my ($symb,$thisurl)=@_;
                   6517:     my $thisfn=$thisurl;
1.439     www      6518:     $thisfn=&declutter($thisfn);
1.215     www      6519: # direct jump to resource in page or to a sequence - will construct own symbs
                   6520:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   6521: # check URL part
1.409     www      6522:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      6523: 
1.431     www      6524:     unless ($url eq $thisfn) { return 0; }
1.213     www      6525: 
1.216     www      6526:     $symb=&symbclean($symb);
1.510     www      6527:     $thisurl=&deversion($thisurl);
1.439     www      6528:     $thisfn=&deversion($thisfn);
1.213     www      6529: 
                   6530:     my %bighash;
                   6531:     my $okay=0;
1.431     www      6532: 
1.620     albertel 6533:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6534:                             &GDBM_READER(),0640)) {
1.510     www      6535:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      6536:         unless ($ids) { 
1.510     www      6537:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      6538:         }
                   6539:         if ($ids) {
                   6540: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 6541: 	    foreach my $id (split(/\,/,$ids)) {
                   6542: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      6543:                if (
                   6544:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   6545:    eq $symb) { 
1.620     albertel 6546: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 6547: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 6548: 		       $okay=1; 
                   6549: 		   }
                   6550: 	       }
1.216     www      6551: 	   }
                   6552:         }
1.213     www      6553: 	untie(%bighash);
                   6554:     }
                   6555:     return $okay;
1.31      www      6556: }
                   6557: 
1.210     www      6558: # --------------------------------------------------------------- Clean-up symb
                   6559: 
                   6560: sub symbclean {
                   6561:     my $symb=shift;
1.568     albertel 6562:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      6563: # remove version from map
                   6564:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      6565: 
1.210     www      6566: # remove version from URL
                   6567:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      6568: 
1.507     www      6569: # remove wrapper
                   6570: 
1.510     www      6571:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 6572:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      6573:     return $symb;
1.409     www      6574: }
                   6575: 
                   6576: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 6577: 
                   6578: sub encode_symb {
                   6579:     my ($map,$resid,$url)=@_;
                   6580:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   6581: }
1.409     www      6582: 
                   6583: sub decode_symb {
1.568     albertel 6584:     my $symb=shift;
                   6585:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   6586:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      6587:     return (&fixversion($map),$resid,&fixversion($url));
                   6588: }
                   6589: 
                   6590: sub fixversion {
                   6591:     my $fn=shift;
1.609     banghart 6592:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      6593:     my %bighash;
                   6594:     my $uri=&clutter($fn);
1.620     albertel 6595:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      6596: # is this cached?
1.599     albertel 6597:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      6598:     if (defined($cached)) { return $result; }
                   6599: # unfortunately not cached, or expired
1.620     albertel 6600:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      6601: 	    &GDBM_READER(),0640)) {
                   6602:  	if ($bighash{'version_'.$uri}) {
                   6603:  	    my $version=$bighash{'version_'.$uri};
1.444     www      6604:  	    unless (($version eq 'mostrecent') || 
                   6605: 		    ($version==&getversion($uri))) {
1.440     www      6606:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   6607:  	    }
                   6608:  	}
                   6609:  	untie %bighash;
1.413     www      6610:     }
1.599     albertel 6611:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      6612: }
                   6613: 
                   6614: sub deversion {
                   6615:     my $url=shift;
                   6616:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   6617:     return $url;
1.210     www      6618: }
                   6619: 
1.31      www      6620: # ------------------------------------------------------ Return symb list entry
                   6621: 
                   6622: sub symbread {
1.249     www      6623:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 6624:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 6625:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      6626: # no filename provided? try from environment
1.44      www      6627:     unless ($thisfn) {
1.620     albertel 6628:         if ($env{'request.symb'}) {
                   6629: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 6630: 	}
1.620     albertel 6631: 	$thisfn=$env{'request.filename'};
1.44      www      6632:     }
1.569     albertel 6633:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      6634: # is that filename actually a symb? Verify, clean, and return
                   6635:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 6636: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 6637: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 6638: 	}
1.242     www      6639:     }
1.44      www      6640:     $thisfn=declutter($thisfn);
1.31      www      6641:     my %hash;
1.37      www      6642:     my %bighash;
                   6643:     my $syval='';
1.620     albertel 6644:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  6645:         my $targetfn = $thisfn;
1.609     banghart 6646:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  6647:             $targetfn = 'adm/wrapper/'.$thisfn;
                   6648:         }
1.687     albertel 6649: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   6650: 	    $targetfn=$1;
                   6651: 	}
1.620     albertel 6652:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6653:                       &GDBM_READER(),0640)) {
1.481     raeburn  6654: 	    $syval=$hash{$targetfn};
1.37      www      6655:             untie(%hash);
                   6656:         }
                   6657: # ---------------------------------------------------------- There was an entry
                   6658:         if ($syval) {
1.601     albertel 6659: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 6660: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.601     albertel 6661: 		    #&appenv('request.ambiguous' => $thisfn);
1.620     albertel 6662: 		    #return $env{$cache_str}='';
1.601     albertel 6663: 		#}    
                   6664: 		#$syval.=$1;
                   6665: 	    #}
1.37      www      6666:         } else {
                   6667: # ------------------------------------------------------- Was not in symb table
1.620     albertel 6668:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6669:                             &GDBM_READER(),0640)) {
1.37      www      6670: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      6671:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      6672:               unless ($ids) { 
                   6673:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      6674:               }
                   6675:               unless ($ids) {
                   6676: # alias?
                   6677: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      6678:               }
1.37      www      6679:               if ($ids) {
                   6680: # ------------------------------------------------------------------- Has ID(s)
                   6681:                  my @possibilities=split(/\,/,$ids);
1.39      www      6682:                  if ($#possibilities==0) {
                   6683: # ----------------------------------------------- There is only one possibility
1.37      www      6684: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 6685: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6686: 						    $resid,$thisfn);
1.249     www      6687:                  } elsif (!$donotrecurse) {
1.39      www      6688: # ------------------------------------------ There is more than one possibility
                   6689:                      my $realpossible=0;
1.800     albertel 6690:                      foreach my $id (@possibilities) {
                   6691: 			 my $file=$bighash{'src_'.$id};
1.39      www      6692:                          if (&allowed('bre',$file)) {
1.800     albertel 6693:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      6694:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   6695: 				$realpossible++;
1.626     albertel 6696:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6697: 						    $resid,$thisfn);
1.39      www      6698:                             }
                   6699: 			 }
1.191     harris41 6700:                      }
1.39      www      6701: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      6702:                  } else {
                   6703:                      $syval='';
1.37      www      6704:                  }
                   6705: 	      }
                   6706:               untie(%bighash)
1.481     raeburn  6707:            }
1.31      www      6708:         }
1.62      www      6709:         if ($syval) {
1.620     albertel 6710: 	    return $env{$cache_str}=$syval;
1.62      www      6711:         }
1.31      www      6712:     }
1.44      www      6713:     &appenv('request.ambiguous' => $thisfn);
1.620     albertel 6714:     return $env{$cache_str}='';
1.31      www      6715: }
                   6716: 
                   6717: # ---------------------------------------------------------- Return random seed
                   6718: 
1.32      www      6719: sub numval {
                   6720:     my $txt=shift;
                   6721:     $txt=~tr/A-J/0-9/;
                   6722:     $txt=~tr/a-j/0-9/;
                   6723:     $txt=~tr/K-T/0-9/;
                   6724:     $txt=~tr/k-t/0-9/;
                   6725:     $txt=~tr/U-Z/0-5/;
                   6726:     $txt=~tr/u-z/0-5/;
                   6727:     $txt=~s/\D//g;
1.564     albertel 6728:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      6729:     return int($txt);
1.368     albertel 6730: }
                   6731: 
1.484     albertel 6732: sub numval2 {
                   6733:     my $txt=shift;
                   6734:     $txt=~tr/A-J/0-9/;
                   6735:     $txt=~tr/a-j/0-9/;
                   6736:     $txt=~tr/K-T/0-9/;
                   6737:     $txt=~tr/k-t/0-9/;
                   6738:     $txt=~tr/U-Z/0-5/;
                   6739:     $txt=~tr/u-z/0-5/;
                   6740:     $txt=~s/\D//g;
                   6741:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   6742:     my $total;
                   6743:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 6744:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 6745:     return int($total);
                   6746: }
                   6747: 
1.575     albertel 6748: sub numval3 {
                   6749:     use integer;
                   6750:     my $txt=shift;
                   6751:     $txt=~tr/A-J/0-9/;
                   6752:     $txt=~tr/a-j/0-9/;
                   6753:     $txt=~tr/K-T/0-9/;
                   6754:     $txt=~tr/k-t/0-9/;
                   6755:     $txt=~tr/U-Z/0-5/;
                   6756:     $txt=~tr/u-z/0-5/;
                   6757:     $txt=~s/\D//g;
                   6758:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   6759:     my $total;
                   6760:     foreach my $val (@txts) { $total+=$val; }
                   6761:     if ($_64bit) { $total=(($total<<32)>>32); }
                   6762:     return $total;
                   6763: }
                   6764: 
1.675     albertel 6765: sub digest {
                   6766:     my ($data)=@_;
                   6767:     my $digest=&Digest::MD5::md5($data);
                   6768:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   6769:     my ($e,$f);
                   6770:     {
                   6771:         use integer;
                   6772:         $e=($a+$b);
                   6773:         $f=($c+$d);
                   6774:         if ($_64bit) {
                   6775:             $e=(($e<<32)>>32);
                   6776:             $f=(($f<<32)>>32);
                   6777:         }
                   6778:     }
                   6779:     if (wantarray) {
                   6780: 	return ($e,$f);
                   6781:     } else {
                   6782: 	my $g;
                   6783: 	{
                   6784: 	    use integer;
                   6785: 	    $g=($e+$f);
                   6786: 	    if ($_64bit) {
                   6787: 		$g=(($g<<32)>>32);
                   6788: 	    }
                   6789: 	}
                   6790: 	return $g;
                   6791:     }
                   6792: }
                   6793: 
1.368     albertel 6794: sub latest_rnd_algorithm_id {
1.675     albertel 6795:     return '64bit5';
1.366     albertel 6796: }
1.32      www      6797: 
1.503     albertel 6798: sub get_rand_alg {
                   6799:     my ($courseid)=@_;
1.790     albertel 6800:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 6801:     if ($courseid) {
1.620     albertel 6802: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 6803:     }
                   6804:     return &latest_rnd_algorithm_id();
                   6805: }
                   6806: 
1.562     albertel 6807: sub validCODE {
                   6808:     my ($CODE)=@_;
                   6809:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   6810:     return 0;
                   6811: }
                   6812: 
1.491     albertel 6813: sub getCODE {
1.620     albertel 6814:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 6815:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   6816: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   6817: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 6818: 	return $Apache::lonhomework::history{'resource.CODE'};
                   6819:     }
                   6820:     return undef;
                   6821: }
                   6822: 
1.31      www      6823: sub rndseed {
1.155     albertel 6824:     my ($symb,$courseid,$domain,$username)=@_;
1.366     albertel 6825: 
1.790     albertel 6826:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.155     albertel 6827:     if (!$symb) {
1.366     albertel 6828: 	unless ($symb=$wsymb) { return time; }
                   6829:     }
                   6830:     if (!$courseid) { $courseid=$wcourseid; }
                   6831:     if (!$domain) { $domain=$wdomain; }
                   6832:     if (!$username) { $username=$wusername }
1.503     albertel 6833:     my $which=&get_rand_alg();
1.803     albertel 6834: 
1.491     albertel 6835:     if (defined(&getCODE())) {
1.675     albertel 6836: 	if ($which eq '64bit5') {
                   6837: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   6838: 	} elsif ($which eq '64bit4') {
1.575     albertel 6839: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   6840: 	} else {
                   6841: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   6842: 	}
1.675     albertel 6843:     } elsif ($which eq '64bit5') {
                   6844: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 6845:     } elsif ($which eq '64bit4') {
                   6846: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 6847:     } elsif ($which eq '64bit3') {
                   6848: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 6849:     } elsif ($which eq '64bit2') {
                   6850: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 6851:     } elsif ($which eq '64bit') {
                   6852: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   6853:     }
                   6854:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   6855: }
                   6856: 
                   6857: sub rndseed_32bit {
                   6858:     my ($symb,$courseid,$domain,$username)=@_;
                   6859:     {
                   6860: 	use integer;
                   6861: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   6862: 	my $symbseed=numval($symb) << 22;
                   6863: 	my $namechck=unpack("%32C*",$username) << 17;
                   6864: 	my $nameseed=numval($username) << 12;
                   6865: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   6866: 	my $courseseed=unpack("%32C*",$courseid);
                   6867: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 6868: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6869: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 6870: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 6871: 	return $num;
                   6872:     }
                   6873: }
                   6874: 
                   6875: sub rndseed_64bit {
                   6876:     my ($symb,$courseid,$domain,$username)=@_;
                   6877:     {
                   6878: 	use integer;
                   6879: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   6880: 	my $symbseed=numval($symb) << 10;
                   6881: 	my $namechck=unpack("%32S*",$username);
                   6882: 	
                   6883: 	my $nameseed=numval($username) << 21;
                   6884: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   6885: 	my $courseseed=unpack("%32S*",$courseid);
                   6886: 	
                   6887: 	my $num1=$symbchck+$symbseed+$namechck;
                   6888: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6889: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6890: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 6891: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 6892: 	return "$num1,$num2";
1.155     albertel 6893:     }
1.366     albertel 6894: }
                   6895: 
1.443     albertel 6896: sub rndseed_64bit2 {
                   6897:     my ($symb,$courseid,$domain,$username)=@_;
                   6898:     {
                   6899: 	use integer;
                   6900: 	# strings need to be an even # of cahracters long, it it is odd the
                   6901:         # last characters gets thrown away
                   6902: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6903: 	my $symbseed=numval($symb) << 10;
                   6904: 	my $namechck=unpack("%32S*",$username.' ');
                   6905: 	
                   6906: 	my $nameseed=numval($username) << 21;
1.501     albertel 6907: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6908: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6909: 	
                   6910: 	my $num1=$symbchck+$symbseed+$namechck;
                   6911: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6912: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6913: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 6914: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 6915: 	return "$num1,$num2";
                   6916:     }
                   6917: }
                   6918: 
                   6919: sub rndseed_64bit3 {
                   6920:     my ($symb,$courseid,$domain,$username)=@_;
                   6921:     {
                   6922: 	use integer;
                   6923: 	# strings need to be an even # of cahracters long, it it is odd the
                   6924:         # last characters gets thrown away
                   6925: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6926: 	my $symbseed=numval2($symb) << 10;
                   6927: 	my $namechck=unpack("%32S*",$username.' ');
                   6928: 	
                   6929: 	my $nameseed=numval2($username) << 21;
1.443     albertel 6930: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6931: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6932: 	
                   6933: 	my $num1=$symbchck+$symbseed+$namechck;
                   6934: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6935: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6936: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 6937: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6938: 	
1.503     albertel 6939: 	return "$num1:$num2";
1.443     albertel 6940:     }
                   6941: }
                   6942: 
1.575     albertel 6943: sub rndseed_64bit4 {
                   6944:     my ($symb,$courseid,$domain,$username)=@_;
                   6945:     {
                   6946: 	use integer;
                   6947: 	# strings need to be an even # of cahracters long, it it is odd the
                   6948:         # last characters gets thrown away
                   6949: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6950: 	my $symbseed=numval3($symb) << 10;
                   6951: 	my $namechck=unpack("%32S*",$username.' ');
                   6952: 	
                   6953: 	my $nameseed=numval3($username) << 21;
                   6954: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6955: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6956: 	
                   6957: 	my $num1=$symbchck+$symbseed+$namechck;
                   6958: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6959: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6960: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 6961: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   6962: 	
                   6963: 	return "$num1:$num2";
                   6964:     }
                   6965: }
                   6966: 
1.675     albertel 6967: sub rndseed_64bit5 {
                   6968:     my ($symb,$courseid,$domain,$username)=@_;
                   6969:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   6970:     return "$num1:$num2";
                   6971: }
                   6972: 
1.366     albertel 6973: sub rndseed_CODE_64bit {
                   6974:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 6975:     {
1.366     albertel 6976: 	use integer;
1.443     albertel 6977: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 6978: 	my $symbseed=numval2($symb);
1.491     albertel 6979: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   6980: 	my $CODEseed=numval(&getCODE());
1.443     albertel 6981: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 6982: 	my $num1=$symbseed+$CODEchck;
                   6983: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 6984: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   6985: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 6986: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   6987: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 6988: 	return "$num1:$num2";
1.366     albertel 6989:     }
                   6990: }
                   6991: 
1.575     albertel 6992: sub rndseed_CODE_64bit4 {
                   6993:     my ($symb,$courseid,$domain,$username)=@_;
                   6994:     {
                   6995: 	use integer;
                   6996: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   6997: 	my $symbseed=numval3($symb);
                   6998: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   6999: 	my $CODEseed=numval3(&getCODE());
                   7000: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7001: 	my $num1=$symbseed+$CODEchck;
                   7002: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 7003: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   7004: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 7005: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   7006: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   7007: 	return "$num1:$num2";
                   7008:     }
                   7009: }
                   7010: 
1.675     albertel 7011: sub rndseed_CODE_64bit5 {
                   7012:     my ($symb,$courseid,$domain,$username)=@_;
                   7013:     my $code = &getCODE();
                   7014:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   7015:     return "$num1:$num2";
                   7016: }
                   7017: 
1.366     albertel 7018: sub setup_random_from_rndseed {
                   7019:     my ($rndseed)=@_;
1.503     albertel 7020:     if ($rndseed =~/([,:])/) {
                   7021: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 7022: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   7023:     } else {
                   7024: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 7025:     }
1.36      albertel 7026: }
                   7027: 
1.474     albertel 7028: sub latest_receipt_algorithm_id {
                   7029:     return 'receipt2';
                   7030: }
                   7031: 
1.480     www      7032: sub recunique {
                   7033:     my $fucourseid=shift;
                   7034:     my $unique;
1.620     albertel 7035:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   7036: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      7037:     } else {
                   7038: 	$unique=$perlvar{'lonReceipt'};
                   7039:     }
                   7040:     return unpack("%32C*",$unique);
                   7041: }
                   7042: 
                   7043: sub recprefix {
                   7044:     my $fucourseid=shift;
                   7045:     my $prefix;
1.620     albertel 7046:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   7047: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      7048:     } else {
                   7049: 	$prefix=$perlvar{'lonHostID'};
                   7050:     }
                   7051:     return unpack("%32C*",$prefix);
                   7052: }
                   7053: 
1.76      www      7054: sub ireceipt {
1.474     albertel 7055:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.76      www      7056:     my $cuname=unpack("%32C*",$funame);
                   7057:     my $cudom=unpack("%32C*",$fudom);
                   7058:     my $cucourseid=unpack("%32C*",$fucourseid);
                   7059:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      7060:     my $cunique=&recunique($fucourseid);
1.474     albertel 7061:     my $cpart=unpack("%32S*",$part);
1.480     www      7062:     my $return =&recprefix($fucourseid).'-';
1.620     albertel 7063:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   7064: 	$env{'request.state'} eq 'construct') {
1.790     albertel 7065: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 7066: 			       
                   7067: 	$return.= ($cunique%$cuname+
                   7068: 		   $cunique%$cudom+
                   7069: 		   $cusymb%$cuname+
                   7070: 		   $cusymb%$cudom+
                   7071: 		   $cucourseid%$cuname+
                   7072: 		   $cucourseid%$cudom+
                   7073: 		   $cpart%$cuname+
                   7074: 		   $cpart%$cudom);
                   7075:     } else {
                   7076: 	$return.= ($cunique%$cuname+
                   7077: 		   $cunique%$cudom+
                   7078: 		   $cusymb%$cuname+
                   7079: 		   $cusymb%$cudom+
                   7080: 		   $cucourseid%$cuname+
                   7081: 		   $cucourseid%$cudom);
                   7082:     }
                   7083:     return $return;
1.76      www      7084: }
                   7085: 
                   7086: sub receipt {
1.474     albertel 7087:     my ($part)=@_;
1.790     albertel 7088:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 7089:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      7090: }
1.260     ng       7091: 
1.790     albertel 7092: sub whichuser {
                   7093:     my ($passedsymb)=@_;
                   7094:     my ($symb,$courseid,$domain,$name,$publicuser);
                   7095:     if (defined($env{'form.grade_symb'})) {
                   7096: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   7097: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   7098: 	if (!$allowed &&
                   7099: 	    exists($env{'request.course.sec'}) &&
                   7100: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   7101: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   7102: 			      '/'.$env{'request.course.sec'});
                   7103: 	}
                   7104: 	if ($allowed) {
                   7105: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   7106: 	    $courseid=$tmp_courseid;
                   7107: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   7108: 	    ($name)=&get_env_multiple('form.grade_username');
                   7109: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   7110: 	}
                   7111:     }
                   7112:     if (!$passedsymb) {
                   7113: 	$symb=&symbread();
                   7114:     } else {
                   7115: 	$symb=$passedsymb;
                   7116:     }
                   7117:     $courseid=$env{'request.course.id'};
                   7118:     $domain=$env{'user.domain'};
                   7119:     $name=$env{'user.name'};
                   7120:     if ($name eq 'public' && $domain eq 'public') {
                   7121: 	if (!defined($env{'form.username'})) {
                   7122: 	    $env{'form.username'}.=time.rand(10000000);
                   7123: 	}
                   7124: 	$name.=$env{'form.username'};
                   7125:     }
                   7126:     return ($symb,$courseid,$domain,$name,$publicuser);
                   7127: 
                   7128: }
                   7129: 
1.36      albertel 7130: # ------------------------------------------------------------ Serves up a file
1.472     albertel 7131: # returns either the contents of the file or 
                   7132: # -1 if the file doesn't exist
1.481     raeburn  7133: #
                   7134: # if the target is a file that was uploaded via DOCS, 
                   7135: # a check will be made to see if a current copy exists on the local server,
                   7136: # if it does this will be served, otherwise a copy will be retrieved from
                   7137: # the home server for the course and stored in /home/httpd/html/userfiles on
                   7138: # the local server.   
1.472     albertel 7139: 
1.36      albertel 7140: sub getfile {
1.538     albertel 7141:     my ($file) = @_;
1.609     banghart 7142:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 7143:     &repcopy($file);
                   7144:     return &readfile($file);
                   7145: }
                   7146: 
                   7147: sub repcopy_userfile {
                   7148:     my ($file)=@_;
1.609     banghart 7149:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 7150:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 7151:     my ($cdom,$cnum,$filename) = 
1.811     albertel 7152: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 7153:     my ($info,$rtncode);
                   7154:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   7155:     if (-e "$file") {
                   7156: 	my @fileinfo = stat($file);
                   7157: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 7158: 	if ($lwpresp ne 'ok') {
                   7159: 	    if ($rtncode eq '404') {
1.538     albertel 7160: 		unlink($file);
1.482     albertel 7161: 	    }
1.517     albertel 7162: 	    #my $ua=new LWP::UserAgent;
1.538     albertel 7163: 	    #my $request=new HTTP::Request('GET',&tokenwrapper($uri));
1.517     albertel 7164: 	    #my $response=$ua->request($request);
                   7165: 	    #if ($response->is_success()) {
                   7166: 	#	return $response->content;
                   7167: 	#    } else {
                   7168: 	#	return -1;
                   7169: 	#    }
1.482     albertel 7170: 	    return -1;
                   7171: 	}
                   7172: 	if ($info < $fileinfo[9]) {
1.607     raeburn  7173: 	    return 'ok';
1.482     albertel 7174: 	}
                   7175: 	$info = '';
1.538     albertel 7176: 	$lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 7177: 	if ($lwpresp ne 'ok') {
                   7178: 	    return -1;
                   7179: 	}
                   7180:     } else {
1.538     albertel 7181: 	my $lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 7182: 	if ($lwpresp ne 'ok') {
1.824.2.2  albertel 7183: 	    return -1;
1.482     albertel 7184: 	}
                   7185: 	my @parts = ($cdom,$cnum); 
                   7186: 	if ($filename =~ m|^(.+)/[^/]+$|) {
                   7187: 	    push @parts, split(/\//,$1);
1.518     albertel 7188: 	}
1.538     albertel 7189: 	my $path = $perlvar{'lonDocRoot'}.'/userfiles';
1.482     albertel 7190: 	foreach my $part (@parts) {
                   7191: 	    $path .= '/'.$part;
                   7192: 	    if (!-e $path) {
                   7193: 		mkdir($path,0770);
                   7194: 	    }
                   7195: 	}
                   7196:     }
1.538     albertel 7197:     open(FILE,">$file");
1.482     albertel 7198:     print FILE $info;
                   7199:     close(FILE);
1.607     raeburn  7200:     return 'ok';
1.481     raeburn  7201: }
                   7202: 
1.517     albertel 7203: sub tokenwrapper {
                   7204:     my $uri=shift;
1.552     albertel 7205:     $uri=~s|^http\://([^/]+)||;
                   7206:     $uri=~s|^/||;
1.620     albertel 7207:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 7208:     my $token=$1;
1.552     albertel 7209:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   7210:     if ($udom && $uname && $file) {
                   7211: 	$file=~s|(\?\.*)*$||;
1.620     albertel 7212:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
1.552     albertel 7213:         return 'http://'.$hostname{ &homeserver($uname,$udom)}.'/'.$uri.
1.517     albertel 7214:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   7215:                                '&tokenissued='.$perlvar{'lonHostID'};
                   7216:     } else {
                   7217:         return '/adm/notfound.html';
                   7218:     }
                   7219: }
                   7220: 
1.481     raeburn  7221: sub getuploaded {
                   7222:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   7223:     $uri=~s/^\///;
                   7224:     $uri = 'http://'.$hostname{ &homeserver($cnum,$cdom)}.'/raw/'.$uri;
                   7225:     my $ua=new LWP::UserAgent;
                   7226:     my $request=new HTTP::Request($reqtype,$uri);
                   7227:     my $response=$ua->request($request);
                   7228:     $$rtncode = $response->code;
1.482     albertel 7229:     if (! $response->is_success()) {
                   7230: 	return 'failed';
                   7231:     }      
                   7232:     if ($reqtype eq 'HEAD') {
1.486     www      7233: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 7234:     } elsif ($reqtype eq 'GET') {
                   7235: 	$$info = $response->content;
1.472     albertel 7236:     }
1.482     albertel 7237:     return 'ok';
1.36      albertel 7238: }
                   7239: 
1.481     raeburn  7240: sub readfile {
                   7241:     my $file = shift;
                   7242:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   7243:     my $fh;
                   7244:     open($fh,"<$file");
                   7245:     my $a='';
1.800     albertel 7246:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  7247:     return $a;
                   7248: }
                   7249: 
1.36      albertel 7250: sub filelocation {
1.590     banghart 7251:     my ($dir,$file) = @_;
                   7252:     my $location;
                   7253:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 7254: 
                   7255:     if ($file =~ m-^/adm/-) {
                   7256: 	$file=~s-^/adm/wrapper/-/-;
                   7257: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   7258:     }
1.590     banghart 7259:     if ($file=~m:^/~:) { # is a contruction space reference
                   7260:         $location = $file;
                   7261:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 7262:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 7263: 	# is a correct contruction space reference
                   7264:         $location = $file;
1.609     banghart 7265:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 7266:         my ($udom,$uname,$filename)=
1.811     albertel 7267:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 7268:         my $home=&homeserver($uname,$udom);
                   7269:         my $is_me=0;
                   7270:         my @ids=&current_machine_ids();
                   7271:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   7272:         if ($is_me) {
1.740     www      7273:   	    $location=&propath($udom,$uname).
1.590     banghart 7274:   	      '/userfiles/'.$filename;
                   7275:         } else {
                   7276:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   7277:   	      $udom.'/'.$uname.'/'.$filename;
                   7278:         }
                   7279:     } else {
                   7280:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   7281:         $file=~s:^/res/:/:;
                   7282:         if ( !( $file =~ m:^/:) ) {
                   7283:             $location = $dir. '/'.$file;
                   7284:         } else {
                   7285:             $location = '/home/httpd/html/res'.$file;
                   7286:         }
1.59      albertel 7287:     }
1.590     banghart 7288:     $location=~s://+:/:g; # remove duplicate /
                   7289:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
                   7290:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   7291:     return $location;
1.46      www      7292: }
1.36      albertel 7293: 
1.46      www      7294: sub hreflocation {
                   7295:     my ($dir,$file)=@_;
1.460     albertel 7296:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666     albertel 7297: 	$file=filelocation($dir,$file);
1.700     albertel 7298:     } elsif ($file=~m-^/adm/-) {
                   7299: 	$file=~s-^/adm/wrapper/-/-;
                   7300: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 7301:     }
                   7302:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   7303: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 7304:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   7305: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 7306:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 7307: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 7308: 	    -/uploaded/$1/$2/-x;
1.46      www      7309:     }
1.462     albertel 7310:     return $file;
1.465     albertel 7311: }
                   7312: 
                   7313: sub current_machine_domains {
                   7314:     my $hostname=$hostname{$perlvar{'lonHostID'}};
                   7315:     my @domains;
                   7316:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  7317: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 7318: 	if ($hostname eq $name) {
                   7319: 	    push(@domains,$hostdom{$id});
                   7320: 	}
                   7321:     }
                   7322:     return @domains;
                   7323: }
                   7324: 
                   7325: sub current_machine_ids {
                   7326:     my $hostname=$hostname{$perlvar{'lonHostID'}};
                   7327:     my @ids;
                   7328:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  7329: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 7330: 	if ($hostname eq $name) {
                   7331: 	    push(@ids,$id);
                   7332: 	}
                   7333:     }
                   7334:     return @ids;
1.31      www      7335: }
                   7336: 
1.824     raeburn  7337: sub additional_machine_domains {
                   7338:     my @domains;
                   7339:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   7340:     while( my $line = <$fh>) {
                   7341:         $line =~ s/\s//g;
                   7342:         push(@domains,$line);
                   7343:     }
                   7344:     return @domains;
                   7345: }
                   7346: 
                   7347: sub default_login_domain {
                   7348:     my $domain = $perlvar{'lonDefDomain'};
                   7349:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   7350:     foreach my $posdom (&current_machine_domains(),
                   7351:                         &additional_machine_domains()) {
                   7352:         if (lc($posdom) eq lc($testdomain)) {
                   7353:             $domain=$posdom;
                   7354:             last;
                   7355:         }
                   7356:     }
                   7357:     return $domain;
                   7358: }
                   7359: 
1.31      www      7360: # ------------------------------------------------------------- Declutters URLs
                   7361: 
                   7362: sub declutter {
                   7363:     my $thisfn=shift;
1.569     albertel 7364:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 7365:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      7366:     $thisfn=~s/^\///;
1.697     albertel 7367:     $thisfn=~s|^adm/wrapper/||;
                   7368:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      7369:     $thisfn=~s/^res\///;
1.235     www      7370:     $thisfn=~s/\?.+$//;
1.268     www      7371:     return $thisfn;
                   7372: }
                   7373: 
                   7374: # ------------------------------------------------------------- Clutter up URLs
                   7375: 
                   7376: sub clutter {
                   7377:     my $thisfn='/'.&declutter(shift);
1.609     banghart 7378:     unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) { 
1.270     www      7379:        $thisfn='/res'.$thisfn; 
                   7380:     }
1.694     albertel 7381:     if ($thisfn !~m|/adm|) {
1.695     albertel 7382: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 7383: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 7384: 	} else {
                   7385: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   7386: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 7387: 	    if ($embstyle eq 'ssi'
                   7388: 		|| ($embstyle eq 'hdn')
                   7389: 		|| ($embstyle eq 'rat')
                   7390: 		|| ($embstyle eq 'prv')
                   7391: 		|| ($embstyle eq 'ign')) {
                   7392: 		#do nothing with these
                   7393: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 7394: 		|| ($embstyle eq 'emb')
                   7395: 		|| ($embstyle eq 'wrp')) {
                   7396: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 7397: 	    } elsif ($embstyle eq 'unk'
                   7398: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 7399: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 7400: 	    } else {
1.718     www      7401: #		&logthis("Got a blank emb style");
1.695     albertel 7402: 	    }
1.694     albertel 7403: 	}
                   7404:     }
1.31      www      7405:     return $thisfn;
1.12      www      7406: }
                   7407: 
1.787     albertel 7408: sub clutter_with_no_wrapper {
                   7409:     my $uri = &clutter(shift);
                   7410:     if ($uri =~ m-^/adm/-) {
                   7411: 	$uri =~ s-^/adm/wrapper/-/-;
                   7412: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   7413:     }
                   7414:     return $uri;
                   7415: }
                   7416: 
1.557     albertel 7417: sub freeze_escape {
                   7418:     my ($value)=@_;
                   7419:     if (ref($value)) {
                   7420: 	$value=&nfreeze($value);
                   7421: 	return '__FROZEN__'.&escape($value);
                   7422:     }
                   7423:     return &escape($value);
                   7424: }
                   7425: 
1.11      www      7426: 
1.557     albertel 7427: sub thaw_unescape {
                   7428:     my ($value)=@_;
                   7429:     if ($value =~ /^__FROZEN__/) {
                   7430: 	substr($value,0,10,undef);
                   7431: 	$value=&unescape($value);
                   7432: 	return &thaw($value);
                   7433:     }
                   7434:     return &unescape($value);
                   7435: }
                   7436: 
1.436     albertel 7437: sub correct_line_ends {
                   7438:     my ($result)=@_;
                   7439:     $$result =~s/\r\n/\n/mg;
                   7440:     $$result =~s/\r/\n/mg;
1.415     albertel 7441: }
1.1       albertel 7442: # ================================================================ Main Program
                   7443: 
1.184     www      7444: sub goodbye {
1.204     albertel 7445:    &logthis("Starting Shut down");
1.443     albertel 7446: #not converted to using infrastruture and probably shouldn't be
1.599     albertel 7447:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&freeze(\%badServerCache))));
1.443     albertel 7448: #converted
1.599     albertel 7449: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
                   7450:    &logthis(sprintf("%-20s is %s",'%homecache',length(&freeze(\%homecache))));
                   7451: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&freeze(\%titlecache))));
                   7452: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&freeze(\%courseresdatacache))));
1.425     albertel 7453: #1.1 only
1.599     albertel 7454: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&freeze(\%userresdatacache))));
                   7455: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&freeze(\%getsectioncache))));
                   7456: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&freeze(\%courseresversioncache))));
                   7457: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&freeze(\%resversioncache))));
                   7458:    &logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
                   7459:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   7460:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      7461:    &flushcourselogs();
                   7462:    &logthis("Shutting down");
                   7463: }
                   7464: 
1.179     www      7465: BEGIN {
1.228     harris41 7466: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
1.195     www      7467:     unless ($readit) {
1.217     harris41 7468: {
1.781     raeburn  7469:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   7470:     %perlvar = (%perlvar,%{$configvars});
1.227     harris41 7471: }
1.1       albertel 7472: 
1.327     albertel 7473: # ------------------------------------------------------------ Read domain file
                   7474: {
                   7475:     %domaindescription = ();
                   7476:     %domain_auth_def = ();
                   7477:     %domain_auth_arg_def = ();
1.448     albertel 7478:     my $fh;
                   7479:     if (open($fh,"<".$Apache::lonnet::perlvar{'lonTabDir'}.'/domain.tab')) {
1.800     albertel 7480: 	while (my $line = <$fh>) {
                   7481:            next if ($line =~ /^(\#|\s*$)/);
1.390     matthew  7482: #           next if /^\#/;
1.801     foxr     7483:            chomp $line;
1.403     www      7484:            my ($domain, $domain_description, $def_auth, $def_auth_arg,
1.800     albertel 7485: 	       $def_lang, $city, $longi, $lati, $primary) = split(/:/,$line,9);
1.403     www      7486: 	   $domain_auth_def{$domain}=$def_auth;
1.327     albertel 7487:            $domain_auth_arg_def{$domain}=$def_auth_arg;
1.403     www      7488: 	   $domaindescription{$domain}=$domain_description;
                   7489: 	   $domain_lang_def{$domain}=$def_lang;
                   7490: 	   $domain_city{$domain}=$city;
                   7491: 	   $domain_longi{$domain}=$longi;
                   7492: 	   $domain_lati{$domain}=$lati;
1.685     raeburn  7493:            $domain_primary{$domain}=$primary;
1.403     www      7494: 
1.448     albertel 7495:  #         &logthis("Domain.tab: $domain, $domain_auth_def{$domain}, $domain_auth_arg_def{$domain},$domaindescription{$domain}");
1.327     albertel 7496: #          &logthis("Domain.tab: $domain ".$domaindescription{$domain} );
1.448     albertel 7497: 	}
1.327     albertel 7498:     }
1.448     albertel 7499:     close ($fh);
1.327     albertel 7500: }
                   7501: 
                   7502: 
1.1       albertel 7503: # ------------------------------------------------------------- Read hosts file
                   7504: {
1.448     albertel 7505:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
1.1       albertel 7506: 
                   7507:     while (my $configline=<$config>) {
1.303     matthew  7508:        next if ($configline =~ /^(\#|\s*$)/);
1.154     www      7509:        chomp($configline);
1.595     albertel 7510:        my ($id,$domain,$role,$name)=split(/:/,$configline);
1.597     albertel 7511:        $name=~s/\s//g;
1.595     albertel 7512:        if ($id && $domain && $role && $name) {
1.252     albertel 7513: 	 $hostname{$id}=$name;
                   7514: 	 $hostdom{$id}=$domain;
                   7515: 	 if ($role eq 'library') { $libserv{$id}=$name; }
1.245     www      7516:        }
1.1       albertel 7517:     }
1.448     albertel 7518:     close($config);
1.619     albertel 7519:     # FIXME: dev server don't want this, production servers _do_ want this
1.654     albertel 7520:     #&get_iphost();
1.1       albertel 7521: }
                   7522: 
1.598     albertel 7523: sub get_iphost {
                   7524:     if (%iphost) { return %iphost; }
1.653     albertel 7525:     my %name_to_ip;
1.598     albertel 7526:     foreach my $id (keys(%hostname)) {
                   7527: 	my $name=$hostname{$id};
1.653     albertel 7528: 	my $ip;
                   7529: 	if (!exists($name_to_ip{$name})) {
                   7530: 	    $ip = gethostbyname($name);
                   7531: 	    if (!$ip || length($ip) ne 4) {
                   7532: 		&logthis("Skipping host $id name $name no IP found\n");
                   7533: 		next;
                   7534: 	    }
                   7535: 	    $ip=inet_ntoa($ip);
                   7536: 	    $name_to_ip{$name} = $ip;
                   7537: 	} else {
                   7538: 	    $ip = $name_to_ip{$name};
1.598     albertel 7539: 	}
                   7540: 	push(@{$iphost{$ip}},$id);
                   7541:     }
                   7542:     return %iphost;
                   7543: }
                   7544: 
1.1       albertel 7545: # ------------------------------------------------------ Read spare server file
                   7546: {
1.448     albertel 7547:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 7548: 
                   7549:     while (my $configline=<$config>) {
                   7550:        chomp($configline);
1.284     matthew  7551:        if ($configline) {
1.784     albertel 7552: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 7553: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 7554: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 7555:        }
                   7556:     }
1.448     albertel 7557:     close($config);
1.1       albertel 7558: }
1.11      www      7559: # ------------------------------------------------------------ Read permissions
                   7560: {
1.448     albertel 7561:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      7562: 
                   7563:     while (my $configline=<$config>) {
1.448     albertel 7564: 	chomp($configline);
                   7565: 	if ($configline) {
                   7566: 	    my ($role,$perm)=split(/ /,$configline);
                   7567: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   7568: 	}
1.11      www      7569:     }
1.448     albertel 7570:     close($config);
1.11      www      7571: }
                   7572: 
                   7573: # -------------------------------------------- Read plain texts for permissions
                   7574: {
1.448     albertel 7575:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      7576: 
                   7577:     while (my $configline=<$config>) {
1.448     albertel 7578: 	chomp($configline);
                   7579: 	if ($configline) {
1.742     raeburn  7580: 	    my ($short,@plain)=split(/:/,$configline);
                   7581:             %{$prp{$short}} = ();
                   7582: 	    if (@plain > 0) {
                   7583:                 $prp{$short}{'std'} = $plain[0];
                   7584:                 for (my $i=1; $i<@plain; $i++) {
                   7585:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   7586:                 }
                   7587:             }
1.448     albertel 7588: 	}
1.135     www      7589:     }
1.448     albertel 7590:     close($config);
1.135     www      7591: }
                   7592: 
                   7593: # ---------------------------------------------------------- Read package table
                   7594: {
1.448     albertel 7595:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      7596: 
                   7597:     while (my $configline=<$config>) {
1.483     albertel 7598: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 7599: 	chomp($configline);
                   7600: 	my ($short,$plain)=split(/:/,$configline);
                   7601: 	my ($pack,$name)=split(/\&/,$short);
                   7602: 	if ($plain ne '') {
                   7603: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   7604: 	    $packagetab{$short}=$plain; 
                   7605: 	}
1.11      www      7606:     }
1.448     albertel 7607:     close($config);
1.329     matthew  7608: }
                   7609: 
                   7610: # ------------- set up temporary directory
                   7611: {
                   7612:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   7613: 
1.11      www      7614: }
                   7615: 
1.794     albertel 7616: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   7617: 				'compress_threshold'=> 20_000,
                   7618:  			        });
1.185     www      7619: 
1.281     www      7620: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      7621: $dumpcount=0;
1.22      www      7622: 
1.163     harris41 7623: &logtouch();
1.672     albertel 7624: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      7625: $readit=1;
1.564     albertel 7626:     {
                   7627: 	use integer;
                   7628: 	my $test=(2**32)+1;
1.568     albertel 7629: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 7630: 	&logthis(" Detected 64bit platform ($_64bit)");
                   7631:     }
1.195     www      7632: }
1.1       albertel 7633: }
1.179     www      7634: 
1.1       albertel 7635: 1;
1.191     harris41 7636: __END__
                   7637: 
1.243     albertel 7638: =pod
                   7639: 
1.191     harris41 7640: =head1 NAME
                   7641: 
1.243     albertel 7642: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 7643: 
                   7644: =head1 SYNOPSIS
                   7645: 
1.243     albertel 7646: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 7647: 
                   7648:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   7649: 
1.243     albertel 7650: Common parameters:
                   7651: 
                   7652: =over 4
                   7653: 
                   7654: =item *
                   7655: 
                   7656: $uname : an internal username (if $cname expecting a course Id specifically)
                   7657: 
                   7658: =item *
                   7659: 
                   7660: $udom : a domain (if $cdom expecting a course's domain specifically)
                   7661: 
                   7662: =item *
                   7663: 
                   7664: $symb : a resource instance identifier
                   7665: 
                   7666: =item *
                   7667: 
                   7668: $namespace : the name of a .db file that contains the data needed or
                   7669: being set.
                   7670: 
                   7671: =back
                   7672: 
1.394     bowersj2 7673: =head1 OVERVIEW
1.191     harris41 7674: 
1.394     bowersj2 7675: lonnet provides subroutines which interact with the
                   7676: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   7677: about classes, users, and resources.
1.243     albertel 7678: 
                   7679: For many of these objects you can also use this to store data about
                   7680: them or modify them in various ways.
1.191     harris41 7681: 
1.394     bowersj2 7682: =head2 Symbs
1.191     harris41 7683: 
1.394     bowersj2 7684: To identify a specific instance of a resource, LON-CAPA uses symbols
                   7685: or "symbs"X<symb>. These identifiers are built from the URL of the
                   7686: map, the resource number of the resource in the map, and the URL of
                   7687: the resource itself. The latter is somewhat redundant, but might help
                   7688: if maps change.
                   7689: 
                   7690: An example is
                   7691: 
                   7692:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   7693: 
                   7694: The respective map entry is
                   7695: 
                   7696:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   7697:   title="Problem 2">
                   7698:  </resource>
                   7699: 
                   7700: Symbs are used by the random number generator, as well as to store and
                   7701: restore data specific to a certain instance of for example a problem.
                   7702: 
                   7703: =head2 Storing And Retrieving Data
                   7704: 
                   7705: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   7706: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   7707: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   7708: is is the non-critical message twin of cstore. These functions are for
                   7709: handlers to store a perl hash to a user's permanent data space in an
                   7710: easy manner, and to retrieve it again on another call. It is expected
                   7711: that a handler would use this once at the beginning to retrieve data,
                   7712: and then again once at the end to send only the new data back.
                   7713: 
                   7714: The data is stored in the user's data directory on the user's
                   7715: homeserver under the ID of the course.
                   7716: 
                   7717: The hash that is returned by restore will have all of the previous
                   7718: value for all of the elements of the hash.
                   7719: 
                   7720: Example:
                   7721: 
                   7722:  #creating a hash
                   7723:  my %hash;
                   7724:  $hash{'foo'}='bar';
                   7725: 
                   7726:  #storing it
                   7727:  &Apache::lonnet::cstore(\%hash);
                   7728: 
                   7729:  #changing a value
                   7730:  $hash{'foo'}='notbar';
                   7731: 
                   7732:  #adding a new value
                   7733:  $hash{'bar'}='foo';
                   7734:  &Apache::lonnet::cstore(\%hash);
                   7735: 
                   7736:  #retrieving the hash
                   7737:  my %history=&Apache::lonnet::restore();
                   7738: 
                   7739:  #print the hash
                   7740:  foreach my $key (sort(keys(%history))) {
                   7741:    print("\%history{$key} = $history{$key}");
                   7742:  }
                   7743: 
                   7744: Will print out:
1.191     harris41 7745: 
1.394     bowersj2 7746:  %history{1:foo} = bar
                   7747:  %history{1:keys} = foo:timestamp
                   7748:  %history{1:timestamp} = 990455579
                   7749:  %history{2:bar} = foo
                   7750:  %history{2:foo} = notbar
                   7751:  %history{2:keys} = foo:bar:timestamp
                   7752:  %history{2:timestamp} = 990455580
                   7753:  %history{bar} = foo
                   7754:  %history{foo} = notbar
                   7755:  %history{timestamp} = 990455580
                   7756:  %history{version} = 2
                   7757: 
                   7758: Note that the special hash entries C<keys>, C<version> and
                   7759: C<timestamp> were added to the hash. C<version> will be equal to the
                   7760: total number of versions of the data that have been stored. The
                   7761: C<timestamp> attribute will be the UNIX time the hash was
                   7762: stored. C<keys> is available in every historical section to list which
                   7763: keys were added or changed at a specific historical revision of a
                   7764: hash.
                   7765: 
                   7766: B<Warning>: do not store the hash that restore returns directly. This
                   7767: will cause a mess since it will restore the historical keys as if the
                   7768: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 7769: 
1.394     bowersj2 7770: Calling convention:
1.191     harris41 7771: 
1.394     bowersj2 7772:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   7773:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 7774: 
1.394     bowersj2 7775: For more detailed information, see lonnet specific documentation.
1.191     harris41 7776: 
1.394     bowersj2 7777: =head1 RETURN MESSAGES
1.191     harris41 7778: 
1.394     bowersj2 7779: =over 4
1.191     harris41 7780: 
1.394     bowersj2 7781: =item * B<con_lost>: unable to contact remote host
1.191     harris41 7782: 
1.394     bowersj2 7783: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   7784: when the connection is brought back up
1.191     harris41 7785: 
1.394     bowersj2 7786: =item * B<con_failed>: unable to contact remote host and unable to save message
                   7787: for later delivery
1.191     harris41 7788: 
1.394     bowersj2 7789: =item * B<error:>: an error a occured, a description of the error follows the :
1.191     harris41 7790: 
1.394     bowersj2 7791: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 7792: that was requested
1.191     harris41 7793: 
1.243     albertel 7794: =back
1.191     harris41 7795: 
1.243     albertel 7796: =head1 PUBLIC SUBROUTINES
1.191     harris41 7797: 
1.243     albertel 7798: =head2 Session Environment Functions
1.191     harris41 7799: 
1.243     albertel 7800: =over 4
1.191     harris41 7801: 
1.394     bowersj2 7802: =item * 
                   7803: X<appenv()>
                   7804: B<appenv(%hash)>: the value of %hash is written to
                   7805: the user envirnoment file, and will be restored for each access this
1.620     albertel 7806: user makes during this session, also modifies the %env for the current
1.394     bowersj2 7807: process
1.191     harris41 7808: 
                   7809: =item *
1.394     bowersj2 7810: X<delenv()>
                   7811: B<delenv($regexp)>: removes all items from the session
                   7812: environment file that matches the regular expression in $regexp. The
1.620     albertel 7813: values are also delted from the current processes %env.
1.191     harris41 7814: 
1.795     albertel 7815: =item * get_env_multiple($name) 
                   7816: 
                   7817: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   7818: values may be defined and end up as an array ref.
                   7819: 
                   7820: returns an array of values
                   7821: 
1.243     albertel 7822: =back
                   7823: 
                   7824: =head2 User Information
1.191     harris41 7825: 
1.243     albertel 7826: =over 4
1.191     harris41 7827: 
                   7828: =item *
1.394     bowersj2 7829: X<queryauthenticate()>
                   7830: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 7831: authentication scheme
                   7832: 
                   7833: =item *
1.394     bowersj2 7834: X<authenticate()>
                   7835: B<authenticate($uname,$upass,$udom)>: try to
                   7836: authenticate user from domain's lib servers (first use the current
                   7837: one). C<$upass> should be the users password.
1.191     harris41 7838: 
                   7839: =item *
1.394     bowersj2 7840: X<homeserver()>
                   7841: B<homeserver($uname,$udom)>: find the server which has
                   7842: the user's directory and files (there must be only one), this caches
                   7843: the answer, and also caches if there is a borken connection.
1.191     harris41 7844: 
                   7845: =item *
1.394     bowersj2 7846: X<idget()>
                   7847: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   7848: (IDs are a unique resource in a domain, there must be only 1 ID per
                   7849: username, and only 1 username per ID in a specific domain) (returns
                   7850: hash: id=>name,id=>name)
1.191     harris41 7851: 
                   7852: =item *
1.394     bowersj2 7853: X<idrget()>
                   7854: B<idrget($udom,@unames)>: find the IDs behind a list of
                   7855: usernames (returns hash: name=>id,name=>id)
1.191     harris41 7856: 
                   7857: =item *
1.394     bowersj2 7858: X<idput()>
                   7859: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 7860: 
                   7861: =item *
1.394     bowersj2 7862: X<rolesinit()>
                   7863: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 7864: 
                   7865: =item *
1.551     albertel 7866: X<getsection()>
                   7867: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 7868: course $cname, return section name/number or '' for "not in course"
                   7869: and '-1' for "no section"
                   7870: 
                   7871: =item *
1.394     bowersj2 7872: X<userenvironment()>
                   7873: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 7874: passed in @what from the requested user's environment, returns a hash
                   7875: 
                   7876: =back
                   7877: 
                   7878: =head2 User Roles
                   7879: 
                   7880: =over 4
                   7881: 
                   7882: =item *
                   7883: 
1.810     raeburn  7884: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 7885:  F: full access
                   7886:  U,I,K: authentication modes (cxx only)
                   7887:  '': forbidden
                   7888:  1: user needs to choose course
                   7889:  2: browse allowed
1.766     albertel 7890:  A: passphrase authentication needed
1.243     albertel 7891: 
                   7892: =item *
                   7893: 
                   7894: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   7895: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   7896: and course level
                   7897: 
                   7898: =item *
                   7899: 
                   7900: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   7901: explanation of a user role term
                   7902: 
                   7903: =back
                   7904: 
                   7905: =head2 User Modification
                   7906: 
                   7907: =over 4
                   7908: 
                   7909: =item *
                   7910: 
                   7911: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
                   7912: user for the level given by URL.  Optional start and end dates (leave empty
                   7913: string or zero for "no date")
1.191     harris41 7914: 
                   7915: =item *
                   7916: 
1.243     albertel 7917: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   7918: change a users, password, possible return values are: ok,
                   7919: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   7920: refused
1.191     harris41 7921: 
                   7922: =item *
                   7923: 
1.243     albertel 7924: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 7925: 
                   7926: =item *
                   7927: 
1.243     albertel 7928: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
                   7929: modify user
1.191     harris41 7930: 
                   7931: =item *
                   7932: 
1.286     matthew  7933: modifystudent
                   7934: 
                   7935: modify a students enrollment and identification information.
                   7936: The course id is resolved based on the current users environment.  
                   7937: This means the envoking user must be a course coordinator or otherwise
                   7938: associated with a course.
                   7939: 
1.297     matthew  7940: This call is essentially a wrapper for lonnet::modifyuser and
                   7941: lonnet::modify_student_enrollment
1.286     matthew  7942: 
                   7943: Inputs: 
                   7944: 
                   7945: =over 4
                   7946: 
                   7947: =item B<$udom> Students loncapa domain
                   7948: 
                   7949: =item B<$uname> Students loncapa login name
                   7950: 
                   7951: =item B<$uid> Students id/student number
                   7952: 
                   7953: =item B<$umode> Students authentication mode
                   7954: 
                   7955: =item B<$upass> Students password
                   7956: 
                   7957: =item B<$first> Students first name
                   7958: 
                   7959: =item B<$middle> Students middle name
                   7960: 
                   7961: =item B<$last> Students last name
                   7962: 
                   7963: =item B<$gene> Students generation
                   7964: 
                   7965: =item B<$usec> Students section in course
                   7966: 
                   7967: =item B<$end> Unix time of the roles expiration
                   7968: 
                   7969: =item B<$start> Unix time of the roles start date
                   7970: 
                   7971: =item B<$forceid> If defined, allow $uid to be changed
                   7972: 
                   7973: =item B<$desiredhome> server to use as home server for student
                   7974: 
                   7975: =back
1.297     matthew  7976: 
                   7977: =item *
                   7978: 
                   7979: modify_student_enrollment
                   7980: 
                   7981: Change a students enrollment status in a class.  The environment variable
                   7982: 'role.request.course' must be defined for this function to proceed.
                   7983: 
                   7984: Inputs:
                   7985: 
                   7986: =over 4
                   7987: 
                   7988: =item $udom, students domain
                   7989: 
                   7990: =item $uname, students name
                   7991: 
                   7992: =item $uid, students user id
                   7993: 
                   7994: =item $first, students first name
                   7995: 
                   7996: =item $middle
                   7997: 
                   7998: =item $last
                   7999: 
                   8000: =item $gene
                   8001: 
                   8002: =item $usec
                   8003: 
                   8004: =item $end
                   8005: 
                   8006: =item $start
                   8007: 
                   8008: =back
                   8009: 
1.191     harris41 8010: 
                   8011: =item *
                   8012: 
1.243     albertel 8013: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   8014: custom role; give a custom role to a user for the level given by URL.  Specify
                   8015: name and domain of role author, and role name
1.191     harris41 8016: 
                   8017: =item *
                   8018: 
1.243     albertel 8019: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 8020: 
                   8021: =item *
                   8022: 
1.243     albertel 8023: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   8024: 
                   8025: =back
                   8026: 
                   8027: =head2 Course Infomation
                   8028: 
                   8029: =over 4
1.191     harris41 8030: 
                   8031: =item *
                   8032: 
1.631     albertel 8033: coursedescription($courseid) : returns a hash of information about the
                   8034: specified course id, including all environment settings for the
                   8035: course, the description of the course will be in the hash under the
                   8036: key 'description'
1.191     harris41 8037: 
                   8038: =item *
                   8039: 
1.624     albertel 8040: resdata($name,$domain,$type,@which) : request for current parameter
                   8041: setting for a specific $type, where $type is either 'course' or 'user',
                   8042: @what should be a list of parameters to ask about. This routine caches
                   8043: answers for 5 minutes.
1.243     albertel 8044: 
                   8045: =back
                   8046: 
                   8047: =head2 Course Modification
                   8048: 
                   8049: =over 4
1.191     harris41 8050: 
                   8051: =item *
                   8052: 
1.243     albertel 8053: writecoursepref($courseid,%prefs) : write preferences (environment
                   8054: database) for a course
1.191     harris41 8055: 
                   8056: =item *
                   8057: 
1.243     albertel 8058: createcourse($udom,$description,$url) : make/modify course
                   8059: 
                   8060: =back
                   8061: 
                   8062: =head2 Resource Subroutines
                   8063: 
                   8064: =over 4
1.191     harris41 8065: 
                   8066: =item *
                   8067: 
1.243     albertel 8068: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 8069: 
                   8070: =item *
                   8071: 
1.243     albertel 8072: repcopy($filename) : subscribes to the requested file, and attempts to
                   8073: replicate from the owning library server, Might return
1.607     raeburn  8074: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   8075: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 8076: resource. Expects the local filesystem pathname
                   8077: (/home/httpd/html/res/....)
                   8078: 
                   8079: =back
                   8080: 
                   8081: =head2 Resource Information
                   8082: 
                   8083: =over 4
1.191     harris41 8084: 
                   8085: =item *
                   8086: 
1.243     albertel 8087: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   8088: a vairety of different possible values, $varname should be a request
                   8089: string, and the other parameters can be used to specify who and what
                   8090: one is asking about.
                   8091: 
                   8092: Possible values for $varname are environment.lastname (or other item
                   8093: from the envirnment hash), user.name (or someother aspect about the
                   8094: user), resource.0.maxtries (or some other part and parameter of a
                   8095: resource)
1.204     albertel 8096: 
                   8097: =item *
                   8098: 
1.243     albertel 8099: directcondval($number) : get current value of a condition; reads from a state
                   8100: string
1.204     albertel 8101: 
                   8102: =item *
                   8103: 
1.243     albertel 8104: condval($condidx) : value of condition index based on state
1.204     albertel 8105: 
                   8106: =item *
                   8107: 
1.243     albertel 8108: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   8109: resource's metadata, $what should be either a specific key, or either
                   8110: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   8111: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   8112: 
                   8113: this function automatically caches all requests
1.191     harris41 8114: 
                   8115: =item *
                   8116: 
1.243     albertel 8117: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   8118: network of library servers; returns file handle of where SQL and regex results
                   8119: will be stored for query
1.191     harris41 8120: 
                   8121: =item *
                   8122: 
1.243     albertel 8123: symbread($filename) : return symbolic list entry (filename argument optional);
                   8124: returns the data handle
1.191     harris41 8125: 
                   8126: =item *
                   8127: 
1.243     albertel 8128: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 8129: a possible symb for the URL in $thisfn, and if is an encryypted
                   8130: resource that the user accessed using /enc/ returns a 1 on success, 0
                   8131: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 8132: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 8133: 
1.191     harris41 8134: 
                   8135: =item *
                   8136: 
1.243     albertel 8137: symbclean($symb) : removes versions numbers from a symb, returns the
                   8138: cleaned symb
1.191     harris41 8139: 
                   8140: =item *
                   8141: 
1.243     albertel 8142: is_on_map($uri) : checks if the $uri is somewhere on the current
                   8143: course map, user must be in a course for it to work.
1.191     harris41 8144: 
                   8145: =item *
                   8146: 
1.243     albertel 8147: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 8148: 
                   8149: =item *
                   8150: 
1.243     albertel 8151: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   8152: a random seed, all arguments are optional, if they aren't sent it uses the
                   8153: environment to derive them. Note: if symb isn't sent and it can't get one
                   8154: from &symbread it will use the current time as its return value
1.191     harris41 8155: 
                   8156: =item *
                   8157: 
1.243     albertel 8158: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   8159: unfakeable, receipt
1.191     harris41 8160: 
                   8161: =item *
                   8162: 
1.620     albertel 8163: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 8164: 
                   8165: =item *
                   8166: 
1.243     albertel 8167: countacc($url) : count the number of accesses to a given URL
1.191     harris41 8168: 
                   8169: =item *
                   8170: 
1.243     albertel 8171: 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 8172: 
                   8173: =item *
                   8174: 
1.243     albertel 8175: 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 8176: 
                   8177: =item *
                   8178: 
1.243     albertel 8179: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 8180: 
                   8181: =item *
                   8182: 
1.243     albertel 8183: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   8184: forcing spreadsheet to reevaluate the resource scores next time.
                   8185: 
                   8186: =back
                   8187: 
                   8188: =head2 Storing/Retreiving Data
                   8189: 
                   8190: =over 4
1.191     harris41 8191: 
                   8192: =item *
                   8193: 
1.243     albertel 8194: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   8195: for this url; hashref needs to be given and should be a \%hashname; the
                   8196: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 8197: be derived from the env
1.191     harris41 8198: 
                   8199: =item *
                   8200: 
1.243     albertel 8201: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   8202: uses critical subroutine
1.191     harris41 8203: 
                   8204: =item *
                   8205: 
1.243     albertel 8206: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   8207: all args are optional
1.191     harris41 8208: 
                   8209: =item *
                   8210: 
1.717     albertel 8211: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   8212: dumps the complete (or key matching regexp) namespace into a hash
                   8213: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   8214: normally &store()ed into
                   8215: 
                   8216: $range should be either an integer '100' (give me the first 100
                   8217:                                            matching records)
                   8218:               or be  two integers sperated by a - with no spaces
                   8219:                  '30-50' (give me the 30th through the 50th matching
                   8220:                           records)
                   8221: 
                   8222: 
                   8223: =item *
                   8224: 
                   8225: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   8226: replaces a &store() version of data with a replacement set of data
                   8227: for a particular resource in a namespace passed in the $storehash hash 
                   8228: reference
                   8229: 
                   8230: =item *
                   8231: 
1.243     albertel 8232: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   8233: works very similar to store/cstore, but all data is stored in a
                   8234: temporary location and can be reset using tmpreset, $storehash should
                   8235: be a hash reference, returns nothing on success
1.191     harris41 8236: 
                   8237: =item *
                   8238: 
1.243     albertel 8239: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   8240: similar to restore, but all data is stored in a temporary location and
                   8241: can be reset using tmpreset. Returns a hash of values on success,
                   8242: error string otherwise.
1.191     harris41 8243: 
                   8244: =item *
                   8245: 
1.243     albertel 8246: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   8247: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 8248: 
                   8249: =item *
                   8250: 
1.243     albertel 8251: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   8252: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 8253: 
                   8254: =item *
                   8255: 
1.243     albertel 8256: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   8257: namesp ($udom and $uname are optional)
1.191     harris41 8258: 
                   8259: =item *
                   8260: 
1.702     albertel 8261: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 8262: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 8263: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  8264: 
1.702     albertel 8265: $range should be either an integer '100' (give me the first 100
                   8266:                                            matching records)
                   8267:               or be  two integers sperated by a - with no spaces
                   8268:                  '30-50' (give me the 30th through the 50th matching
                   8269:                           records)
1.449     matthew  8270: =item *
                   8271: 
                   8272: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   8273: $store can be a scalar, an array reference, or if the amount to be 
                   8274: incremented is > 1, a hash reference.
                   8275: 
                   8276: ($udom and $uname are optional)
1.191     harris41 8277: 
                   8278: =item *
                   8279: 
1.243     albertel 8280: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   8281: ($udom and $uname are optional)
1.191     harris41 8282: 
                   8283: =item *
                   8284: 
1.243     albertel 8285: cput($namespace,$storehash,$udom,$uname) : critical put
                   8286: ($udom and $uname are optional)
1.191     harris41 8287: 
                   8288: =item *
                   8289: 
1.748     albertel 8290: newput($namespace,$storehash,$udom,$uname) :
                   8291: 
                   8292: Attempts to store the items in the $storehash, but only if they don't
                   8293: currently exist, if this succeeds you can be certain that you have 
                   8294: successfully created a new key value pair in the $namespace db.
                   8295: 
                   8296: 
                   8297: Args:
                   8298:  $namespace: name of database to store values to
                   8299:  $storehash: hashref to store to the db
                   8300:  $udom: (optional) domain of user containing the db
                   8301:  $uname: (optional) name of user caontaining the db
                   8302: 
                   8303: Returns:
                   8304:  'ok' -> succeeded in storing all keys of $storehash
                   8305:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   8306:                         least <key> already existed in the db (other
                   8307:                         requested keys may also already exist)
                   8308:  'error: <msg>' -> unable to tie the DB or other erorr occured
                   8309:  'con_lost' -> unable to contact request server
                   8310:  'refused' -> action was not allowed by remote machine
                   8311: 
                   8312: 
                   8313: =item *
                   8314: 
1.243     albertel 8315: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   8316: reference filled in from namesp (encrypts the return communication)
                   8317: ($udom and $uname are optional)
1.191     harris41 8318: 
                   8319: =item *
                   8320: 
1.243     albertel 8321: log($udom,$name,$home,$message) : write to permanent log for user; use
                   8322: critical subroutine
                   8323: 
1.806     raeburn  8324: =item *
                   8325: 
                   8326: get_dom($namespace,$storearr,$udomain) : returns hash with keys from array
                   8327: reference filled in from namespace found in domain level on primary domain server ($udomain is optional)
                   8328: 
                   8329: =item *
                   8330: 
                   8331: put_dom($namespace,$storehash,$udomain) :  stores hash in namespace at domain level on primary domain server ($udomain is optional)
                   8332: 
1.243     albertel 8333: =back
                   8334: 
                   8335: =head2 Network Status Functions
                   8336: 
                   8337: =over 4
1.191     harris41 8338: 
                   8339: =item *
                   8340: 
                   8341: dirlist($uri) : return directory list based on URI
                   8342: 
                   8343: =item *
                   8344: 
1.243     albertel 8345: spareserver() : find server with least workload from spare.tab
                   8346: 
                   8347: =back
                   8348: 
                   8349: =head2 Apache Request
                   8350: 
                   8351: =over 4
1.191     harris41 8352: 
                   8353: =item *
                   8354: 
1.243     albertel 8355: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   8356: localhost, posts hash
                   8357: 
                   8358: =back
                   8359: 
                   8360: =head2 Data to String to Data
                   8361: 
                   8362: =over 4
1.191     harris41 8363: 
                   8364: =item *
                   8365: 
1.243     albertel 8366: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   8367: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 8368: 
                   8369: =item *
                   8370: 
1.243     albertel 8371: hashref2str($hashref) : convert a hashref into a string complete with
                   8372: escaping and '=' and '&' separators, supports elements that are
                   8373: arrayrefs and hashrefs
1.191     harris41 8374: 
                   8375: =item *
                   8376: 
1.243     albertel 8377: arrayref2str($arrayref) : convert an arrayref into a string complete
                   8378: with escaping and '&' separators, supports elements that are arrayrefs
                   8379: and hashrefs
1.191     harris41 8380: 
                   8381: =item *
                   8382: 
1.243     albertel 8383: str2hash($string) : convert string to hash using unescaping and
                   8384: splitting on '=' and '&', supports elements that are arrayrefs and
                   8385: hashrefs
1.191     harris41 8386: 
                   8387: =item *
                   8388: 
1.243     albertel 8389: str2array($string) : convert string to hash using unescaping and
                   8390: splitting on '&', supports elements that are arrayrefs and hashrefs
                   8391: 
                   8392: =back
                   8393: 
                   8394: =head2 Logging Routines
                   8395: 
                   8396: =over 4
                   8397: 
                   8398: These routines allow one to make log messages in the lonnet.log and
                   8399: lonnet.perm logfiles.
1.191     harris41 8400: 
                   8401: =item *
                   8402: 
1.243     albertel 8403: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 8404: 
                   8405: =item *
                   8406: 
1.243     albertel 8407: logthis() : append message to the normal lonnet.log file, it gets
                   8408: preiodically rolled over and deleted.
1.191     harris41 8409: 
                   8410: =item *
                   8411: 
1.243     albertel 8412: logperm() : append a permanent message to lonnet.perm.log, this log
                   8413: file never gets deleted by any automated portion of the system, only
                   8414: messages of critical importance should go in here.
                   8415: 
                   8416: =back
                   8417: 
                   8418: =head2 General File Helper Routines
                   8419: 
                   8420: =over 4
1.191     harris41 8421: 
                   8422: =item *
                   8423: 
1.481     raeburn  8424: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   8425: (a) files in /uploaded
                   8426:   (i) If a local copy of the file exists - 
                   8427:       compares modification date of local copy with last-modified date for 
                   8428:       definitive version stored on home server for course. If local copy is 
                   8429:       stale, requests a new version from the home server and stores it. 
                   8430:       If the original has been removed from the home server, then local copy 
                   8431:       is unlinked.
                   8432:   (ii) If local copy does not exist -
                   8433:       requests the file from the home server and stores it. 
                   8434:   
                   8435:   If $caller is 'uploadrep':  
                   8436:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   8437:     for request for files originally uploaded via DOCS. 
                   8438:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   8439:   
                   8440:   Otherwise:
                   8441:      This indicates a call from the content generation phase of the request.
                   8442:      -  returns the entire contents of the file or -1.
                   8443:      
                   8444: (b) files in /res
                   8445:    - returns the entire contents of a file or -1; 
                   8446:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 8447: 
1.712     albertel 8448: 
                   8449: =item *
                   8450: 
                   8451: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   8452:                   reference
                   8453: 
                   8454: returns either a stat() list of data about the file or an empty list
                   8455: if the file doesn't exist or couldn't find out about it (connection
                   8456: problems or user unknown)
                   8457: 
1.191     harris41 8458: =item *
                   8459: 
1.243     albertel 8460: filelocation($dir,$file) : returns file system location of a file
                   8461: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   8462: directory that relative $file lookups are to looked in ($dir of /a/dir
                   8463: and a file of ../bob will become /a/bob)
1.191     harris41 8464: 
                   8465: =item *
                   8466: 
                   8467: hreflocation($dir,$file) : returns file system location or a URL; same as
                   8468: filelocation except for hrefs
                   8469: 
                   8470: =item *
                   8471: 
                   8472: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   8473: 
1.243     albertel 8474: =back
                   8475: 
1.608     albertel 8476: =head2 Usererfile file routines (/uploaded*)
                   8477: 
                   8478: =over 4
                   8479: 
                   8480: =item *
                   8481: 
                   8482: userfileupload(): main rotine for putting a file in a user or course's
                   8483:                   filespace, arguments are,
                   8484: 
1.620     albertel 8485:  formname - required - this is the name of the element in $env where the
1.608     albertel 8486:            filename, and the contents of the file to create/modifed exist
1.620     albertel 8487:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   8488:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 8489:  coursedoc - if true, store the file in the course of the active role
                   8490:              of the current user
                   8491:  subdir - required - subdirectory to put the file in under ../userfiles/
                   8492:          if undefined, it will be placed in "unknown"
                   8493: 
                   8494:  (This routine calls clean_filename() to remove any dangerous
                   8495:  characters from the filename, and then calls finuserfileupload() to
                   8496:  complete the transaction)
                   8497: 
                   8498:  returns either the url of the uploaded file (/uploaded/....) if successful
                   8499:  and /adm/notfound.html if unsuccessful
                   8500: 
                   8501: =item *
                   8502: 
                   8503: clean_filename(): routine for cleaing a filename up for storage in
                   8504:                  userfile space, argument is:
                   8505: 
                   8506:  filename - proposed filename
                   8507: 
                   8508: returns: the new clean filename
                   8509: 
                   8510: =item *
                   8511: 
                   8512: finishuserfileupload(): routine that creaes and sends the file to
                   8513: userspace, probably shouldn't be called directly
                   8514: 
                   8515:   docuname: username or courseid of destination for the file
                   8516:   docudom: domain of user/course of destination for the file
                   8517:   formname: same as for userfileupload()
                   8518:   fname: filename (inculding subdirectories) for the file
                   8519: 
                   8520:  returns either the url of the uploaded file (/uploaded/....) if successful
                   8521:  and /adm/notfound.html if unsuccessful
                   8522: 
                   8523: =item *
                   8524: 
                   8525: renameuserfile(): renames an existing userfile to a new name
                   8526: 
                   8527:   Args:
                   8528:    docuname: username or courseid of destination for the file
                   8529:    docudom: domain of user/course of destination for the file
                   8530:    old: current file name (including any subdirs under userfiles)
                   8531:    new: desired file name (including any subdirs under userfiles)
                   8532: 
                   8533: =item *
                   8534: 
                   8535: mkdiruserfile(): creates a directory is a userfiles dir
                   8536: 
                   8537:   Args:
                   8538:    docuname: username or courseid of destination for the file
                   8539:    docudom: domain of user/course of destination for the file
                   8540:    dir: dir to create (including any subdirs under userfiles)
                   8541: 
                   8542: =item *
                   8543: 
                   8544: removeuserfile(): removes a file that exists in userfiles
                   8545: 
                   8546:   Args:
                   8547:    docuname: username or courseid of destination for the file
                   8548:    docudom: domain of user/course of destination for the file
                   8549:    fname: filname to delete (including any subdirs under userfiles)
                   8550: 
                   8551: =item *
                   8552: 
                   8553: removeuploadedurl(): convience function for removeuserfile()
                   8554: 
                   8555:   Args:
                   8556:    url:  a full /uploaded/... url to delete
                   8557: 
1.747     albertel 8558: =item * 
                   8559: 
                   8560: get_portfile_permissions():
                   8561:   Args:
                   8562:     domain: domain of user or course contain the portfolio files
                   8563:     user: name of user or num of course contain the portfolio files
                   8564:   Returns:
                   8565:     hashref of a dump of the proper file_permissions.db
                   8566:    
                   8567: 
                   8568: =item * 
                   8569: 
                   8570: get_access_controls():
                   8571: 
                   8572: Args:
                   8573:   current_permissions: the hash ref returned from get_portfile_permissions()
                   8574:   group: (optional) the group you want the files associated with
                   8575:   file: (optional) the file you want access info on
                   8576: 
                   8577: Returns:
1.749     raeburn  8578:     a hash (keys are file names) of hashes containing
                   8579:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   8580:         values are XML containing access control settings (see below) 
1.747     albertel 8581: 
                   8582: Internal notes:
                   8583: 
1.749     raeburn  8584:  access controls are stored in file_permissions.db as key=value pairs.
                   8585:     key -> path to file/file_name\0uniqueID:scope_end_start
                   8586:         where scope -> public,guest,course,group,domains or users.
                   8587:               end -> UNIX time for end of access (0 -> no end date)
                   8588:               start -> UNIX time for start of access
                   8589: 
                   8590:     value -> XML description of access control
                   8591:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   8592:             <start></start>
                   8593:             <end></end>
                   8594: 
                   8595:             <password></password>  for scope type = guest
                   8596: 
                   8597:             <domain></domain>     for scope type = course or group
                   8598:             <number></number>
                   8599:             <roles id="">
                   8600:              <role></role>
                   8601:              <access></access>
                   8602:              <section></section>
                   8603:              <group></group>
                   8604:             </roles>
                   8605: 
                   8606:             <dom></dom>         for scope type = domains
                   8607: 
                   8608:             <users>             for scope type = users
                   8609:              <user>
                   8610:               <uname></uname>
                   8611:               <udom></udom>
                   8612:              </user>
                   8613:             </users>
                   8614:            </scope> 
                   8615:               
                   8616:  Access data is also aggregated for each file in an additional key=value pair:
                   8617:  key -> path to file/file_name\0accesscontrol 
                   8618:  value -> reference to hash
                   8619:           hash contains key = value pairs
                   8620:           where key = uniqueID:scope_end_start
                   8621:                 value = UNIX time record was last updated
                   8622: 
                   8623:           Used to improve speed of look-ups of access controls for each file.  
                   8624:  
                   8625:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   8626: 
                   8627: modify_access_controls():
                   8628: 
                   8629: Modifies access controls for a portfolio file
                   8630: Args
                   8631: 1. file name
                   8632: 2. reference to hash of required changes,
                   8633: 3. domain
                   8634: 4. username
                   8635:   where domain,username are the domain of the portfolio owner 
                   8636:   (either a user or a course) 
                   8637: 
                   8638: Returns:
                   8639: 1. result of additions or updates ('ok' or 'error', with error message). 
                   8640: 2. result of deletions ('ok' or 'error', with error message).
                   8641: 3. reference to hash of any new or updated access controls.
                   8642: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   8643:    key = integer (inbound ID)
                   8644:    value = uniqueID  
1.747     albertel 8645: 
1.608     albertel 8646: =back
                   8647: 
1.243     albertel 8648: =head2 HTTP Helper Routines
                   8649: 
                   8650: =over 4
                   8651: 
1.191     harris41 8652: =item *
                   8653: 
                   8654: escape() : unpack non-word characters into CGI-compatible hex codes
                   8655: 
                   8656: =item *
                   8657: 
                   8658: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   8659: 
1.243     albertel 8660: =back
                   8661: 
                   8662: =head1 PRIVATE SUBROUTINES
                   8663: 
                   8664: =head2 Underlying communication routines (Shouldn't call)
                   8665: 
                   8666: =over 4
                   8667: 
                   8668: =item *
                   8669: 
                   8670: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   8671: 
                   8672: =item *
                   8673: 
                   8674: reply() : uses subreply to send a message to remote machine, logs all failures
                   8675: 
                   8676: =item *
                   8677: 
                   8678: critical() : passes a critical message to another server; if cannot
                   8679: get through then place message in connection buffer directory and
                   8680: returns con_delayed, if incapable of saving message, returns
                   8681: con_failed
                   8682: 
                   8683: =item *
                   8684: 
                   8685: reconlonc() : tries to reconnect lonc client processes.
                   8686: 
                   8687: =back
                   8688: 
                   8689: =head2 Resource Access Logging
                   8690: 
                   8691: =over 4
                   8692: 
                   8693: =item *
                   8694: 
                   8695: flushcourselogs() : flush (save) buffer logs and access logs
                   8696: 
                   8697: =item *
                   8698: 
                   8699: courselog($what) : save message for course in hash
                   8700: 
                   8701: =item *
                   8702: 
                   8703: courseacclog($what) : save message for course using &courselog().  Perform
                   8704: special processing for specific resource types (problems, exams, quizzes, etc).
                   8705: 
1.191     harris41 8706: =item *
                   8707: 
                   8708: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   8709: as a PerlChildExitHandler
1.243     albertel 8710: 
                   8711: =back
                   8712: 
                   8713: =head2 Other
                   8714: 
                   8715: =over 4
                   8716: 
                   8717: =item *
                   8718: 
                   8719: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 8720: 
                   8721: =back
                   8722: 
                   8723: =cut

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