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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.916   ! albertel    4: # $Id: lonnet.pm,v 1.915 2007/10/01 21:06:04 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.486     www        34: use HTTP::Date;
                     35: # use Date::Parse;
1.871     albertel   36: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
                     37:             $_64bit %env);
                     38: 
                     39: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     40:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     41:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
                     42:     %courseownerbuf, %coursetypebuf);
1.403     www        43: 
1.1       albertel   44: use IO::Socket;
1.31      www        45: use GDBM_File;
1.208     albertel   46: use HTML::LCParser;
1.88      www        47: use Fcntl qw(:flock);
1.870     albertel   48: use Storable qw(thaw nfreeze);
1.539     albertel   49: use Time::HiRes qw( gettimeofday tv_interval );
1.599     albertel   50: use Cache::Memcached;
1.676     albertel   51: use Digest::MD5;
1.790     albertel   52: use Math::Random;
1.807     albertel   53: use LONCAPA qw(:DEFAULT :match);
1.740     www        54: use LONCAPA::Configuration;
1.676     albertel   55: 
1.195     www        56: my $readit;
1.550     foxr       57: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel   58: 
1.619     albertel   59: require Exporter;
                     60: 
                     61: our @ISA = qw (Exporter);
                     62: our @EXPORT = qw(%env);
                     63: 
1.449     matthew    64: =pod
                     65: 
                     66: =head1 Package Variables
                     67: 
                     68: These are largely undocumented, so if you decipher one please note it here.
                     69: 
                     70: =over 4
                     71: 
                     72: =item $processmarker
                     73: 
                     74: Contains the time this process was started and this servers host id.
                     75: 
                     76: =item $dumpcount
                     77: 
                     78: Counts the number of times a message log flush has been attempted (regardless
                     79: of success) by this process.  Used as part of the filename when messages are
                     80: delayed.
                     81: 
                     82: =back
                     83: 
                     84: =cut
                     85: 
                     86: 
1.1       albertel   87: # --------------------------------------------------------------------- Logging
1.729     www        88: {
                     89:     my $logid;
                     90:     sub instructor_log {
                     91: 	my ($hash_name,$storehash,$delflag,$uname,$udom)=@_;
                     92: 	$logid++;
                     93: 	my $id=time().'00000'.$$.'00000'.$logid;
                     94: 	return &Apache::lonnet::put('nohist_'.$hash_name,
1.730     www        95: 				    { $id => {
                     96: 					'exe_uname' => $env{'user.name'},
                     97: 					'exe_udom'  => $env{'user.domain'},
                     98: 					'exe_time'  => time(),
                     99: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    100: 					'delflag'   => $delflag,
                    101: 					'logentry'  => $storehash,
                    102: 					'uname'     => $uname,
                    103: 					'udom'      => $udom,
                    104: 				    }
                    105: 				  },
1.729     www       106: 				    $env{'course.'.$env{'request.course.id'}.'.domain'},
                    107: 				    $env{'course.'.$env{'request.course.id'}.'.num'}
                    108: 				    );
                    109:     }
                    110: }
1.1       albertel  111: 
1.163     harris41  112: sub logtouch {
                    113:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  114:     unless (-e "$execdir/logs/lonnet.log") {	
                    115: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  116: 	close $fh;
                    117:     }
                    118:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    119:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    120: }
                    121: 
1.1       albertel  122: sub logthis {
                    123:     my $message=shift;
                    124:     my $execdir=$perlvar{'lonDaemons'};
                    125:     my $now=time;
                    126:     my $local=localtime($now);
1.448     albertel  127:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
                    128: 	print $fh "$local ($$): $message\n";
                    129: 	close($fh);
                    130:     }
1.1       albertel  131:     return 1;
                    132: }
                    133: 
                    134: sub logperm {
                    135:     my $message=shift;
                    136:     my $execdir=$perlvar{'lonDaemons'};
                    137:     my $now=time;
                    138:     my $local=localtime($now);
1.448     albertel  139:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    140: 	print $fh "$now:$message:$local\n";
                    141: 	close($fh);
                    142:     }
1.1       albertel  143:     return 1;
                    144: }
                    145: 
1.850     albertel  146: sub create_connection {
1.853     albertel  147:     my ($hostname,$lonid) = @_;
1.851     albertel  148:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  149: 				     Type    => SOCK_STREAM,
                    150: 				     Timeout => 10);
                    151:     return 0 if (!$client);
1.890     albertel  152:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  153:     my $result = <$client>;
                    154:     chomp($result);
                    155:     return 1 if ($result eq 'done');
                    156:     return 0;
                    157: }
                    158: 
                    159: 
1.1       albertel  160: # -------------------------------------------------- Non-critical communication
                    161: sub subreply {
                    162:     my ($cmd,$server)=@_;
1.838     albertel  163:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      164:     #
                    165:     #  With loncnew process trimming, there's a timing hole between lonc server
                    166:     #  process exit and the master server picking up the listen on the AF_UNIX
                    167:     #  socket.  In that time interval, a lock file will exist:
                    168: 
                    169:     my $lockfile=$peerfile.".lock";
                    170:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    171: 	sleep(1);
                    172:     }
                    173:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      174:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      175:     #
1.550     foxr      176:     #   We'll give the connection a few tries before abandoning it.  If
                    177:     #   connection is not possible, we'll con_lost back to the client.
                    178:     #   
                    179:     my $client;
                    180:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    181: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    182: 				      Type    => SOCK_STREAM,
                    183: 				      Timeout => 10);
1.869     albertel  184: 	if ($client) {
1.550     foxr      185: 	    last;		# Connected!
1.850     albertel  186: 	} else {
1.853     albertel  187: 	    &create_connection(&hostname($server),$server);
1.550     foxr      188: 	}
1.850     albertel  189:         sleep(1);		# Try again later if failed connection.
1.550     foxr      190:     }
                    191:     my $answer;
                    192:     if ($client) {
1.704     albertel  193: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      194: 	$answer=<$client>;
                    195: 	if (!$answer) { $answer="con_lost"; }
                    196: 	chomp($answer);
                    197:     } else {
                    198: 	$answer = 'con_lost';	# Failed connection.
                    199:     }
1.1       albertel  200:     return $answer;
                    201: }
                    202: 
                    203: sub reply {
                    204:     my ($cmd,$server)=@_;
1.838     albertel  205:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  206:     my $answer=subreply($cmd,$server);
1.65      www       207:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  208:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       209:                 " $cmd to $server returned $answer</font>");
                    210:     }
1.1       albertel  211:     return $answer;
                    212: }
                    213: 
                    214: # ----------------------------------------------------------- Send USR1 to lonc
                    215: 
                    216: sub reconlonc {
1.891     albertel  217:     my ($lonid) = @_;
                    218:     my $hostname = &hostname($lonid);
                    219:     if ($lonid) {
                    220: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    221: 	if ($hostname && -e $peerfile) {
                    222: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    223: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    224: 					     Type    => SOCK_STREAM,
                    225: 					     Timeout => 10);
                    226: 	    if ($client) {
                    227: 		print $client ("reset_retries\n");
                    228: 		my $answer=<$client>;
                    229: 		#reset just this one.
                    230: 	    }
                    231: 	}
                    232: 	return;
                    233:     }
                    234: 
1.836     www       235:     &logthis("Trying to reconnect lonc");
1.1       albertel  236:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  237:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  238: 	my $loncpid=<$fh>;
                    239:         chomp($loncpid);
                    240:         if (kill 0 => $loncpid) {
                    241: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    242:             kill USR1 => $loncpid;
                    243:             sleep 1;
1.836     www       244:          } else {
1.12      www       245: 	    &logthis(
1.672     albertel  246:                "<font color=\"blue\">WARNING:".
1.12      www       247:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  248:         }
                    249:     } else {
1.836     www       250: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  251:     }
                    252: }
                    253: 
                    254: # ------------------------------------------------------ Critical communication
1.12      www       255: 
1.1       albertel  256: sub critical {
                    257:     my ($cmd,$server)=@_;
1.838     albertel  258:     unless (&hostname($server)) {
1.672     albertel  259:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       260:                " Critical message to unknown server ($server)</font>");
                    261:         return 'no_such_host';
                    262:     }
1.1       albertel  263:     my $answer=reply($cmd,$server);
                    264:     if ($answer eq 'con_lost') {
                    265: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  266: 	my $answer=reply($cmd,$server);
1.1       albertel  267:         if ($answer eq 'con_lost') {
                    268:             my $now=time;
                    269:             my $middlename=$cmd;
1.5       www       270:             $middlename=substr($middlename,0,16);
1.1       albertel  271:             $middlename=~s/\W//g;
                    272:             my $dfilename=
1.305     www       273:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    274:             $dumpcount++;
1.1       albertel  275:             {
1.448     albertel  276: 		my $dfh;
                    277: 		if (open($dfh,">$dfilename")) {
                    278: 		    print $dfh "$cmd\n"; 
                    279: 		    close($dfh);
                    280: 		}
1.1       albertel  281:             }
                    282:             sleep 2;
                    283:             my $wcmd='';
                    284:             {
1.448     albertel  285: 		my $dfh;
                    286: 		if (open($dfh,"<$dfilename")) {
                    287: 		    $wcmd=<$dfh>; 
                    288: 		    close($dfh);
                    289: 		}
1.1       albertel  290:             }
                    291:             chomp($wcmd);
1.7       www       292:             if ($wcmd eq $cmd) {
1.672     albertel  293: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       294:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  295:                 &logperm("D:$server:$cmd");
                    296: 	        return 'con_delayed';
                    297:             } else {
1.672     albertel  298:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       299:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  300:                 &logperm("F:$server:$cmd");
                    301:                 return 'con_failed';
                    302:             }
                    303:         }
                    304:     }
                    305:     return $answer;
1.405     albertel  306: }
                    307: 
1.755     albertel  308: # ------------------------------------------- check if return value is an error
                    309: 
                    310: sub error {
                    311:     my ($result) = @_;
1.756     albertel  312:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  313: 	if ($2 == 2) { return undef; }
                    314: 	return $1;
                    315:     }
                    316:     return undef;
                    317: }
                    318: 
1.783     albertel  319: sub convert_and_load_session_env {
                    320:     my ($lonidsdir,$handle)=@_;
                    321:     my @profile;
                    322:     {
1.915     albertel  323: 	open(my $idf,'+<',"$lonidsdir/$handle.id");
                    324: 	if (!$idf) {
                    325: 	    return 0;
                    326: 	}
1.783     albertel  327: 	flock($idf,LOCK_SH);
                    328: 	@profile=<$idf>;
                    329: 	close($idf);
                    330:     }
                    331:     my %temp_env;
                    332:     foreach my $line (@profile) {
1.786     albertel  333: 	if ($line !~ m/=/) {
                    334: 	    return 0;
                    335: 	}
1.783     albertel  336: 	chomp($line);
                    337: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    338: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    339:     }
                    340:     unlink("$lonidsdir/$handle.id");
                    341:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    342: 	    0640)) {
                    343: 	%disk_env = %temp_env;
                    344: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    345: 	untie(%disk_env);
                    346:     }
1.786     albertel  347:     return 1;
1.783     albertel  348: }
                    349: 
1.374     www       350: # ------------------------------------------- Transfer profile into environment
1.780     albertel  351: my $env_loaded;
                    352: sub transfer_profile_to_env {
1.788     albertel  353:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    354:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       355: 
1.720     albertel  356:     if (!defined($lonidsdir)) {
                    357: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    358:     }
                    359:     if (!defined($handle)) {
                    360:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    361:     }
                    362: 
1.786     albertel  363:     my $convert;
                    364:     {
1.915     albertel  365:     	open(my $idf,'+<',"$lonidsdir/$handle.id");
                    366: 	if (!$idf) {
                    367: 	    return;
                    368: 	}
1.786     albertel  369: 	flock($idf,LOCK_SH);
                    370: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    371: 		&GDBM_READER(),0640)) {
                    372: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    373: 	    untie(%disk_env);
                    374: 	} else {
                    375: 	    $convert = 1;
                    376: 	}
                    377:     }
                    378:     if ($convert) {
                    379: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    380: 	    &logthis("Failed to load session, or convert session.");
                    381: 	}
1.374     www       382:     }
1.783     albertel  383: 
1.786     albertel  384:     my %remove;
1.783     albertel  385:     while ( my $envname = each(%env) ) {
1.433     matthew   386:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    387:             if ($time < time-300) {
1.783     albertel  388:                 $remove{$key}++;
1.433     matthew   389:             }
                    390:         }
                    391:     }
1.783     albertel  392: 
1.619     albertel  393:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  394:     $env_loaded=1;
1.783     albertel  395:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   396:         &delenv($expired_key);
1.374     www       397:     }
1.1       albertel  398: }
                    399: 
1.916   ! albertel  400: # ---------------------------------------------------- Check for valid session 
        !           401: sub check_for_valid_session {
        !           402:     my ($r) = @_;
        !           403:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
        !           404:     my $lonid=$cookies{'lonID'};
        !           405:     return undef if (!$lonid);
        !           406: 
        !           407:     my $handle=&LONCAPA::clean_handle($lonid->value);
        !           408:     my $lonidsdir=$r->dir_config('lonIDsDir');
        !           409:     return undef if (!-e "$lonidsdir/$handle.id");
        !           410: 
        !           411:     open(my $idf,'+<',"$lonidsdir/$handle.id");
        !           412:     return undef if (!$idf);
        !           413: 
        !           414:     flock($idf,LOCK_SH);
        !           415:     my %disk_env;
        !           416:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
        !           417: 	    &GDBM_READER(),0640)) {
        !           418: 	return undef;	
        !           419:     }
        !           420: 
        !           421:     if (!defined($disk_env{'user.name'})
        !           422: 	|| !defined($disk_env{'user.domain'})) {
        !           423: 	return undef;
        !           424:     }
        !           425:     return $handle;
        !           426: }
        !           427: 
1.830     albertel  428: sub timed_flock {
                    429:     my ($file,$lock_type) = @_;
                    430:     my $failed=0;
                    431:     eval {
                    432: 	local $SIG{__DIE__}='DEFAULT';
                    433: 	local $SIG{ALRM}=sub {
                    434: 	    $failed=1;
                    435: 	    die("failed lock");
                    436: 	};
                    437: 	alarm(13);
                    438: 	flock($file,$lock_type);
                    439: 	alarm(0);
                    440:     };
                    441:     if ($failed) {
                    442: 	return undef;
                    443:     } else {
                    444: 	return 1;
                    445:     }
                    446: }
                    447: 
1.5       www       448: # ---------------------------------------------------------- Append Environment
                    449: 
                    450: sub appenv {
1.6       www       451:     my %newenv=@_;
1.692     albertel  452:     foreach my $key (keys(%newenv)) {
                    453: 	if (($newenv{$key}=~/^user\.role/) || ($newenv{$key}=~/^user\.priv/)) {
1.672     albertel  454:             &logthis("<font color=\"blue\">WARNING: ".
1.692     albertel  455:                 "Attempt to modify environment ".$key." to ".$newenv{$key}
1.151     www       456:                 .'</font>');
1.692     albertel  457: 	    delete($newenv{$key});
1.35      www       458:         } else {
1.692     albertel  459:             $env{$key}=$newenv{$key};
1.35      www       460:         }
1.191     harris41  461:     }
1.915     albertel  462:     open(my $env_file,'+<',$env{'user.environment'});
                    463:     if ($env_file
                    464: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  465: 	&&
                    466: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    467: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  468: 	while (my ($key,$value) = each(%newenv)) {
                    469: 	    $disk_env{$key} = $value;
1.448     albertel  470: 	}
1.783     albertel  471: 	untie(%disk_env);
1.56      www       472:     }
                    473:     return 'ok';
                    474: }
                    475: # ----------------------------------------------------- Delete from Environment
                    476: 
                    477: sub delenv {
                    478:     my $delthis=shift;
                    479:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672     albertel  480:         &logthis("<font color=\"blue\">WARNING: ".
1.56      www       481:                 "Attempt to delete from environment ".$delthis);
                    482:         return 'error';
                    483:     }
1.915     albertel  484:     open(my $env_file,'+<',$env{'user.environment'});
                    485:     if ($env_file
                    486: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  487: 	&&
                    488: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    489: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  490: 	foreach my $key (keys(%disk_env)) {
                    491: 	    if ($key=~/^$delthis/) { 
1.915     albertel  492: 		delete($env{$key});
                    493: 		delete($disk_env{$key});
                    494: 	    }
1.448     albertel  495: 	}
1.783     albertel  496: 	untie(%disk_env);
1.5       www       497:     }
                    498:     return 'ok';
1.369     albertel  499: }
                    500: 
1.790     albertel  501: sub get_env_multiple {
                    502:     my ($name) = @_;
                    503:     my @values;
                    504:     if (defined($env{$name})) {
                    505:         # exists is it an array
                    506:         if (ref($env{$name})) {
                    507:             @values=@{ $env{$name} };
                    508:         } else {
                    509:             $values[0]=$env{$name};
                    510:         }
                    511:     }
                    512:     return(@values);
                    513: }
                    514: 
1.369     albertel  515: # ------------------------------------------ Find out current server userload
                    516: # there is a copy in lond
                    517: sub userload {
                    518:     my $numusers=0;
                    519:     {
                    520: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    521: 	my $filename;
                    522: 	my $curtime=time;
                    523: 	while ($filename=readdir(LONIDS)) {
                    524: 	    if ($filename eq '.' || $filename eq '..') {next;}
1.404     albertel  525: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  526: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  527: 	}
                    528: 	closedir(LONIDS);
                    529:     }
                    530:     my $userloadpercent=0;
                    531:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    532:     if ($maxuserload) {
1.371     albertel  533: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  534:     }
1.372     albertel  535:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  536:     return $userloadpercent;
1.283     www       537: }
                    538: 
                    539: # ------------------------------------------ Fight off request when overloaded
                    540: 
                    541: sub overloaderror {
                    542:     my ($r,$checkserver)=@_;
                    543:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
                    544:     my $loadavg;
                    545:     if ($checkserver eq $perlvar{'lonHostID'}) {
1.448     albertel  546:        open(my $loadfile,'/proc/loadavg');
1.283     www       547:        $loadavg=<$loadfile>;
                    548:        $loadavg =~ s/\s.*//g;
1.285     matthew   549:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448     albertel  550:        close($loadfile);
1.283     www       551:     } else {
                    552:        $loadavg=&reply('load',$checkserver);
                    553:     }
1.285     matthew   554:     my $overload=$loadavg-100;
1.283     www       555:     if ($overload>0) {
1.285     matthew   556: 	$r->err_headers_out->{'Retry-After'}=$overload;
1.283     www       557:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554     www       558:         return 413;
1.283     www       559:     }    
                    560:     return '';
1.5       www       561: }
1.1       albertel  562: 
                    563: # ------------------------------ Find server with least workload from spare.tab
1.11      www       564: 
1.1       albertel  565: sub spareserver {
1.670     albertel  566:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.784     albertel  567:     my $spare_server;
1.370     albertel  568:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  569:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    570:                                                      :  $userloadpercent;
                    571:     
                    572:     foreach my $try_server (@{ $spareid{'primary'} }) {
                    573: 	($spare_server, $lowest_load) =
                    574: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
                    575:     }
                    576: 
                    577:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    578: 
                    579:     if (!$found_server) {
                    580: 	foreach my $try_server (@{ $spareid{'default'} }) {
                    581: 	    ($spare_server, $lowest_load) =
                    582: 		&compare_server_load($try_server, $spare_server, $lowest_load);
                    583: 	}
                    584:     }
                    585: 
                    586:     if (!$want_server_name) {
1.838     albertel  587: 	$spare_server="http://".&hostname($spare_server);
1.784     albertel  588:     }
                    589:     return $spare_server;
                    590: }
                    591: 
                    592: sub compare_server_load {
                    593:     my ($try_server, $spare_server, $lowest_load) = @_;
                    594: 
                    595:     my $loadans     = &reply('load',    $try_server);
                    596:     my $userloadans = &reply('userload',$try_server);
                    597: 
                    598:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
                    599: 	next; #didn't get a number from the server
                    600:     }
                    601: 
                    602:     my $load;
                    603:     if ($loadans =~ /\d/) {
                    604: 	if ($userloadans =~ /\d/) {
                    605: 	    #both are numbers, pick the bigger one
                    606: 	    $load = ($loadans > $userloadans) ? $loadans 
                    607: 		                              : $userloadans;
1.411     albertel  608: 	} else {
1.784     albertel  609: 	    $load = $loadans;
1.411     albertel  610: 	}
1.784     albertel  611:     } else {
                    612: 	$load = $userloadans;
                    613:     }
                    614: 
                    615:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    616: 	$spare_server = $try_server;
                    617: 	$lowest_load  = $load;
1.370     albertel  618:     }
1.784     albertel  619:     return ($spare_server,$lowest_load);
1.202     matthew   620: }
1.914     albertel  621: 
                    622: # --------------------------- ask offload servers if user already has a session
                    623: sub find_existing_session {
                    624:     my ($udom,$uname) = @_;
                    625:     foreach my $try_server (@{ $spareid{'primary'} },
                    626: 			    @{ $spareid{'default'} }) {
                    627: 	return $try_server if (&has_user_session($try_server, $udom, $uname));
                    628:     }
                    629:     return;
                    630: }
                    631: 
                    632: # -------------------------------- ask if server already has a session for user
                    633: sub has_user_session {
                    634:     my ($lonid,$udom,$uname) = @_;
                    635:     my $result = &reply(join(':','userhassession',
                    636: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    637:     return 1 if ($result eq 'ok');
                    638: 
                    639:     return 0;
                    640: }
                    641: 
1.202     matthew   642: # --------------------------------------------- Try to change a user's password
                    643: 
                    644: sub changepass {
1.799     raeburn   645:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   646:     $currentpass = &escape($currentpass);
                    647:     $newpass     = &escape($newpass);
1.799     raeburn   648:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
1.202     matthew   649: 		       $server);
                    650:     if (! $answer) {
                    651: 	&logthis("No reply on password change request to $server ".
                    652: 		 "by $uname in domain $udom.");
                    653:     } elsif ($answer =~ "^ok") {
                    654:         &logthis("$uname in $udom successfully changed their password ".
                    655: 		 "on $server.");
                    656:     } elsif ($answer =~ "^pwchange_failure") {
                    657: 	&logthis("$uname in $udom was unable to change their password ".
                    658: 		 "on $server.  The action was blocked by either lcpasswd ".
                    659: 		 "or pwchange");
                    660:     } elsif ($answer =~ "^non_authorized") {
                    661:         &logthis("$uname in $udom did not get their password correct when ".
                    662: 		 "attempting to change it on $server.");
                    663:     } elsif ($answer =~ "^auth_mode_error") {
                    664:         &logthis("$uname in $udom attempted to change their password despite ".
                    665: 		 "not being locally or internally authenticated on $server.");
                    666:     } elsif ($answer =~ "^unknown_user") {
                    667:         &logthis("$uname in $udom attempted to change their password ".
                    668: 		 "on $server but were unable to because $server is not ".
                    669: 		 "their home server.");
                    670:     } elsif ($answer =~ "^refused") {
                    671: 	&logthis("$server refused to change $uname in $udom password because ".
                    672: 		 "it was sent an unencrypted request to change the password.");
                    673:     }
                    674:     return $answer;
1.1       albertel  675: }
                    676: 
1.169     harris41  677: # ----------------------- Try to determine user's current authentication scheme
                    678: 
                    679: sub queryauthenticate {
                    680:     my ($uname,$udom)=@_;
1.456     albertel  681:     my $uhome=&homeserver($uname,$udom);
                    682:     if (!$uhome) {
                    683: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                    684: 	return 'no_host';
                    685:     }
                    686:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                    687:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                    688: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41  689:     }
1.456     albertel  690:     return $answer;
1.169     harris41  691: }
                    692: 
1.1       albertel  693: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       694: 
1.1       albertel  695: sub authenticate {
                    696:     my ($uname,$upass,$udom)=@_;
1.807     albertel  697:     $upass=&escape($upass);
                    698:     $uname= &LONCAPA::clean_username($uname);
1.836     www       699:     my $uhome=&homeserver($uname,$udom,1);
                    700:     if ((!$uhome) || ($uhome eq 'no_host')) {
                    701: # Maybe the machine was offline and only re-appeared again recently?
                    702:         &reconlonc();
                    703: # One more
                    704: 	my $uhome=&homeserver($uname,$udom,1);
                    705: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                    706: 	    &logthis("User $uname at $udom is unknown in authenticate");
                    707: 	}
1.471     albertel  708: 	return 'no_host';
1.1       albertel  709:     }
1.471     albertel  710:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
                    711:     if ($answer eq 'authorized') {
                    712: 	&logthis("User $uname at $udom authorized by $uhome"); 
                    713: 	return $uhome; 
                    714:     }
                    715:     if ($answer eq 'non_authorized') {
                    716: 	&logthis("User $uname at $udom rejected by $uhome");
                    717: 	return 'no_host'; 
1.9       www       718:     }
1.471     albertel  719:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel  720:     return 'no_host';
                    721: }
                    722: 
                    723: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www       724: 
1.599     albertel  725: my %homecache;
1.1       albertel  726: sub homeserver {
1.230     stredwic  727:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel  728:     my $index="$uname:$udom";
1.426     albertel  729: 
1.599     albertel  730:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel  731: 
                    732:     my %servers = &get_servers($udom,'library');
                    733:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic  734:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic  735: 		 exists($badServerCache{$tryserver}));
1.841     albertel  736: 
                    737: 	my $answer=reply("home:$udom:$uname",$tryserver);
                    738: 	if ($answer eq 'found') {
                    739: 	    delete($badServerCache{$tryserver}); 
                    740: 	    return $homecache{$index}=$tryserver;
                    741: 	} elsif ($answer eq 'no_host') {
                    742: 	    $badServerCache{$tryserver}=1;
                    743: 	}
1.1       albertel  744:     }    
                    745:     return 'no_host';
1.70      www       746: }
                    747: 
                    748: # ------------------------------------- Find the usernames behind a list of IDs
                    749: 
                    750: sub idget {
                    751:     my ($udom,@ids)=@_;
                    752:     my %returnhash=();
                    753:     
1.841     albertel  754:     my %servers = &get_servers($udom,'library');
                    755:     foreach my $tryserver (keys(%servers)) {
                    756: 	my $idlist=join('&',@ids);
                    757: 	$idlist=~tr/A-Z/a-z/; 
                    758: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                    759: 	my @answer=();
                    760: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                    761: 	    @answer=split(/\&/,$reply);
                    762: 	}                    ;
                    763: 	my $i;
                    764: 	for ($i=0;$i<=$#ids;$i++) {
                    765: 	    if ($answer[$i]) {
                    766: 		$returnhash{$ids[$i]}=$answer[$i];
                    767: 	    } 
                    768: 	}
                    769:     } 
1.70      www       770:     return %returnhash;
                    771: }
                    772: 
                    773: # ------------------------------------- Find the IDs behind a list of usernames
                    774: 
                    775: sub idrget {
                    776:     my ($udom,@unames)=@_;
                    777:     my %returnhash=();
1.800     albertel  778:     foreach my $uname (@unames) {
                    779:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41  780:     }
1.70      www       781:     return %returnhash;
                    782: }
                    783: 
                    784: # ------------------------------- Store away a list of names and associated IDs
                    785: 
                    786: sub idput {
                    787:     my ($udom,%ids)=@_;
                    788:     my %servers=();
1.800     albertel  789:     foreach my $uname (keys(%ids)) {
                    790: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                    791:         my $uhom=&homeserver($uname,$udom);
1.70      www       792:         if ($uhom ne 'no_host') {
1.800     albertel  793:             my $id=&escape($ids{$uname});
1.70      www       794:             $id=~tr/A-Z/a-z/;
1.800     albertel  795:             my $esc_unam=&escape($uname);
1.70      www       796: 	    if ($servers{$uhom}) {
1.800     albertel  797: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www       798:             } else {
1.800     albertel  799:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www       800:             }
                    801:         }
1.191     harris41  802:     }
1.800     albertel  803:     foreach my $server (keys(%servers)) {
                    804:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41  805:     }
1.344     www       806: }
                    807: 
1.806     raeburn   808: # ------------------------------------------- get items from domain db files   
                    809: 
                    810: sub get_dom {
1.860     raeburn   811:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn   812:     my $items='';
                    813:     foreach my $item (@$storearr) {
                    814:         $items.=&escape($item).'&';
                    815:     }
                    816:     $items=~s/\&$//;
1.860     raeburn   817:     if (!$udom) {
                    818:         $udom=$env{'user.domain'};
                    819:         if (defined(&domain($udom,'primary'))) {
                    820:             $uhome=&domain($udom,'primary');
                    821:         } else {
1.874     albertel  822:             undef($uhome);
1.860     raeburn   823:         }
                    824:     } else {
                    825:         if (!$uhome) {
                    826:             if (defined(&domain($udom,'primary'))) {
                    827:                 $uhome=&domain($udom,'primary');
                    828:             }
                    829:         }
                    830:     }
                    831:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn   832:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn   833:         my %returnhash;
1.875     albertel  834:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn   835:             return %returnhash;
                    836:         }
1.806     raeburn   837:         my @pairs=split(/\&/,$rep);
                    838:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                    839:             return @pairs;
                    840:         }
                    841:         my $i=0;
                    842:         foreach my $item (@$storearr) {
                    843:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                    844:             $i++;
                    845:         }
                    846:         return %returnhash;
                    847:     } else {
1.880     banghart  848:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn   849:     }
                    850: }
                    851: 
                    852: # -------------------------------------------- put items in domain db files 
                    853: 
                    854: sub put_dom {
1.860     raeburn   855:     my ($namespace,$storehash,$udom,$uhome)=@_;
                    856:     if (!$udom) {
                    857:         $udom=$env{'user.domain'};
                    858:         if (defined(&domain($udom,'primary'))) {
                    859:             $uhome=&domain($udom,'primary');
                    860:         } else {
1.874     albertel  861:             undef($uhome);
1.860     raeburn   862:         }
                    863:     } else {
                    864:         if (!$uhome) {
                    865:             if (defined(&domain($udom,'primary'))) {
                    866:                 $uhome=&domain($udom,'primary');
                    867:             }
                    868:         }
                    869:     } 
                    870:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn   871:         my $items='';
                    872:         foreach my $item (keys(%$storehash)) {
                    873:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                    874:         }
                    875:         $items=~s/\&$//;
                    876:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                    877:     } else {
1.860     raeburn   878:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn   879:     }
                    880: }
                    881: 
1.837     raeburn   882: sub retrieve_inst_usertypes {
                    883:     my ($udom) = @_;
                    884:     my (%returnhash,@order);
1.846     albertel  885:     if (defined(&domain($udom,'primary'))) {
                    886:         my $uhome=&domain($udom,'primary');
1.837     raeburn   887:         my $rep=&reply("inst_usertypes:$udom",$uhome);
                    888:         my ($hashitems,$orderitems) = split(/:/,$rep); 
                    889:         my @pairs=split(/\&/,$hashitems);
                    890:         foreach my $item (@pairs) {
                    891:             my ($key,$value)=split(/=/,$item,2);
                    892:             $key = &unescape($key);
                    893:             next if ($key =~ /^error: 2 /);
                    894:             $returnhash{$key}=&thaw_unescape($value);
                    895:         }
                    896:         my @esc_order = split(/\&/,$orderitems);
                    897:         foreach my $item (@esc_order) {
                    898:             push(@order,&unescape($item));
                    899:         }
                    900:     } else {
                    901:         &logthis("get_dom failed - no primary domain server for $udom");
                    902:     }
                    903:     return (\%returnhash,\@order);
                    904: }
                    905: 
1.868     raeburn   906: sub is_domainimage {
                    907:     my ($url) = @_;
                    908:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                    909:         if (&domain($1) ne '') {
                    910:             return '1';
                    911:         }
                    912:     }
                    913:     return;
                    914: }
                    915: 
1.899     raeburn   916: sub inst_directory_query {
                    917:     my ($srch) = @_;
                    918:     my $udom = $srch->{'srchdomain'};
                    919:     my %results;
                    920:     my $homeserver = &domain($udom,'primary');
1.909     raeburn   921:     my $outcome;
1.899     raeburn   922:     if ($homeserver ne '') {
1.904     albertel  923: 	my $queryid=&reply("querysend:instdirsearch:".
                    924: 			   &escape($srch->{'srchby'}).':'.
                    925: 			   &escape($srch->{'srchterm'}).':'.
                    926: 			   &escape($srch->{'srchtype'}),$homeserver);
                    927: 	my $host=&hostname($homeserver);
                    928: 	if ($queryid !~/^\Q$host\E\_/) {
                    929: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                    930: 	    return;
                    931: 	}
                    932: 	my $response = &get_query_reply($queryid);
                    933: 	my $maxtries = 5;
                    934: 	my $tries = 1;
                    935: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                    936: 	    $response = &get_query_reply($queryid);
                    937: 	    $tries ++;
                    938: 	}
                    939: 
                    940:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn   941:             if ($response eq 'unavailable') {
                    942:                 $outcome = $response;
                    943:             } else {
                    944:                 $outcome = 'ok';
                    945:                 my @matches = split(/\n/,$response);
                    946:                 foreach my $match (@matches) {
                    947:                     my ($key,$value) = split(/=/,$match);
                    948:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                    949:                 }
1.899     raeburn   950:             }
                    951:         }
                    952:     }
1.909     raeburn   953:     return ($outcome,%results);
1.899     raeburn   954: }
                    955: 
                    956: sub usersearch {
                    957:     my ($srch) = @_;
                    958:     my $dom = $srch->{'srchdomain'};
                    959:     my %results;
                    960:     my %libserv = &all_library();
                    961:     my $query = 'usersearch';
                    962:     foreach my $tryserver (keys(%libserv)) {
                    963:         if (&host_domain($tryserver) eq $dom) {
                    964:             my $host=&hostname($tryserver);
                    965:             my $queryid=
1.911     raeburn   966:                 &reply("querysend:".&escape($query).':'.
                    967:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn   968:                        &escape($srch->{'srchtype'}).':'.
                    969:                        &escape($srch->{'srchterm'}),$tryserver);
                    970:             if ($queryid !~/^\Q$host\E\_/) {
                    971:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn   972:                 next;
1.899     raeburn   973:             }
                    974:             my $reply = &get_query_reply($queryid);
                    975:             my $maxtries = 1;
                    976:             my $tries = 1;
                    977:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                    978:                 $reply = &get_query_reply($queryid);
                    979:                 $tries ++;
                    980:             }
                    981:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                    982:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                    983:             } else {
1.911     raeburn   984:                 my @matches;
                    985:                 if ($reply =~ /\n/) {
                    986:                     @matches = split(/\n/,$reply);
                    987:                 } else {
                    988:                     @matches = split(/\&/,$reply);
                    989:                 }
1.899     raeburn   990:                 foreach my $match (@matches) {
                    991:                     my ($uname,$udom,%userhash);
1.911     raeburn   992:                     foreach my $entry (split(/:/,$match)) {
                    993:                         my ($key,$value) =
                    994:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn   995:                         $userhash{$key} = $value;
                    996:                         if ($key eq 'username') {
                    997:                             $uname = $value;
                    998:                         } elsif ($key eq 'domain') {
                    999:                             $udom = $value;
1.911     raeburn  1000:                         }
1.899     raeburn  1001:                     }
                   1002:                     $results{$uname.':'.$udom} = \%userhash;
                   1003:                 }
                   1004:             }
                   1005:         }
                   1006:     }
                   1007:     return %results;
                   1008: }
                   1009: 
1.912     raeburn  1010: sub get_instuser {
                   1011:     my ($udom,$uname,$id) = @_;
                   1012:     my $homeserver = &domain($udom,'primary');
                   1013:     my ($outcome,%results);
                   1014:     if ($homeserver ne '') {
                   1015:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1016:                            &escape($id).':'.&escape($udom),$homeserver);
                   1017:         my $host=&hostname($homeserver);
                   1018:         if ($queryid !~/^\Q$host\E\_/) {
                   1019:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1020:             return;
                   1021:         }
                   1022:         my $response = &get_query_reply($queryid);
                   1023:         my $maxtries = 5;
                   1024:         my $tries = 1;
                   1025:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1026:             $response = &get_query_reply($queryid);
                   1027:             $tries ++;
                   1028:         }
                   1029:         if (!&error($response) && $response ne 'refused') {
                   1030:             if ($response eq 'unavailable') {
                   1031:                 $outcome = $response;
                   1032:             } else {
                   1033:                 $outcome = 'ok';
                   1034:                 my @matches = split(/\n/,$response);
                   1035:                 foreach my $match (@matches) {
                   1036:                     my ($key,$value) = split(/=/,$match);
                   1037:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1038:                 }
                   1039:             }
                   1040:         }
                   1041:     }
                   1042:     my %userinfo;
                   1043:     if (ref($results{$uname}) eq 'HASH') {
                   1044:         %userinfo = %{$results{$uname}};
                   1045:     } 
                   1046:     return ($outcome,%userinfo);
                   1047: }
                   1048: 
                   1049: sub inst_rulecheck {
                   1050:     my ($udom,$uname,$rules) = @_;
                   1051:     my %returnhash;
                   1052:     if ($udom ne '') {
                   1053:         if (ref($rules) eq 'ARRAY') {
                   1054:             @{$rules} = map {&escape($_);} (@{$rules});
                   1055:             my $rulestr = join(':',@{$rules});
                   1056:             my $homeserver=&domain($udom,'primary');
                   1057:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
                   1058:                 my $response=&unescape(&reply('instrulecheck:'.&escape($udom).':'.
                   1059:                                               &escape($uname).':'.$rulestr,
                   1060:                                               $homeserver));
                   1061:                 if ($response ne 'refused') {
                   1062:                     my @pairs=split(/\&/,$response);
                   1063:                     foreach my $item (@pairs) {
                   1064:                         my ($key,$value)=split(/=/,$item,2);
                   1065:                         $key = &unescape($key);
                   1066:                         next if ($key =~ /^error: 2 /);
                   1067:                         $returnhash{$key}=&thaw_unescape($value);
                   1068:                     }
                   1069:                 }
                   1070:             }
                   1071:         }
                   1072:     }
                   1073:     return %returnhash;
                   1074: }
                   1075: 
                   1076: sub inst_userrules {
                   1077:     my ($udom) = @_;
                   1078:     my (%ruleshash,@ruleorder);
                   1079:     if ($udom ne '') {
                   1080:         my $homeserver=&domain($udom,'primary');
                   1081:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
                   1082:             my $response=&reply('instuserrules:'.&escape($udom),
                   1083:                                  $homeserver);
                   1084:             if (($response ne 'refused') && ($response ne 'error') && 
                   1085:                 ($response ne 'no_such_host')) {
                   1086:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1087:                 my @pairs=split(/\&/,$hashitems);
                   1088:                 foreach my $item (@pairs) {
                   1089:                     my ($key,$value)=split(/=/,$item,2);
                   1090:                     $key = &unescape($key);
                   1091:                     next if ($key =~ /^error: 2 /);
                   1092:                     $ruleshash{$key}=&thaw_unescape($value);
                   1093:                 }
                   1094:                 my @esc_order = split(/\&/,$orderitems);
                   1095:                 foreach my $item (@esc_order) {
                   1096:                     push(@ruleorder,&unescape($item));
                   1097:                 }
                   1098:             }
                   1099:         }
                   1100:     }
                   1101:     return (\%ruleshash,\@ruleorder);
                   1102: }
                   1103: 
1.344     www      1104: # --------------------------------------------------- Assign a key to a student
                   1105: 
                   1106: sub assign_access_key {
1.364     www      1107: #
                   1108: # a valid key looks like uname:udom#comments
                   1109: # comments are being appended
                   1110: #
1.498     www      1111:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   1112:     $kdom=
1.620     albertel 1113:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      1114:     $knum=
1.620     albertel 1115:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      1116:     $cdom=
1.620     albertel 1117:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1118:     $cnum=
1.620     albertel 1119:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1120:     $udom=$env{'user.name'} unless (defined($udom));
                   1121:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      1122:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      1123:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 1124:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      1125:                                                   # assigned to this person
                   1126:                                                   # - this should not happen,
1.345     www      1127:                                                   # unless something went wrong
                   1128:                                                   # the first time around
                   1129: # ready to assign
1.364     www      1130:         $logentry=$1.'; '.$logentry;
1.496     www      1131:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      1132:                                                  $kdom,$knum) eq 'ok') {
1.345     www      1133: # key now belongs to user
1.346     www      1134: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      1135:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
                   1136:                 &appenv('environment.'.$envkey => $ckey);
                   1137:                 return 'ok';
                   1138:             } else {
                   1139:                 return 
                   1140:   'error: Count not permanently assign key, will need to be re-entered later.';
                   1141: 	    }
                   1142:         } else {
                   1143:             return 'error: Could not assign key, try again later.';
                   1144:         }
1.364     www      1145:     } elsif (!$existing{$ckey}) {
1.345     www      1146: # the key does not exist
                   1147: 	return 'error: The key does not exist';
                   1148:     } else {
                   1149: # the key is somebody else's
                   1150: 	return 'error: The key is already in use';
                   1151:     }
1.344     www      1152: }
                   1153: 
1.364     www      1154: # ------------------------------------------ put an additional comment on a key
                   1155: 
                   1156: sub comment_access_key {
                   1157: #
                   1158: # a valid key looks like uname:udom#comments
                   1159: # comments are being appended
                   1160: #
                   1161:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   1162:     $cdom=
1.620     albertel 1163:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      1164:     $cnum=
1.620     albertel 1165:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      1166:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   1167:     if ($existing{$ckey}) {
                   1168:         $existing{$ckey}.='; '.$logentry;
                   1169: # ready to assign
1.367     www      1170:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      1171:                                                  $cdom,$cnum) eq 'ok') {
                   1172: 	    return 'ok';
                   1173:         } else {
                   1174: 	    return 'error: Count not store comment.';
                   1175:         }
                   1176:     } else {
                   1177: # the key does not exist
                   1178: 	return 'error: The key does not exist';
                   1179:     }
                   1180: }
                   1181: 
1.344     www      1182: # ------------------------------------------------------ Generate a set of keys
                   1183: 
                   1184: sub generate_access_keys {
1.364     www      1185:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      1186:     $cdom=
1.620     albertel 1187:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1188:     $cnum=
1.620     albertel 1189:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      1190:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      1191:     unless (($cdom) && ($cnum)) { return 0; }
                   1192:     if ($number>10000) { return 0; }
                   1193:     sleep(2); # make sure don't get same seed twice
                   1194:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   1195:     my $total=0;
                   1196:     for (my $i=1;$i<=$number;$i++) {
                   1197:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   1198:                   sprintf("%lx",int(100000*rand)).'-'.
                   1199:                   sprintf("%lx",int(100000*rand));
                   1200:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   1201:        $newkey=~s/0/h/g; # and also 0 and O
                   1202:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   1203:        if ($existing{$newkey}) {
                   1204:            $i--;
                   1205:        } else {
1.364     www      1206: 	  if (&put('accesskeys',
                   1207:               { $newkey => '# generated '.localtime().
1.620     albertel 1208:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      1209:                            '; '.$logentry },
                   1210: 		   $cdom,$cnum) eq 'ok') {
1.344     www      1211:               $total++;
                   1212: 	  }
                   1213:        }
                   1214:     }
1.620     albertel 1215:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      1216:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   1217:     return $total;
                   1218: }
                   1219: 
                   1220: # ------------------------------------------------------- Validate an accesskey
                   1221: 
                   1222: sub validate_access_key {
                   1223:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   1224:     $cdom=
1.620     albertel 1225:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1226:     $cnum=
1.620     albertel 1227:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1228:     $udom=$env{'user.domain'} unless (defined($udom));
                   1229:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      1230:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 1231:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      1232: }
                   1233: 
                   1234: # ------------------------------------- Find the section of student in a course
1.652     albertel 1235: sub devalidate_getsection_cache {
                   1236:     my ($udom,$unam,$courseid)=@_;
                   1237:     my $hashid="$udom:$unam:$courseid";
                   1238:     &devalidate_cache_new('getsection',$hashid);
                   1239: }
1.298     matthew  1240: 
1.815     albertel 1241: sub courseid_to_courseurl {
                   1242:     my ($courseid) = @_;
                   1243:     #already url style courseid
                   1244:     return $courseid if ($courseid =~ m{^/});
                   1245: 
                   1246:     if (exists($env{'course.'.$courseid.'.num'})) {
                   1247: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   1248: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   1249: 	return "/$cdom/$cnum";
                   1250:     }
                   1251: 
                   1252:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   1253:     if (exists($courseinfo{'num'})) {
                   1254: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   1255:     }
                   1256: 
                   1257:     return undef;
                   1258: }
                   1259: 
1.298     matthew  1260: sub getsection {
                   1261:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 1262:     my $cachetime=1800;
1.551     albertel 1263: 
                   1264:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 1265:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 1266:     if (defined($cached)) { return $result; }
                   1267: 
1.298     matthew  1268:     my %Pending; 
                   1269:     my %Expired;
                   1270:     #
                   1271:     # Each role can either have not started yet (pending), be active, 
                   1272:     #    or have expired.
                   1273:     #
                   1274:     # If there is an active role, we are done.
                   1275:     #
                   1276:     # If there is more than one role which has not started yet, 
                   1277:     #     choose the one which will start sooner
                   1278:     # If there is one role which has not started yet, return it.
                   1279:     #
                   1280:     # If there is more than one expired role, choose the one which ended last.
                   1281:     # If there is a role which has expired, return it.
                   1282:     #
1.815     albertel 1283:     $courseid = &courseid_to_courseurl($courseid);
1.817     raeburn  1284:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
                   1285:     foreach my $key (keys(%roleshash)) {
1.479     albertel 1286:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  1287:         my $section=$1;
                   1288:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  1289:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  1290:         my $now=time;
1.548     albertel 1291:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  1292:             $Expired{$end}=$section;
                   1293:             next;
                   1294:         }
1.548     albertel 1295:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  1296:             $Pending{$start}=$section;
                   1297:             next;
                   1298:         }
1.599     albertel 1299:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  1300:     }
                   1301:     #
                   1302:     # Presumedly there will be few matching roles from the above
                   1303:     # loop and the sorting time will be negligible.
                   1304:     if (scalar(keys(%Pending))) {
                   1305:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 1306:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  1307:     } 
                   1308:     if (scalar(keys(%Expired))) {
                   1309:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   1310:         my $time = pop(@sorted);
1.599     albertel 1311:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  1312:     }
1.599     albertel 1313:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  1314: }
1.70      www      1315: 
1.599     albertel 1316: sub save_cache {
                   1317:     &purge_remembered();
1.722     albertel 1318:     #&Apache::loncommon::validate_page();
1.620     albertel 1319:     undef(%env);
1.780     albertel 1320:     undef($env_loaded);
1.599     albertel 1321: }
1.452     albertel 1322: 
1.599     albertel 1323: my $to_remember=-1;
                   1324: my %remembered;
                   1325: my %accessed;
                   1326: my $kicks=0;
                   1327: my $hits=0;
1.849     albertel 1328: sub make_key {
                   1329:     my ($name,$id) = @_;
1.872     albertel 1330:     if (length($id) > 65 
                   1331: 	&& length(&escape($id)) > 200) {
                   1332: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   1333:     }
1.849     albertel 1334:     return &escape($name.':'.$id);
                   1335: }
                   1336: 
1.599     albertel 1337: sub devalidate_cache_new {
                   1338:     my ($name,$id,$debug) = @_;
                   1339:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 1340:     $id=&make_key($name,$id);
1.599     albertel 1341:     $memcache->delete($id);
                   1342:     delete($remembered{$id});
                   1343:     delete($accessed{$id});
                   1344: }
                   1345: 
                   1346: sub is_cached_new {
                   1347:     my ($name,$id,$debug) = @_;
1.849     albertel 1348:     $id=&make_key($name,$id);
1.599     albertel 1349:     if (exists($remembered{$id})) {
                   1350: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                   1351: 	$accessed{$id}=[&gettimeofday()];
                   1352: 	$hits++;
                   1353: 	return ($remembered{$id},1);
                   1354:     }
                   1355:     my $value = $memcache->get($id);
                   1356:     if (!(defined($value))) {
                   1357: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 1358: 	return (undef,undef);
1.416     albertel 1359:     }
1.599     albertel 1360:     if ($value eq '__undef__') {
                   1361: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   1362: 	$value=undef;
                   1363:     }
                   1364:     &make_room($id,$value,$debug);
                   1365:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   1366:     return ($value,1);
                   1367: }
                   1368: 
                   1369: sub do_cache_new {
                   1370:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 1371:     $id=&make_key($name,$id);
1.599     albertel 1372:     my $setvalue=$value;
                   1373:     if (!defined($setvalue)) {
                   1374: 	$setvalue='__undef__';
                   1375:     }
1.623     albertel 1376:     if (!defined($time) ) {
                   1377: 	$time=600;
                   1378:     }
1.599     albertel 1379:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 1380:     my $result = $memcache->set($id,$setvalue,$time);
                   1381:     if (! $result) {
1.872     albertel 1382: 	&logthis("caching of id -> $id  failed");
1.910     albertel 1383: 	$memcache->disconnect_all();
1.872     albertel 1384:     }
1.600     albertel 1385:     # need to make a copy of $value
                   1386:     #&make_room($id,$value,$debug);
1.599     albertel 1387:     return $value;
                   1388: }
                   1389: 
                   1390: sub make_room {
                   1391:     my ($id,$value,$debug)=@_;
                   1392:     $remembered{$id}=$value;
                   1393:     if ($to_remember<0) { return; }
                   1394:     $accessed{$id}=[&gettimeofday()];
                   1395:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   1396:     my $to_kick;
                   1397:     my $max_time=0;
                   1398:     foreach my $other (keys(%accessed)) {
                   1399: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   1400: 	    $to_kick=$other;
                   1401: 	    $max_time=&tv_interval($accessed{$other});
                   1402: 	}
                   1403:     }
                   1404:     delete($remembered{$to_kick});
                   1405:     delete($accessed{$to_kick});
                   1406:     $kicks++;
                   1407:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 1408:     return;
                   1409: }
                   1410: 
1.599     albertel 1411: sub purge_remembered {
1.604     albertel 1412:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   1413:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 1414:     undef(%remembered);
                   1415:     undef(%accessed);
1.428     albertel 1416: }
1.70      www      1417: # ------------------------------------- Read an entry from a user's environment
                   1418: 
                   1419: sub userenvironment {
                   1420:     my ($udom,$unam,@what)=@_;
                   1421:     my %returnhash=();
                   1422:     my @answer=split(/\&/,
                   1423:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
                   1424:                       &homeserver($unam,$udom)));
                   1425:     my $i;
                   1426:     for ($i=0;$i<=$#what;$i++) {
                   1427: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                   1428:     }
                   1429:     return %returnhash;
1.1       albertel 1430: }
                   1431: 
1.617     albertel 1432: # ---------------------------------------------------------- Get a studentphoto
                   1433: sub studentphoto {
                   1434:     my ($udom,$unam,$ext) = @_;
                   1435:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1436:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1437:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1438:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1439:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1440:             } else {
                   1441:                 my ($result,$perm_reqd)=
1.707     albertel 1442: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1443:                 if ($result eq 'ok') {
                   1444:                     if (!($perm_reqd eq 'yes')) {
                   1445:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1446:                     }
                   1447:                 }
                   1448:             }
                   1449:         }
                   1450:     } else {
                   1451:         my ($result,$perm_reqd) = 
1.707     albertel 1452: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1453:         if ($result eq 'ok') {
                   1454:             if (!($perm_reqd eq 'yes')) {
                   1455:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1456:             }
                   1457:         }
                   1458:     }
                   1459:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1460: }
                   1461: 
                   1462: sub retrievestudentphoto {
                   1463:     my ($udom,$unam,$ext,$type) = @_;
                   1464:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1465:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1466:     if ($ret eq 'ok') {
                   1467:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1468:         if ($type eq 'thumbnail') {
                   1469:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1470:         }
                   1471:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1472:         return $tokenurl;
                   1473:     } else {
                   1474:         if ($type eq 'thumbnail') {
                   1475:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1476:         } else { 
                   1477:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1478:         }
1.617     albertel 1479:     }
                   1480: }
                   1481: 
1.263     www      1482: # -------------------------------------------------------------------- New chat
                   1483: 
                   1484: sub chatsend {
1.724     raeburn  1485:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1486:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1487:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1488:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1489:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1490: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1491: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1492: }
                   1493: 
                   1494: # ------------------------------------------ Find current version of a resource
                   1495: 
                   1496: sub getversion {
                   1497:     my $fname=&clutter(shift);
                   1498:     unless ($fname=~/^\/res\//) { return -1; }
                   1499:     return &currentversion(&filelocation('',$fname));
                   1500: }
                   1501: 
                   1502: sub currentversion {
                   1503:     my $fname=shift;
1.599     albertel 1504:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1505:     if (defined($cached)) { return $result; }
1.292     www      1506:     my $author=$fname;
                   1507:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1508:     my ($udom,$uname)=split(/\//,$author);
                   1509:     my $home=homeserver($uname,$udom);
                   1510:     if ($home eq 'no_host') { 
                   1511:         return -1; 
                   1512:     }
                   1513:     my $answer=reply("currentversion:$fname",$home);
                   1514:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1515: 	return -1;
                   1516:     }
1.599     albertel 1517:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1518: }
                   1519: 
1.1       albertel 1520: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1521: 
1.1       albertel 1522: sub subscribe {
                   1523:     my $fname=shift;
1.761     raeburn  1524:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1525:     $fname=~s/[\n\r]//g;
1.1       albertel 1526:     my $author=$fname;
                   1527:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1528:     my ($udom,$uname)=split(/\//,$author);
                   1529:     my $home=homeserver($uname,$udom);
1.335     albertel 1530:     if ($home eq 'no_host') {
                   1531:         return 'not_found';
1.1       albertel 1532:     }
                   1533:     my $answer=reply("sub:$fname",$home);
1.64      www      1534:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1535: 	$answer.=' by '.$home;
                   1536:     }
1.1       albertel 1537:     return $answer;
                   1538: }
                   1539:     
1.8       www      1540: # -------------------------------------------------------------- Replicate file
                   1541: 
                   1542: sub repcopy {
                   1543:     my $filename=shift;
1.23      www      1544:     $filename=~s/\/+/\//g;
1.607     raeburn  1545:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1546:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1547:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1548: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1549: 	return &repcopy_userfile($filename);
                   1550:     }
1.532     albertel 1551:     $filename=~s/[\n\r]//g;
1.8       www      1552:     my $transname="$filename.in.transfer";
1.828     www      1553: # FIXME: this should flock
1.607     raeburn  1554:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1555:     my $remoteurl=subscribe($filename);
1.64      www      1556:     if ($remoteurl =~ /^con_lost by/) {
                   1557: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1558:            return 'unavailable';
1.8       www      1559:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1560: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1561: 	   return 'not_found';
1.64      www      1562:     } elsif ($remoteurl =~ /^rejected by/) {
                   1563: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1564:            return 'forbidden';
1.20      www      1565:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1566:            return 'ok';
1.8       www      1567:     } else {
1.290     www      1568:         my $author=$filename;
                   1569:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1570:         my ($udom,$uname)=split(/\//,$author);
                   1571:         my $home=homeserver($uname,$udom);
                   1572:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1573:            my @parts=split(/\//,$filename);
                   1574:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1575:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1576:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1577: 	       return 'bad_request';
1.8       www      1578:            }
                   1579:            my $count;
                   1580:            for ($count=5;$count<$#parts;$count++) {
                   1581:                $path.="/$parts[$count]";
                   1582:                if ((-e $path)!=1) {
                   1583: 		   mkdir($path,0777);
                   1584:                }
                   1585:            }
                   1586:            my $ua=new LWP::UserAgent;
                   1587:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1588:            my $response=$ua->request($request,$transname);
                   1589:            if ($response->is_error()) {
                   1590: 	       unlink($transname);
                   1591:                my $message=$response->status_line;
1.672     albertel 1592:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      1593:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1594:                return 'unavailable';
1.8       www      1595:            } else {
1.16      www      1596: 	       if ($remoteurl!~/\.meta$/) {
                   1597:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1598:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1599:                   if ($mresponse->is_error()) {
                   1600: 		      unlink($filename.'.meta');
                   1601:                       &logthis(
1.672     albertel 1602:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      1603:                   }
                   1604: 	       }
1.8       www      1605:                rename($transname,$filename);
1.607     raeburn  1606:                return 'ok';
1.8       www      1607:            }
1.290     www      1608:        }
1.8       www      1609:     }
1.330     www      1610: }
                   1611: 
                   1612: # ------------------------------------------------ Get server side include body
                   1613: sub ssi_body {
1.381     albertel 1614:     my ($filelink,%form)=@_;
1.606     matthew  1615:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1616:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1617:     }
1.330     www      1618:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
1.381     albertel 1619:                                      &ssi($filelink,%form));
1.778     albertel 1620:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1621:     $output=~s/^.*?\<body[^\>]*\>//si;
                   1622:     $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
1.330     www      1623:     return $output;
1.8       www      1624: }
                   1625: 
1.15      www      1626: # --------------------------------------------------------- Server Side Include
                   1627: 
1.782     albertel 1628: sub absolute_url {
                   1629:     my ($host_name) = @_;
                   1630:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   1631:     if ($host_name eq '') {
                   1632: 	$host_name = $ENV{'SERVER_NAME'};
                   1633:     }
                   1634:     return $protocol.$host_name;
                   1635: }
                   1636: 
1.15      www      1637: sub ssi {
                   1638: 
1.23      www      1639:     my ($fn,%form)=@_;
1.15      www      1640: 
                   1641:     my $ua=new LWP::UserAgent;
1.23      www      1642:     
                   1643:     my $request;
1.711     albertel 1644: 
                   1645:     $form{'no_update_last_known'}=1;
1.895     albertel 1646:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      1647:     if (%form) {
1.782     albertel 1648:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.201     albertel 1649:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www      1650:     } else {
1.782     albertel 1651:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      1652:     }
                   1653: 
1.15      www      1654:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1655:     my $response=$ua->request($request);
                   1656: 
1.324     www      1657:     return $response->content;
                   1658: }
                   1659: 
                   1660: sub externalssi {
                   1661:     my ($url)=@_;
                   1662:     my $ua=new LWP::UserAgent;
                   1663:     my $request=new HTTP::Request('GET',$url);
                   1664:     my $response=$ua->request($request);
1.15      www      1665:     return $response->content;
                   1666: }
1.254     www      1667: 
1.492     albertel 1668: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1669: 
                   1670: sub allowuploaded {
                   1671:     my ($srcurl,$url)=@_;
                   1672:     $url=&clutter(&declutter($url));
                   1673:     my $dir=$url;
                   1674:     $dir=~s/\/[^\/]+$//;
                   1675:     my %httpref=();
                   1676:     my $httpurl=&hreflocation('',$url);
                   1677:     $httpref{'httpref.'.$httpurl}=$srcurl;
                   1678:     &Apache::lonnet::appenv(%httpref);
1.254     www      1679: }
1.477     raeburn  1680: 
1.478     albertel 1681: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 1682: # input: action, courseID, current domain, intended
1.637     raeburn  1683: #        path to file, source of file, instruction to parse file for objects,
                   1684: #        ref to hash for embedded objects,
                   1685: #        ref to hash for codebase of java objects.
                   1686: #
1.485     raeburn  1687: # output: url to file (if action was uploaddoc), 
                   1688: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  1689: #
1.478     albertel 1690: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   1691: # course.
1.477     raeburn  1692: #
1.478     albertel 1693: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1694: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   1695: #          course's home server.
1.477     raeburn  1696: #
1.478     albertel 1697: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   1698: #          be copied from $source (current location) to 
                   1699: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1700: #         and will then be copied to
                   1701: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   1702: #         course's home server.
1.485     raeburn  1703: #
1.481     raeburn  1704: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 1705: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  1706: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1707: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   1708: #         in course's home server.
1.637     raeburn  1709: #
1.477     raeburn  1710: 
                   1711: sub process_coursefile {
1.638     albertel 1712:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  1713:     my $fetchresult;
1.638     albertel 1714:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  1715:     if ($action eq 'propagate') {
1.638     albertel 1716:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1717: 			     $home);
1.481     raeburn  1718:     } else {
1.477     raeburn  1719:         my $fpath = '';
                   1720:         my $fname = $file;
1.478     albertel 1721:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  1722:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  1723:         my $filepath = &build_filepath($fpath);
1.481     raeburn  1724:         if ($action eq 'copy') {
                   1725:             if ($source eq '') {
                   1726:                 $fetchresult = 'no source file';
                   1727:                 return $fetchresult;
                   1728:             } else {
                   1729:                 my $destination = $filepath.'/'.$fname;
                   1730:                 rename($source,$destination);
                   1731:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1732:                                  $home);
1.481     raeburn  1733:             }
                   1734:         } elsif ($action eq 'uploaddoc') {
                   1735:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 1736:             print $fh $env{'form.'.$source};
1.481     raeburn  1737:             close($fh);
1.637     raeburn  1738:             if ($parser eq 'parse') {
                   1739:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
                   1740:                 unless ($parse_result eq 'ok') {
                   1741:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   1742:                 }
                   1743:             }
1.477     raeburn  1744:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1745:                                  $home);
1.481     raeburn  1746:             if ($fetchresult eq 'ok') {
                   1747:                 return '/uploaded/'.$fpath.'/'.$fname;
                   1748:             } else {
                   1749:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1750:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  1751:                 return '/adm/notfound.html';
                   1752:             }
1.477     raeburn  1753:         }
                   1754:     }
1.485     raeburn  1755:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  1756:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1757:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  1758:     }
                   1759:     return $fetchresult;
                   1760: }
                   1761: 
1.637     raeburn  1762: sub build_filepath {
                   1763:     my ($fpath) = @_;
                   1764:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   1765:     unless ($fpath eq '') {
                   1766:         my @parts=split('/',$fpath);
                   1767:         foreach my $part (@parts) {
                   1768:             $filepath.= '/'.$part;
                   1769:             if ((-e $filepath)!=1) {
                   1770:                 mkdir($filepath,0777);
                   1771:             }
                   1772:         }
                   1773:     }
                   1774:     return $filepath;
                   1775: }
                   1776: 
                   1777: sub store_edited_file {
1.638     albertel 1778:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  1779:     my $file = $primary_url;
                   1780:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   1781:     my $fpath = '';
                   1782:     my $fname = $file;
                   1783:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   1784:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   1785:     my $filepath = &build_filepath($fpath);
                   1786:     open(my $fh,'>'.$filepath.'/'.$fname);
                   1787:     print $fh $content;
                   1788:     close($fh);
1.638     albertel 1789:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  1790:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1791: 			  $home);
1.637     raeburn  1792:     if ($$fetchresult eq 'ok') {
                   1793:         return '/uploaded/'.$fpath.'/'.$fname;
                   1794:     } else {
1.638     albertel 1795:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   1796: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  1797:         return '/adm/notfound.html';
                   1798:     }
                   1799: }
                   1800: 
1.531     albertel 1801: sub clean_filename {
1.831     albertel 1802:     my ($fname,$args)=@_;
1.315     www      1803: # Replace Windows backslashes by forward slashes
1.257     www      1804:     $fname=~s/\\/\//g;
1.831     albertel 1805:     if (!$args->{'keep_path'}) {
                   1806:         # Get rid of everything but the actual filename
                   1807: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   1808:     }
1.315     www      1809: # Replace spaces by underscores
                   1810:     $fname=~s/\s+/\_/g;
                   1811: # Replace all other weird characters by nothing
1.831     albertel 1812:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 1813: # Replace all .\d. sequences with _\d. so they no longer look like version
                   1814: # numbers
                   1815:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 1816:     return $fname;
                   1817: }
                   1818: 
1.608     albertel 1819: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 1820: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 1821: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 1822: #        $coursedoc - if true up to the current course
                   1823: #                     if false
                   1824: #        $subdir - directory in userfile to store the file into
1.858     raeburn  1825: #        $parser - instruction to parse file for objects ($parser = parse)    
                   1826: #        $allfiles - reference to hash for embedded objects
                   1827: #        $codebase - reference to hash for codebase of java objects
                   1828: #        $desuname - username for permanent storage of uploaded file
                   1829: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  1830: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   1831: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.858     raeburn  1832: # 
1.686     albertel 1833: # output: url of file in userspace, or error: <message> 
                   1834: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 1835: 
                   1836: 
1.531     albertel 1837: sub userfileupload {
1.860     raeburn  1838:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
                   1839:         $destudom,$thumbwidth,$thumbheight)=@_;
1.531     albertel 1840:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 1841:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 1842:     $fname=&clean_filename($fname);
1.315     www      1843: # See if there is anything left
1.257     www      1844:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 1845:     chop($env{'form.'.$formname});
1.523     raeburn  1846:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   1847:         my $now = time;
                   1848:         my $filepath = 'tmp/helprequests/'.$now;
                   1849:         my @parts=split(/\//,$filepath);
                   1850:         my $fullpath = $perlvar{'lonDaemons'};
                   1851:         for (my $i=0;$i<@parts;$i++) {
                   1852:             $fullpath .= '/'.$parts[$i];
                   1853:             if ((-e $fullpath)!=1) {
                   1854:                 mkdir($fullpath,0777);
                   1855:             }
                   1856:         }
                   1857:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 1858:         print $fh $env{'form.'.$formname};
1.523     raeburn  1859:         close($fh);
1.741     raeburn  1860:         return $fullpath.'/'.$fname;
                   1861:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   1862:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   1863:                        '_'.$env{'user.domain'}.'/pending';
                   1864:         my @parts=split(/\//,$filepath);
                   1865:         my $fullpath = $perlvar{'lonDaemons'};
                   1866:         for (my $i=0;$i<@parts;$i++) {
                   1867:             $fullpath .= '/'.$parts[$i];
                   1868:             if ((-e $fullpath)!=1) {
                   1869:                 mkdir($fullpath,0777);
                   1870:             }
                   1871:         }
                   1872:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   1873:         print $fh $env{'form.'.$formname};
                   1874:         close($fh);
                   1875:         return $fullpath.'/'.$fname;
1.523     raeburn  1876:     }
1.719     banghart 1877:     
1.258     www      1878: # Create the directory if not present
1.493     albertel 1879:     $fname="$subdir/$fname";
1.259     www      1880:     if ($coursedoc) {
1.638     albertel 1881: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1882: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  1883:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 1884:             return &finishuserfileupload($docuname,$docudom,
                   1885: 					 $formname,$fname,$parser,$allfiles,
1.860     raeburn  1886: 					 $codebase,$thumbwidth,$thumbheight);
1.481     raeburn  1887:         } else {
1.620     albertel 1888:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 1889:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   1890: 				       $fname,$formname,$parser,
                   1891: 				       $allfiles,$codebase);
1.481     raeburn  1892:         }
1.719     banghart 1893:     } elsif (defined($destuname)) {
                   1894:         my $docuname=$destuname;
                   1895:         my $docudom=$destudom;
1.860     raeburn  1896: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   1897: 				     $parser,$allfiles,$codebase,
                   1898:                                      $thumbwidth,$thumbheight);
1.719     banghart 1899:         
1.259     www      1900:     } else {
1.638     albertel 1901:         my $docuname=$env{'user.name'};
                   1902:         my $docudom=$env{'user.domain'};
1.714     raeburn  1903:         if (exists($env{'form.group'})) {
                   1904:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1905:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1906:         }
1.860     raeburn  1907: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   1908: 				     $parser,$allfiles,$codebase,
                   1909:                                      $thumbwidth,$thumbheight);
1.259     www      1910:     }
1.271     www      1911: }
                   1912: 
                   1913: sub finishuserfileupload {
1.860     raeburn  1914:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
                   1915:         $thumbwidth,$thumbheight) = @_;
1.477     raeburn  1916:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      1917:     my $filepath=$perlvar{'lonDocRoot'};
1.860     raeburn  1918:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 1919:     $file=$fname;
                   1920:     if ($fname=~m|/|) {
                   1921:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   1922: 	$path.=$fnamepath.'/';
                   1923:     }
1.259     www      1924:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      1925:     my $count;
                   1926:     for ($count=4;$count<=$#parts;$count++) {
                   1927:         $filepath.="/$parts[$count]";
                   1928:         if ((-e $filepath)!=1) {
                   1929: 	    mkdir($filepath,0777);
                   1930:         }
                   1931:     }
                   1932: # Save the file
                   1933:     {
1.701     albertel 1934: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   1935: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   1936: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   1937: 	    return '/adm/notfound.html';
                   1938: 	}
                   1939: 	if (!print FH ($env{'form.'.$formname})) {
                   1940: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   1941: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   1942: 	    return '/adm/notfound.html';
                   1943: 	}
1.570     albertel 1944: 	close(FH);
1.258     www      1945:     }
1.637     raeburn  1946:     if ($parser eq 'parse') {
1.638     albertel 1947:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
                   1948: 						   $codebase);
1.637     raeburn  1949:         unless ($parse_result eq 'ok') {
1.638     albertel 1950:             &logthis('Failed to parse '.$filepath.$file.
                   1951: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  1952:         }
                   1953:     }
1.860     raeburn  1954:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   1955:         my $input = $filepath.'/'.$file;
                   1956:         my $output = $filepath.'/'.'tn-'.$file;
                   1957:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   1958:         system("convert -sample $thumbsize $input $output");
                   1959:         if (-e $filepath.'/'.'tn-'.$file) {
                   1960:             $fetchthumb  = 1; 
                   1961:         }
                   1962:     }
1.858     raeburn  1963:  
1.259     www      1964: # Notify homeserver to grep it
                   1965: #
1.638     albertel 1966:     my $docuhome=&homeserver($docuname,$docudom);
1.494     albertel 1967:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      1968:     if ($fetchresult eq 'ok') {
1.860     raeburn  1969:         if ($fetchthumb) {
                   1970:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   1971:             if ($thumbresult ne 'ok') {
                   1972:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   1973:                          $docuhome.': '.$thumbresult);
                   1974:             }
                   1975:         }
1.259     www      1976: #
1.258     www      1977: # Return the URL to it
1.494     albertel 1978:         return '/uploaded/'.$path.$file;
1.263     www      1979:     } else {
1.494     albertel 1980:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   1981: 		 ': '.$fetchresult);
1.263     www      1982:         return '/adm/notfound.html';
1.858     raeburn  1983:     }
1.493     albertel 1984: }
                   1985: 
1.637     raeburn  1986: sub extract_embedded_items {
1.648     raeburn  1987:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
1.637     raeburn  1988:     my @state = ();
                   1989:     my %javafiles = (
                   1990:                       codebase => '',
                   1991:                       code => '',
                   1992:                       archive => ''
                   1993:                     );
                   1994:     my %mediafiles = (
                   1995:                       src => '',
                   1996:                       movie => '',
                   1997:                      );
1.648     raeburn  1998:     my $p;
                   1999:     if ($content) {
                   2000:         $p = HTML::LCParser->new($content);
                   2001:     } else {
                   2002:         $p = HTML::LCParser->new($filepath.'/'.$file);
                   2003:     }
1.641     albertel 2004:     while (my $t=$p->get_token()) {
1.640     albertel 2005: 	if ($t->[0] eq 'S') {
                   2006: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 2007: 	    push(@state, $tagname);
1.648     raeburn  2008:             if (lc($tagname) eq 'allow') {
                   2009:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   2010:             }
1.640     albertel 2011: 	    if (lc($tagname) eq 'img') {
                   2012: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   2013: 	    }
1.886     albertel 2014: 	    if (lc($tagname) eq 'a') {
                   2015: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   2016: 	    }
1.645     raeburn  2017:             if (lc($tagname) eq 'script') {
                   2018:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   2019:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   2020:                 } else {
                   2021:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   2022:                 }
                   2023:             }
                   2024:             if (lc($tagname) eq 'link') {
                   2025:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   2026:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   2027:                 }
                   2028:             }
1.640     albertel 2029: 	    if (lc($tagname) eq 'object' ||
                   2030: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   2031: 		foreach my $item (keys(%javafiles)) {
                   2032: 		    $javafiles{$item} = '';
                   2033: 		}
                   2034: 	    }
                   2035: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   2036: 		my $name = lc($attr->{'name'});
                   2037: 		foreach my $item (keys(%javafiles)) {
                   2038: 		    if ($name eq $item) {
                   2039: 			$javafiles{$item} = $attr->{'value'};
                   2040: 			last;
                   2041: 		    }
                   2042: 		}
                   2043: 		foreach my $item (keys(%mediafiles)) {
                   2044: 		    if ($name eq $item) {
                   2045: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   2046: 			last;
                   2047: 		    }
                   2048: 		}
                   2049: 	    }
                   2050: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   2051: 		foreach my $item (keys(%javafiles)) {
                   2052: 		    if ($attr->{$item}) {
                   2053: 			$javafiles{$item} = $attr->{$item};
                   2054: 			last;
                   2055: 		    }
                   2056: 		}
                   2057: 		foreach my $item (keys(%mediafiles)) {
                   2058: 		    if ($attr->{$item}) {
                   2059: 			&add_filetype($allfiles,$attr->{$item},$item);
                   2060: 			last;
                   2061: 		    }
                   2062: 		}
                   2063: 	    }
                   2064: 	} elsif ($t->[0] eq 'E') {
                   2065: 	    my ($tagname) = ($t->[1]);
                   2066: 	    if ($javafiles{'codebase'} ne '') {
                   2067: 		$javafiles{'codebase'} .= '/';
                   2068: 	    }  
                   2069: 	    if (lc($tagname) eq 'applet' ||
                   2070: 		lc($tagname) eq 'object' ||
                   2071: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   2072: 		) {
                   2073: 		foreach my $item (keys(%javafiles)) {
                   2074: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   2075: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   2076: 			&add_filetype($allfiles,$file,$item);
                   2077: 		    }
                   2078: 		}
                   2079: 	    } 
                   2080: 	    pop @state;
                   2081: 	}
                   2082:     }
1.637     raeburn  2083:     return 'ok';
                   2084: }
                   2085: 
1.639     albertel 2086: sub add_filetype {
                   2087:     my ($allfiles,$file,$type)=@_;
                   2088:     if (exists($allfiles->{$file})) {
                   2089: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   2090: 	    push(@{$allfiles->{$file}}, &escape($type));
                   2091: 	}
                   2092:     } else {
                   2093: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  2094:     }
                   2095: }
                   2096: 
1.493     albertel 2097: sub removeuploadedurl {
                   2098:     my ($url)=@_;
                   2099:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613     albertel 2100:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 2101: }
                   2102: 
                   2103: sub removeuserfile {
                   2104:     my ($docuname,$docudom,$fname)=@_;
                   2105:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2106:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
                   2107:     if ($result eq 'ok') {
                   2108:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   2109:             my $metafile = $fname.'.meta';
                   2110:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 2111: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
                   2112:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2113:             my $sqlresult = 
1.823     albertel 2114:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2115:                                         'portfolio_metadata',$group,
                   2116:                                         'delete');
1.798     raeburn  2117:         }
                   2118:     }
                   2119:     return $result;
1.257     www      2120: }
1.15      www      2121: 
1.530     albertel 2122: sub mkdiruserfile {
                   2123:     my ($docuname,$docudom,$dir)=@_;
                   2124:     my $home=&homeserver($docuname,$docudom);
                   2125:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   2126: }
                   2127: 
1.531     albertel 2128: sub renameuserfile {
                   2129:     my ($docuname,$docudom,$old,$new)=@_;
                   2130:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2131:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   2132:                         &escape("$old").':'.&escape("$new"),$home);
                   2133:     if ($result eq 'ok') {
                   2134:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   2135:             my $oldmeta = $old.'.meta';
                   2136:             my $newmeta = $new.'.meta';
                   2137:             my $metaresult = 
                   2138:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 2139: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   2140:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2141:             my $sqlresult = 
1.823     albertel 2142:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2143:                                         'portfolio_metadata',$group,
                   2144:                                         'delete');
1.798     raeburn  2145:         }
                   2146:     }
                   2147:     return $result;
1.531     albertel 2148: }
                   2149: 
1.14      www      2150: # ------------------------------------------------------------------------- Log
                   2151: 
                   2152: sub log {
                   2153:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      2154:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      2155: }
                   2156: 
                   2157: # ------------------------------------------------------------------ Course Log
1.352     www      2158: #
                   2159: # This routine flushes several buffers of non-mission-critical nature
                   2160: #
1.157     www      2161: 
                   2162: sub flushcourselogs {
1.352     www      2163:     &logthis('Flushing log buffers');
                   2164: #
                   2165: # course logs
                   2166: # This is a log of all transactions in a course, which can be used
                   2167: # for data mining purposes
                   2168: #
                   2169: # It also collects the courseid database, which lists last transaction
                   2170: # times and course titles for all courseids
                   2171: #
                   2172:     my %courseidbuffer=();
1.800     albertel 2173:     foreach my $crsid (keys %courselogs) {
1.352     www      2174:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      2175: 		          &escape($courselogs{$crsid}),
                   2176: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      2177: 	    delete $courselogs{$crsid};
                   2178:         } else {
                   2179:             &logthis('Failed to flush log buffer for '.$crsid);
                   2180:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 2181:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      2182:                         " exceeded maximum size, deleting.</font>");
                   2183:                delete $courselogs{$crsid};
                   2184:             }
1.352     www      2185:         }
                   2186:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
                   2187:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
1.516     raeburn  2188: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  2189:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.352     www      2190:         } else {
                   2191:            $courseidbuffer{$coursehombuf{$crsid}}=
1.516     raeburn  2192: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  2193:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.571     raeburn  2194:         }
1.191     harris41 2195:     }
1.352     www      2196: #
                   2197: # Write course id database (reverse lookup) to homeserver of courses 
                   2198: # Is used in pickcourse
                   2199: #
1.840     albertel 2200:     foreach my $crs_home (keys(%courseidbuffer)) {
1.844     albertel 2201:         &courseidput(&host_domain($crs_home),$courseidbuffer{$crs_home},
1.840     albertel 2202: 		     $crs_home);
1.352     www      2203:     }
                   2204: #
                   2205: # File accesses
                   2206: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   2207: #
1.449     matthew  2208:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  2209:         if ($entry =~ /___count$/) {
                   2210:             my ($dom,$name);
1.807     albertel 2211:             ($dom,$name,undef)=
1.811     albertel 2212: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  2213:             if (! defined($dom) || $dom eq '' || 
                   2214:                 ! defined($name) || $name eq '') {
1.620     albertel 2215:                 my $cid = $env{'request.course.id'};
                   2216:                 $dom  = $env{'request.'.$cid.'.domain'};
                   2217:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  2218:             }
1.450     matthew  2219:             my $value = $accesshash{$entry};
                   2220:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   2221:             my %temphash=($url => $value);
1.449     matthew  2222:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   2223:             if ($result eq 'ok') {
                   2224:                 delete $accesshash{$entry};
                   2225:             } elsif ($result eq 'unknown_cmd') {
                   2226:                 # Target server has old code running on it.
1.450     matthew  2227:                 my %temphash=($entry => $value);
1.449     matthew  2228:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2229:                     delete $accesshash{$entry};
                   2230:                 }
                   2231:             }
                   2232:         } else {
1.811     albertel 2233:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  2234:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  2235:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2236:                 delete $accesshash{$entry};
                   2237:             }
1.185     www      2238:         }
1.191     harris41 2239:     }
1.352     www      2240: #
                   2241: # Roles
                   2242: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   2243: #
1.800     albertel 2244:     foreach my $entry (keys(%userrolehash)) {
1.351     www      2245:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      2246: 	    split(/\:/,$entry);
                   2247:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      2248:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      2249:                 $rudom,$runame) eq 'ok') {
                   2250: 	    delete $userrolehash{$entry};
                   2251:         }
                   2252:     }
1.662     raeburn  2253: #
                   2254: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   2255: #
                   2256:     my %domrolebuffer = ();
                   2257:     foreach my $entry (keys %domainrolehash) {
1.901     albertel 2258:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  2259:         if ($domrolebuffer{$rudom}) {
                   2260:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   2261:                       '='.&escape($domainrolehash{$entry});
                   2262:         } else {
                   2263:             $domrolebuffer{$rudom}.=&escape($entry).
                   2264:                       '='.&escape($domainrolehash{$entry});
                   2265:         }
                   2266:         delete $domainrolehash{$entry};
                   2267:     }
                   2268:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 2269: 	my %servers = &get_servers($dom,'library');
                   2270: 	foreach my $tryserver (keys(%servers)) {
                   2271: 	    unless (&reply('domroleput:'.$dom.':'.
                   2272: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   2273: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   2274: 	    }
1.662     raeburn  2275:         }
                   2276:     }
1.186     www      2277:     $dumpcount++;
1.157     www      2278: }
                   2279: 
                   2280: sub courselog {
                   2281:     my $what=shift;
1.158     www      2282:     $what=time.':'.$what;
1.620     albertel 2283:     unless ($env{'request.course.id'}) { return ''; }
                   2284:     $coursedombuf{$env{'request.course.id'}}=
                   2285:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2286:     $coursenumbuf{$env{'request.course.id'}}=
                   2287:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   2288:     $coursehombuf{$env{'request.course.id'}}=
                   2289:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   2290:     $coursedescrbuf{$env{'request.course.id'}}=
                   2291:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   2292:     $courseinstcodebuf{$env{'request.course.id'}}=
                   2293:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   2294:     $courseownerbuf{$env{'request.course.id'}}=
                   2295:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  2296:     $coursetypebuf{$env{'request.course.id'}}=
                   2297:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 2298:     if (defined $courselogs{$env{'request.course.id'}}) {
                   2299: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      2300:     } else {
1.620     albertel 2301: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      2302:     }
1.620     albertel 2303:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      2304: 	&flushcourselogs();
                   2305:     }
1.158     www      2306: }
                   2307: 
                   2308: sub courseacclog {
                   2309:     my $fnsymb=shift;
1.620     albertel 2310:     unless ($env{'request.course.id'}) { return ''; }
                   2311:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 2312:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      2313:         $what.=':POST';
1.583     matthew  2314:         # FIXME: Probably ought to escape things....
1.800     albertel 2315: 	foreach my $key (keys(%env)) {
                   2316:             if ($key=~/^form\.(.*)/) {
                   2317: 		$what.=':'.$1.'='.$env{$key};
1.158     www      2318:             }
1.191     harris41 2319:         }
1.583     matthew  2320:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   2321:         # FIXME: We should not be depending on a form parameter that someone
                   2322:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 2323:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  2324:             $what.= ':POST';
                   2325:             # FIXME: Probably ought to escape things....
                   2326:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   2327:                                  'crsdiscuss') {
1.620     albertel 2328:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  2329:             }
                   2330:         }
1.158     www      2331:     }
                   2332:     &courselog($what);
1.149     www      2333: }
                   2334: 
1.185     www      2335: sub countacc {
                   2336:     my $url=&declutter(shift);
1.458     matthew  2337:     return if (! defined($url) || $url eq '');
1.620     albertel 2338:     unless ($env{'request.course.id'}) { return ''; }
                   2339:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      2340:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  2341:     $accesshash{$key}++;
1.185     www      2342: }
1.349     www      2343: 
1.361     www      2344: sub linklog {
                   2345:     my ($from,$to)=@_;
                   2346:     $from=&declutter($from);
                   2347:     $to=&declutter($to);
                   2348:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   2349:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   2350: }
                   2351:   
1.349     www      2352: sub userrolelog {
                   2353:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  2354:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  2355:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  2356:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   2357:         ($trole=~/^ta/)) {
1.350     www      2358:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2359:        $userrolehash
                   2360:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      2361:                     =$tend.':'.$tstart;
1.662     raeburn  2362:     }
1.898     albertel 2363:     if (($env{'request.role'} =~ /dc\./) &&
                   2364: 	(($trole=~/^au/) || ($trole=~/^in/) ||
                   2365: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
                   2366: 	 ($trole=~/^cr/) || ($trole=~/^ta/))) {
                   2367:        $userrolehash
                   2368:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   2369:                     =$tend.':'.$tstart;
                   2370:     }
1.662     raeburn  2371:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   2372:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   2373:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   2374:         ($trole=~/^sc/)) {
                   2375:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2376:        $domainrolehash
                   2377:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   2378:                     = $tend.':'.$tstart;
                   2379:     }
1.351     www      2380: }
                   2381: 
                   2382: sub get_course_adv_roles {
                   2383:     my $cid=shift;
1.620     albertel 2384:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      2385:     my %coursehash=&coursedescription($cid);
1.470     www      2386:     my %nothide=();
1.800     albertel 2387:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2388: 	$nothide{join(':',split(/[\@\:]/,$user))}=1;
1.470     www      2389:     }
1.351     www      2390:     my %returnhash=();
                   2391:     my %dumphash=
                   2392:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   2393:     my $now=time;
1.800     albertel 2394:     foreach my $entry (keys %dumphash) {
                   2395: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      2396:         if (($tstart) && ($tstart<0)) { next; }
                   2397:         if (($tend) && ($tend<$now)) { next; }
                   2398:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 2399:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 2400: 	if ($username eq '' || $domain eq '') { next; }
1.470     www      2401: 	if ((&privileged($username,$domain)) && 
                   2402: 	    (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 2403: 	if ($role eq 'cr') { next; }
1.351     www      2404:         my $key=&plaintext($role);
                   2405:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
                   2406:         if ($returnhash{$key}) {
                   2407: 	    $returnhash{$key}.=','.$username.':'.$domain;
                   2408:         } else {
                   2409:             $returnhash{$key}=$username.':'.$domain;
                   2410:         }
1.400     www      2411:      }
                   2412:     return %returnhash;
                   2413: }
                   2414: 
                   2415: sub get_my_roles {
1.858     raeburn  2416:     my ($uname,$udom,$context,$types,$roles,$roledoms)=@_;
1.620     albertel 2417:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   2418:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.858     raeburn  2419:     my %dumphash;
                   2420:     if ($context eq 'userroles') { 
                   2421:         %dumphash = &dump('roles',$udom,$uname);
                   2422:     } else {
                   2423:         %dumphash=
1.400     www      2424:             &dump('nohist_userroles',$udom,$uname);
1.858     raeburn  2425:     }
1.400     www      2426:     my %returnhash=();
                   2427:     my $now=time;
1.800     albertel 2428:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  2429:         my ($role,$tend,$tstart);
                   2430:         if ($context eq 'userroles') {
                   2431: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   2432:         } else {
                   2433:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   2434:         }
1.400     www      2435:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  2436:         my $status = 'active';
                   2437:         if (($tend) && ($tend<$now)) {
                   2438:             $status = 'previous';
                   2439:         } 
                   2440:         if (($tstart) && ($now<$tstart)) {
                   2441:             $status = 'future';
                   2442:         }
                   2443:         if (ref($types) eq 'ARRAY') {
                   2444:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   2445:                 next;
                   2446:             } 
                   2447:         } else {
                   2448:             if ($status ne 'active') {
                   2449:                 next;
                   2450:             }
                   2451:         }
1.867     raeburn  2452:         my ($rolecode,$username,$domain,$section,$area);
                   2453:         if ($context eq 'userroles') {
                   2454:             ($area,$rolecode) = split(/_/,$entry);
                   2455:             (undef,$domain,$username,$section) = split(/\//,$area);
                   2456:         } else {
                   2457:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   2458:         }
1.832     raeburn  2459:         if (ref($roledoms) eq 'ARRAY') {
                   2460:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   2461:                 next;
                   2462:             }
                   2463:         }
                   2464:         if (ref($roles) eq 'ARRAY') {
                   2465:             if (!grep(/^\Q$role\E$/,@{$roles})) {
                   2466:                 next;
                   2467:             }
1.867     raeburn  2468:         }
1.400     www      2469: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
1.832     raeburn  2470:     }
1.373     www      2471:     return %returnhash;
1.399     www      2472: }
                   2473: 
                   2474: # ----------------------------------------------------- Frontpage Announcements
                   2475: #
                   2476: #
                   2477: 
                   2478: sub postannounce {
                   2479:     my ($server,$text)=@_;
1.844     albertel 2480:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      2481:     unless ($text=~/\w/) { $text=''; }
                   2482:     return &reply('setannounce:'.&escape($text),$server);
                   2483: }
                   2484: 
                   2485: sub getannounce {
1.448     albertel 2486: 
                   2487:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      2488: 	my $announcement='';
1.800     albertel 2489: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 2490: 	close($fh);
1.399     www      2491: 	if ($announcement=~/\w/) { 
                   2492: 	    return 
                   2493:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 2494:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      2495: 	} else {
                   2496: 	    return '';
                   2497: 	}
                   2498:     } else {
                   2499: 	return '';
                   2500:     }
1.351     www      2501: }
1.353     www      2502: 
                   2503: # ---------------------------------------------------------- Course ID routines
                   2504: # Deal with domain's nohist_courseid.db files
                   2505: #
                   2506: 
                   2507: sub courseidput {
                   2508:     my ($domain,$what,$coursehome)=@_;
                   2509:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   2510: }
                   2511: 
                   2512: sub courseiddump {
1.791     raeburn  2513:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok)=@_;
1.353     www      2514:     my %returnhash=();
1.355     www      2515:     unless ($domfilter) { $domfilter=''; }
1.845     albertel 2516:     my %libserv = &all_library();
                   2517:     foreach my $tryserver (keys(%libserv)) {
                   2518:         if ( (  $hostidflag == 1 
                   2519: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   2520: 	     || (!defined($hostidflag)) ) {
                   2521: 
                   2522: 	    if ($domfilter eq ''
                   2523: 		|| (&host_domain($tryserver) eq $domfilter)) {
1.800     albertel 2524: 	        foreach my $line (
1.844     albertel 2525:                  split(/\&/,&reply('courseiddump:'.&host_domain($tryserver).':'.
1.571     raeburn  2526: 			       $sincefilter.':'.&escape($descfilter).':'.
1.791     raeburn  2527:                                &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter).':'.&escape($typefilter).':'.&escape($regexp_ok),
1.354     www      2528:                                $tryserver))) {
1.800     albertel 2529: 		    my ($key,$value)=split(/\=/,$line,2);
1.506     raeburn  2530:                     if (($key) && ($value)) {
1.516     raeburn  2531: 		        $returnhash{&unescape($key)}=$value;
1.506     raeburn  2532:                     }
1.353     www      2533:                 }
                   2534:             }
                   2535:         }
                   2536:     }
                   2537:     return %returnhash;
                   2538: }
                   2539: 
1.658     raeburn  2540: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  2541: 
                   2542: sub dcmailput {
1.685     raeburn  2543:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  2544:     my $status = &Apache::lonnet::critical(
1.740     www      2545:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   2546:        &escape($message),$server);
1.662     raeburn  2547:     return $status;
                   2548: }
                   2549: 
1.658     raeburn  2550: sub dcmaildump {
                   2551:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  2552:     my %returnhash=();
1.846     albertel 2553: 
                   2554:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  2555:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   2556:                                                          &escape($enddate).':';
                   2557: 	my @esc_senders=map { &escape($_)} @$senders;
                   2558: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 2559: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 2560:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  2561:             if (($key) && ($value)) {
                   2562:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  2563:             }
                   2564:         }
                   2565:     }
                   2566:     return %returnhash;
                   2567: }
1.662     raeburn  2568: # ---------------------------------------------------------- Domain roles
                   2569: 
                   2570: sub get_domain_roles {
                   2571:     my ($dom,$roles,$startdate,$enddate)=@_;
                   2572:     if (undef($startdate) || $startdate eq '') {
                   2573:         $startdate = '.';
                   2574:     }
                   2575:     if (undef($enddate) || $enddate eq '') {
                   2576:         $enddate = '.';
                   2577:     }
                   2578:     my $rolelist = join(':',@{$roles});
                   2579:     my %personnel = ();
1.841     albertel 2580: 
                   2581:     my %servers = &get_servers($dom,'library');
                   2582:     foreach my $tryserver (keys(%servers)) {
                   2583: 	%{$personnel{$tryserver}}=();
                   2584: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   2585: 					    &escape($startdate).':'.
                   2586: 					    &escape($enddate).':'.
                   2587: 					    &escape($rolelist), $tryserver))) {
                   2588: 	    my ($key,$value) = split(/\=/,$line,2);
                   2589: 	    if (($key) && ($value)) {
                   2590: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   2591: 	    }
                   2592: 	}
1.662     raeburn  2593:     }
                   2594:     return %personnel;
                   2595: }
1.658     raeburn  2596: 
1.149     www      2597: # ----------------------------------------------------------- Check out an item
                   2598: 
1.504     albertel 2599: sub get_first_access {
                   2600:     my ($type,$argsymb)=@_;
1.790     albertel 2601:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2602:     if ($argsymb) { $symb=$argsymb; }
                   2603:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2604:     if ($type eq 'map') {
                   2605: 	$res=&symbread($map);
                   2606:     } else {
                   2607: 	$res=$symb;
                   2608:     }
                   2609:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   2610:     return $times{"$courseid\0$res"};
1.504     albertel 2611: }
                   2612: 
                   2613: sub set_first_access {
                   2614:     my ($type)=@_;
1.790     albertel 2615:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2616:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2617:     if ($type eq 'map') {
                   2618: 	$res=&symbread($map);
                   2619:     } else {
                   2620: 	$res=$symb;
                   2621:     }
                   2622:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 2623:     if (!$firstaccess) {
1.588     albertel 2624: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 2625:     }
                   2626:     return 'already_set';
1.504     albertel 2627: }
                   2628: 
1.149     www      2629: sub checkout {
                   2630:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   2631:     my $now=time;
                   2632:     my $lonhost=$perlvar{'lonHostID'};
                   2633:     my $infostr=&escape(
1.234     www      2634:                  'CHECKOUTTOKEN&'.
1.149     www      2635:                  $tuname.'&'.
                   2636:                  $tudom.'&'.
                   2637:                  $tcrsid.'&'.
                   2638:                  $symb.'&'.
                   2639: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   2640:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      2641:     if ($token=~/^error\:/) { 
1.672     albertel 2642:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2643:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2644:                  "</font>");
                   2645:         return ''; 
                   2646:     }
                   2647: 
1.149     www      2648:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   2649:     $token=~tr/a-z/A-Z/;
                   2650: 
1.153     www      2651:     my %infohash=('resource.0.outtoken' => $token,
                   2652:                   'resource.0.checkouttime' => $now,
                   2653:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      2654: 
                   2655:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2656:        return '';
1.151     www      2657:     } else {
1.672     albertel 2658:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2659:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2660:                  "</font>");
1.149     www      2661:     }    
                   2662: 
                   2663:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2664:                          &escape('Checkout '.$infostr.' - '.
                   2665:                                                  $token)) ne 'ok') {
                   2666: 	return '';
1.151     www      2667:     } else {
1.672     albertel 2668:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2669:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2670:                  "</font>");
1.149     www      2671:     }
1.151     www      2672:     return $token;
1.149     www      2673: }
                   2674: 
                   2675: # ------------------------------------------------------------ Check in an item
                   2676: 
                   2677: sub checkin {
                   2678:     my $token=shift;
1.150     www      2679:     my $now=time;
                   2680:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   2681:     $lonhost=~tr/A-Z/a-z/;
1.838     albertel 2682:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150     www      2683:     $dtoken=~s/\W/\_/g;
1.234     www      2684:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      2685:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   2686: 
1.154     www      2687:     unless (($tuname) && ($tudom)) {
                   2688:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   2689:         return '';
                   2690:     }
                   2691:     
                   2692:     unless (&allowed('mgr',$tcrsid)) {
                   2693:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 2694:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      2695:         return '';
                   2696:     }
                   2697: 
1.153     www      2698:     my %infohash=('resource.0.intoken' => $token,
                   2699:                   'resource.0.checkintime' => $now,
                   2700:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      2701: 
                   2702:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2703:        return '';
                   2704:     }    
                   2705: 
                   2706:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2707:                          &escape('Checkin - '.$token)) ne 'ok') {
                   2708: 	return '';
                   2709:     }
                   2710: 
                   2711:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      2712: }
                   2713: 
                   2714: # --------------------------------------------- Set Expire Date for Spreadsheet
                   2715: 
                   2716: sub expirespread {
                   2717:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 2718:     my $cid=$env{'request.course.id'}; 
1.110     www      2719:     if ($cid) {
                   2720:        my $now=time;
                   2721:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 2722:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   2723:                             $env{'course.'.$cid.'.num'}.
1.110     www      2724: 	        	    ':nohist_expirationdates:'.
                   2725:                             &escape($key).'='.$now,
1.620     albertel 2726:                             $env{'course.'.$cid.'.home'})
1.110     www      2727:     }
                   2728:     return 'ok';
1.14      www      2729: }
                   2730: 
1.109     www      2731: # ----------------------------------------------------- Devalidate Spreadsheets
                   2732: 
                   2733: sub devalidate {
1.325     www      2734:     my ($symb,$uname,$udom)=@_;
1.620     albertel 2735:     my $cid=$env{'request.course.id'}; 
1.109     www      2736:     if ($cid) {
1.391     matthew  2737:         # delete the stored spreadsheets for
                   2738:         # - the student level sheet of this user in course's homespace
                   2739:         # - the assessment level sheet for this resource 
                   2740:         #   for this user in user's homespace
1.553     albertel 2741: 	# - current conditional state info
1.325     www      2742: 	my $key=$uname.':'.$udom.':';
1.109     www      2743:         my $status=
1.299     matthew  2744: 	    &del('nohist_calculatedsheets',
1.391     matthew  2745: 		 [$key.'studentcalc:'],
1.620     albertel 2746: 		 $env{'course.'.$cid.'.domain'},
                   2747: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 2748: 		.' '.
                   2749: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  2750: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      2751:         unless ($status eq 'ok ok') {
                   2752:            &logthis('Could not devalidate spreadsheet '.
1.325     www      2753:                     $uname.' at '.$udom.' for '.
1.109     www      2754: 		    $symb.': '.$status);
1.133     albertel 2755:         }
1.553     albertel 2756: 	&delenv('user.state.'.$cid);
1.109     www      2757:     }
                   2758: }
                   2759: 
1.265     albertel 2760: sub get_scalar {
                   2761:     my ($string,$end) = @_;
                   2762:     my $value;
                   2763:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   2764: 	$value = $1;
                   2765:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   2766: 	$value = $1;
                   2767:     }
                   2768:     return &unescape($value);
                   2769: }
                   2770: 
                   2771: sub array2str {
                   2772:   my (@array) = @_;
                   2773:   my $result=&arrayref2str(\@array);
                   2774:   $result=~s/^__ARRAY_REF__//;
                   2775:   $result=~s/__END_ARRAY_REF__$//;
                   2776:   return $result;
                   2777: }
                   2778: 
1.204     albertel 2779: sub arrayref2str {
                   2780:   my ($arrayref) = @_;
1.265     albertel 2781:   my $result='__ARRAY_REF__';
1.204     albertel 2782:   foreach my $elem (@$arrayref) {
1.265     albertel 2783:     if(ref($elem) eq 'ARRAY') {
                   2784:       $result.=&arrayref2str($elem).'&';
                   2785:     } elsif(ref($elem) eq 'HASH') {
                   2786:       $result.=&hashref2str($elem).'&';
                   2787:     } elsif(ref($elem)) {
                   2788:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 2789:     } else {
                   2790:       $result.=&escape($elem).'&';
                   2791:     }
                   2792:   }
                   2793:   $result=~s/\&$//;
1.265     albertel 2794:   $result .= '__END_ARRAY_REF__';
1.204     albertel 2795:   return $result;
                   2796: }
                   2797: 
1.168     albertel 2798: sub hash2str {
1.204     albertel 2799:   my (%hash) = @_;
                   2800:   my $result=&hashref2str(\%hash);
1.265     albertel 2801:   $result=~s/^__HASH_REF__//;
                   2802:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 2803:   return $result;
                   2804: }
                   2805: 
                   2806: sub hashref2str {
                   2807:   my ($hashref)=@_;
1.265     albertel 2808:   my $result='__HASH_REF__';
1.800     albertel 2809:   foreach my $key (sort(keys(%$hashref))) {
                   2810:     if (ref($key) eq 'ARRAY') {
                   2811:       $result.=&arrayref2str($key).'=';
                   2812:     } elsif (ref($key) eq 'HASH') {
                   2813:       $result.=&hashref2str($key).'=';
                   2814:     } elsif (ref($key)) {
1.265     albertel 2815:       $result.='=';
1.800     albertel 2816:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 2817:     } else {
1.800     albertel 2818: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 2819:     }
                   2820: 
1.800     albertel 2821:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   2822:       $result.=&arrayref2str($hashref->{$key}).'&';
                   2823:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   2824:       $result.=&hashref2str($hashref->{$key}).'&';
                   2825:     } elsif(ref($hashref->{$key})) {
1.265     albertel 2826:        $result.='&';
1.800     albertel 2827:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 2828:     } else {
1.800     albertel 2829:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 2830:     }
                   2831:   }
1.168     albertel 2832:   $result=~s/\&$//;
1.265     albertel 2833:   $result .= '__END_HASH_REF__';
1.168     albertel 2834:   return $result;
                   2835: }
                   2836: 
                   2837: sub str2hash {
1.265     albertel 2838:     my ($string)=@_;
                   2839:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   2840:     return %$hash;
                   2841: }
                   2842: 
                   2843: sub str2hashref {
1.168     albertel 2844:   my ($string) = @_;
1.265     albertel 2845: 
                   2846:   my %hash;
                   2847: 
                   2848:   if($string !~ /^__HASH_REF__/) {
                   2849:       if (! ($string eq '' || !defined($string))) {
                   2850: 	  $hash{'error'}='Not hash reference';
                   2851:       }
                   2852:       return (\%hash, $string);
                   2853:   }
                   2854: 
                   2855:   $string =~ s/^__HASH_REF__//;
                   2856: 
                   2857:   while($string !~ /^__END_HASH_REF__/) {
                   2858:       #key
                   2859:       my $key='';
                   2860:       if($string =~ /^__HASH_REF__/) {
                   2861:           ($key, $string)=&str2hashref($string);
                   2862:           if(defined($key->{'error'})) {
                   2863:               $hash{'error'}='Bad data';
                   2864:               return (\%hash, $string);
                   2865:           }
                   2866:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2867:           ($key, $string)=&str2arrayref($string);
                   2868:           if($key->[0] eq 'Array reference error') {
                   2869:               $hash{'error'}='Bad data';
                   2870:               return (\%hash, $string);
                   2871:           }
                   2872:       } else {
                   2873:           $string =~ s/^(.*?)=//;
1.267     albertel 2874: 	  $key=&unescape($1);
1.265     albertel 2875:       }
                   2876:       $string =~ s/^=//;
                   2877: 
                   2878:       #value
                   2879:       my $value='';
                   2880:       if($string =~ /^__HASH_REF__/) {
                   2881:           ($value, $string)=&str2hashref($string);
                   2882:           if(defined($value->{'error'})) {
                   2883:               $hash{'error'}='Bad data';
                   2884:               return (\%hash, $string);
                   2885:           }
                   2886:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2887:           ($value, $string)=&str2arrayref($string);
                   2888:           if($value->[0] eq 'Array reference error') {
                   2889:               $hash{'error'}='Bad data';
                   2890:               return (\%hash, $string);
                   2891:           }
                   2892:       } else {
                   2893: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   2894:       }
                   2895:       $string =~ s/^&//;
                   2896: 
                   2897:       $hash{$key}=$value;
1.204     albertel 2898:   }
1.265     albertel 2899: 
                   2900:   $string =~ s/^__END_HASH_REF__//;
                   2901: 
                   2902:   return (\%hash, $string);
1.204     albertel 2903: }
                   2904: 
                   2905: sub str2array {
1.265     albertel 2906:     my ($string)=@_;
                   2907:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   2908:     return @$array;
                   2909: }
                   2910: 
                   2911: sub str2arrayref {
1.204     albertel 2912:   my ($string) = @_;
1.265     albertel 2913:   my @array;
                   2914: 
                   2915:   if($string !~ /^__ARRAY_REF__/) {
                   2916:       if (! ($string eq '' || !defined($string))) {
                   2917: 	  $array[0]='Array reference error';
                   2918:       }
                   2919:       return (\@array, $string);
                   2920:   }
                   2921: 
                   2922:   $string =~ s/^__ARRAY_REF__//;
                   2923: 
                   2924:   while($string !~ /^__END_ARRAY_REF__/) {
                   2925:       my $value='';
                   2926:       if($string =~ /^__HASH_REF__/) {
                   2927:           ($value, $string)=&str2hashref($string);
                   2928:           if(defined($value->{'error'})) {
                   2929:               $array[0] ='Array reference error';
                   2930:               return (\@array, $string);
                   2931:           }
                   2932:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2933:           ($value, $string)=&str2arrayref($string);
                   2934:           if($value->[0] eq 'Array reference error') {
                   2935:               $array[0] ='Array reference error';
                   2936:               return (\@array, $string);
                   2937:           }
                   2938:       } else {
                   2939: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   2940:       }
                   2941:       $string =~ s/^&//;
                   2942: 
                   2943:       push(@array, $value);
1.191     harris41 2944:   }
1.265     albertel 2945: 
                   2946:   $string =~ s/^__END_ARRAY_REF__//;
                   2947: 
                   2948:   return (\@array, $string);
1.168     albertel 2949: }
                   2950: 
1.167     albertel 2951: # -------------------------------------------------------------------Temp Store
                   2952: 
1.168     albertel 2953: sub tmpreset {
                   2954:   my ($symb,$namespace,$domain,$stuname) = @_;
                   2955:   if (!$symb) {
                   2956:     $symb=&symbread();
1.620     albertel 2957:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2958:   }
                   2959:   $symb=escape($symb);
                   2960: 
1.620     albertel 2961:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 2962:   $namespace=~s/\//\_/g;
                   2963:   $namespace=~s/\W//g;
                   2964: 
1.620     albertel 2965:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2966:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2967:   if ($domain eq 'public' && $stuname eq 'public') {
                   2968:       $stuname=$ENV{'REMOTE_ADDR'};
                   2969:   }
1.168     albertel 2970:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2971:   my %hash;
                   2972:   if (tie(%hash,'GDBM_File',
                   2973: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2974: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2975:     foreach my $key (keys %hash) {
1.180     albertel 2976:       if ($key=~ /:$symb/) {
1.168     albertel 2977: 	delete($hash{$key});
                   2978:       }
                   2979:     }
                   2980:   }
                   2981: }
                   2982: 
1.167     albertel 2983: sub tmpstore {
1.168     albertel 2984:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2985: 
                   2986:   if (!$symb) {
                   2987:     $symb=&symbread();
1.620     albertel 2988:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2989:   }
                   2990:   $symb=escape($symb);
                   2991: 
                   2992:   if (!$namespace) {
                   2993:     # I don't think we would ever want to store this for a course.
                   2994:     # it seems this will only be used if we don't have a course.
1.620     albertel 2995:     #$namespace=$env{'request.course.id'};
1.168     albertel 2996:     #if (!$namespace) {
1.620     albertel 2997:       $namespace=$env{'request.state'};
1.168     albertel 2998:     #}
                   2999:   }
                   3000:   $namespace=~s/\//\_/g;
                   3001:   $namespace=~s/\W//g;
1.620     albertel 3002:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3003:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3004:   if ($domain eq 'public' && $stuname eq 'public') {
                   3005:       $stuname=$ENV{'REMOTE_ADDR'};
                   3006:   }
1.168     albertel 3007:   my $now=time;
                   3008:   my %hash;
                   3009:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3010:   if (tie(%hash,'GDBM_File',
                   3011: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3012: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3013:     $hash{"version:$symb"}++;
                   3014:     my $version=$hash{"version:$symb"};
                   3015:     my $allkeys=''; 
                   3016:     foreach my $key (keys(%$storehash)) {
                   3017:       $allkeys.=$key.':';
1.591     albertel 3018:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 3019:     }
                   3020:     $hash{"$version:$symb:timestamp"}=$now;
                   3021:     $allkeys.='timestamp';
                   3022:     $hash{"$version:keys:$symb"}=$allkeys;
                   3023:     if (untie(%hash)) {
                   3024:       return 'ok';
                   3025:     } else {
                   3026:       return "error:$!";
                   3027:     }
                   3028:   } else {
                   3029:     return "error:$!";
                   3030:   }
                   3031: }
1.167     albertel 3032: 
1.168     albertel 3033: # -----------------------------------------------------------------Temp Restore
1.167     albertel 3034: 
1.168     albertel 3035: sub tmprestore {
                   3036:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 3037: 
1.168     albertel 3038:   if (!$symb) {
                   3039:     $symb=&symbread();
1.620     albertel 3040:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3041:   }
                   3042:   $symb=escape($symb);
                   3043: 
1.620     albertel 3044:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 3045: 
1.620     albertel 3046:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3047:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3048:   if ($domain eq 'public' && $stuname eq 'public') {
                   3049:       $stuname=$ENV{'REMOTE_ADDR'};
                   3050:   }
1.168     albertel 3051:   my %returnhash;
                   3052:   $namespace=~s/\//\_/g;
                   3053:   $namespace=~s/\W//g;
                   3054:   my %hash;
                   3055:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3056:   if (tie(%hash,'GDBM_File',
                   3057: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3058: 	  &GDBM_READER(),0640)) {
1.168     albertel 3059:     my $version=$hash{"version:$symb"};
                   3060:     $returnhash{'version'}=$version;
                   3061:     my $scope;
                   3062:     for ($scope=1;$scope<=$version;$scope++) {
                   3063:       my $vkeys=$hash{"$scope:keys:$symb"};
                   3064:       my @keys=split(/:/,$vkeys);
                   3065:       my $key;
                   3066:       $returnhash{"$scope:keys"}=$vkeys;
                   3067:       foreach $key (@keys) {
1.591     albertel 3068: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   3069: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 3070:       }
                   3071:     }
1.168     albertel 3072:     if (!(untie(%hash))) {
                   3073:       return "error:$!";
                   3074:     }
                   3075:   } else {
                   3076:     return "error:$!";
                   3077:   }
                   3078:   return %returnhash;
1.167     albertel 3079: }
                   3080: 
1.9       www      3081: # ----------------------------------------------------------------------- Store
                   3082: 
                   3083: sub store {
1.124     www      3084:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3085:     my $home='';
                   3086: 
1.168     albertel 3087:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3088: 
1.213     www      3089:     $symb=&symbclean($symb);
1.122     albertel 3090:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3091: 
1.620     albertel 3092:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3093:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3094: 
                   3095:     &devalidate($symb,$stuname,$domain);
1.109     www      3096: 
                   3097:     $symb=escape($symb);
1.187     www      3098:     if (!$namespace) { 
1.620     albertel 3099:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3100:           return ''; 
                   3101:        } 
                   3102:     }
1.620     albertel 3103:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3104: 
                   3105:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3106:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   3107: 
1.12      www      3108:     my $namevalue='';
1.800     albertel 3109:     foreach my $key (keys(%$storehash)) {
                   3110:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3111:     }
1.12      www      3112:     $namevalue=~s/\&$//;
1.187     www      3113:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      3114:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      3115: }
                   3116: 
1.47      www      3117: # -------------------------------------------------------------- Critical Store
                   3118: 
                   3119: sub cstore {
1.124     www      3120:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3121:     my $home='';
                   3122: 
1.168     albertel 3123:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3124: 
1.213     www      3125:     $symb=&symbclean($symb);
1.122     albertel 3126:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3127: 
1.620     albertel 3128:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3129:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3130: 
                   3131:     &devalidate($symb,$stuname,$domain);
1.109     www      3132: 
                   3133:     $symb=escape($symb);
1.187     www      3134:     if (!$namespace) { 
1.620     albertel 3135:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3136:           return ''; 
                   3137:        } 
                   3138:     }
1.620     albertel 3139:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3140: 
                   3141:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3142:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 3143: 
1.47      www      3144:     my $namevalue='';
1.800     albertel 3145:     foreach my $key (keys(%$storehash)) {
                   3146:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3147:     }
1.47      www      3148:     $namevalue=~s/\&$//;
1.187     www      3149:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      3150:     return critical
                   3151:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      3152: }
                   3153: 
1.9       www      3154: # --------------------------------------------------------------------- Restore
                   3155: 
                   3156: sub restore {
1.124     www      3157:     my ($symb,$namespace,$domain,$stuname) = @_;
                   3158:     my $home='';
                   3159: 
1.168     albertel 3160:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3161: 
1.122     albertel 3162:     if (!$symb) {
                   3163:       unless ($symb=escape(&symbread())) { return ''; }
                   3164:     } else {
1.213     www      3165:       $symb=&escape(&symbclean($symb));
1.122     albertel 3166:     }
1.188     www      3167:     if (!$namespace) { 
1.620     albertel 3168:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      3169:           return ''; 
                   3170:        } 
                   3171:     }
1.620     albertel 3172:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3173:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   3174:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 3175:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   3176: 
1.12      www      3177:     my %returnhash=();
1.800     albertel 3178:     foreach my $line (split(/\&/,$answer)) {
                   3179: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 3180:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 3181:     }
1.75      www      3182:     my $version;
                   3183:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 3184:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   3185:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 3186:        }
1.75      www      3187:     }
1.13      www      3188:     return %returnhash;
1.34      www      3189: }
                   3190: 
                   3191: # ---------------------------------------------------------- Course Description
                   3192: 
                   3193: sub coursedescription {
1.731     albertel 3194:     my ($courseid,$args)=@_;
1.34      www      3195:     $courseid=~s/^\///;
1.49      www      3196:     $courseid=~s/\_/\//g;
1.34      www      3197:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 3198:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 3199:     my $normalid=$cdomain.'_'.$cnum;
                   3200:     # need to always cache even if we get errors otherwise we keep 
                   3201:     # trying and trying and trying to get the course description.
                   3202:     my %envhash=();
                   3203:     my %returnhash=();
1.731     albertel 3204:     
                   3205:     my $expiretime=600;
                   3206:     if ($env{'request.course.id'} eq $normalid) {
                   3207: 	$expiretime=120;
                   3208:     }
                   3209: 
                   3210:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   3211:     if (!$args->{'freshen_cache'}
                   3212: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   3213: 	foreach my $key (keys(%env)) {
                   3214: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   3215: 	    my ($setting) = $1;
                   3216: 	    $returnhash{$setting} = $env{$key};
                   3217: 	}
                   3218: 	return %returnhash;
                   3219:     }
                   3220: 
                   3221:     # get the data agin
                   3222:     if (!$args->{'one_time'}) {
                   3223: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   3224:     }
1.811     albertel 3225: 
1.34      www      3226:     if ($chome ne 'no_host') {
1.302     albertel 3227:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 3228:        if (!exists($returnhash{'con_lost'})) {
                   3229:            $returnhash{'home'}= $chome;
                   3230: 	   $returnhash{'domain'} = $cdomain;
                   3231: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  3232:            if (!defined($returnhash{'type'})) {
                   3233:                $returnhash{'type'} = 'Course';
                   3234:            }
1.130     albertel 3235:            while (my ($name,$value) = each %returnhash) {
1.53      www      3236:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 3237:            }
1.270     www      3238:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      3239:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 3240: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      3241:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   3242:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   3243:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      3244:        }
                   3245:     }
1.731     albertel 3246:     if (!$args->{'one_time'}) {
                   3247: 	&appenv(%envhash);
                   3248:     }
1.302     albertel 3249:     return %returnhash;
1.461     www      3250: }
                   3251: 
                   3252: # -------------------------------------------------See if a user is privileged
                   3253: 
                   3254: sub privileged {
                   3255:     my ($username,$domain)=@_;
                   3256:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   3257: 			&homeserver($username,$domain));
                   3258:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   3259:     my $now=time;
                   3260:     if ($rolesdump ne '') {
1.800     albertel 3261:         foreach my $entry (split(/&/,$rolesdump)) {
                   3262: 	    if ($entry!~/^rolesdef_/) {
                   3263: 		my ($area,$role)=split(/=/,$entry);
1.461     www      3264: 		$area=~s/\_\w\w$//;
                   3265: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   3266: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   3267: 		    my $active=1;
                   3268: 		    if ($tend) {
                   3269: 			if ($tend<$now) { $active=0; }
                   3270: 		    }
                   3271: 		    if ($tstart) {
                   3272: 			if ($tstart>$now) { $active=0; }
                   3273: 		    }
                   3274: 		    if ($active) { return 1; }
                   3275: 		}
                   3276: 	    }
                   3277: 	}
                   3278:     }
                   3279:     return 0;
1.9       www      3280: }
1.1       albertel 3281: 
1.103     harris41 3282: # -------------------------------------------------------- Get user privileges
1.11      www      3283: 
                   3284: sub rolesinit {
                   3285:     my ($domain,$username,$authhost)=@_;
                   3286:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12      www      3287:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11      www      3288:     my %allroles=();
1.678     raeburn  3289:     my %allgroups=();   
1.11      www      3290:     my $now=time;
1.743     albertel 3291:     my %userroles = ('user.login.time' => $now);
1.678     raeburn  3292:     my $group_privs;
1.11      www      3293: 
                   3294:     if ($rolesdump ne '') {
1.800     albertel 3295:         foreach my $entry (split(/&/,$rolesdump)) {
                   3296: 	  if ($entry!~/^rolesdef_/) {
                   3297:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 3298: 	    $area=~s/\_\w\w$//;
1.678     raeburn  3299:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 3300: 	    if ($role=~/^cr/) { 
1.807     albertel 3301: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   3302: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 3303: 		    ($tend,$tstart)=split('_',$trest);
                   3304: 		} else {
                   3305: 		    $trole=$role;
                   3306: 		}
1.678     raeburn  3307:             } elsif ($role =~ m|^gr/|) {
                   3308:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   3309:                 ($trole,$group_privs) = split(/\//,$trole);
                   3310:                 $group_privs = &unescape($group_privs);
1.587     albertel 3311: 	    } else {
                   3312: 		($trole,$tend,$tstart)=split(/_/,$role);
                   3313: 	    }
1.743     albertel 3314: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   3315: 					 $username);
                   3316: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  3317:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   3318:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      3319:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 3320: 		my $spec=$trole.'.'.$area;
                   3321: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   3322: 		if ($trole =~ /^cr\//) {
1.567     raeburn  3323:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  3324:                 } elsif ($trole eq 'gr') {
                   3325:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 3326: 		} else {
1.567     raeburn  3327:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 3328: 		}
1.12      www      3329:             }
1.662     raeburn  3330:           }
1.191     harris41 3331:         }
1.743     albertel 3332:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   3333:         $userroles{'user.adv'}    = $adv;
                   3334: 	$userroles{'user.author'} = $author;
1.620     albertel 3335:         $env{'user.adv'}=$adv;
1.11      www      3336:     }
1.743     albertel 3337:     return \%userroles;  
1.11      www      3338: }
                   3339: 
1.567     raeburn  3340: sub set_arearole {
                   3341:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   3342: # log the associated role with the area
                   3343:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 3344:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  3345: }
                   3346: 
                   3347: sub custom_roleprivs {
                   3348:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   3349:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   3350:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 3351:     if (&hostname($homsvr) ne '') {
1.567     raeburn  3352:         my ($rdummy,$roledef)=
                   3353:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   3354:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   3355:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   3356:             if (defined($syspriv)) {
                   3357:                 $$allroles{'cm./'}.=':'.$syspriv;
                   3358:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   3359:             }
                   3360:             if ($tdomain ne '') {
                   3361:                 if (defined($dompriv)) {
                   3362:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   3363:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   3364:                 }
                   3365:                 if (($trest ne '') && (defined($coursepriv))) {
                   3366:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   3367:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   3368:                 }
                   3369:             }
                   3370:         }
                   3371:     }
                   3372: }
                   3373: 
1.678     raeburn  3374: sub group_roleprivs {
                   3375:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   3376:     my $access = 1;
                   3377:     my $now = time;
                   3378:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   3379:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   3380:     if ($access) {
1.811     albertel 3381:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  3382:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   3383:     }
                   3384: }
1.567     raeburn  3385: 
                   3386: sub standard_roleprivs {
                   3387:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   3388:     if (defined($pr{$trole.':s'})) {
                   3389:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   3390:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   3391:     }
                   3392:     if ($tdomain ne '') {
                   3393:         if (defined($pr{$trole.':d'})) {
                   3394:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3395:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3396:         }
                   3397:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   3398:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   3399:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   3400:         }
                   3401:     }
                   3402: }
                   3403: 
                   3404: sub set_userprivs {
1.678     raeburn  3405:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  3406:     my $author=0;
                   3407:     my $adv=0;
1.678     raeburn  3408:     my %grouproles = ();
                   3409:     if (keys(%{$allgroups}) > 0) {
                   3410:         foreach my $role (keys %{$allroles}) {
1.681     raeburn  3411:             my ($trole,$area,$sec,$extendedarea);
1.881     raeburn  3412:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
1.678     raeburn  3413:                 $trole = $1;
                   3414:                 $area = $2;
1.681     raeburn  3415:                 $sec = $3;
                   3416:                 $extendedarea = $area.$sec;
                   3417:                 if (exists($$allgroups{$area})) {
                   3418:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   3419:                         my $spec = $trole.'.'.$extendedarea;
                   3420:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   3421:                                                 $$allgroups{$area}{$group};
1.678     raeburn  3422:                     }
                   3423:                 }
                   3424:             }
                   3425:         }
                   3426:     }
1.800     albertel 3427:     foreach my $group (keys(%grouproles)) {
                   3428:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  3429:     }
1.800     albertel 3430:     foreach my $role (keys(%{$allroles})) {
                   3431:         my %thesepriv;
                   3432:         if (($role=~/^au/) || ($role=~/^ca/)) { $author=1; }
                   3433:         foreach my $item (split(/:/,$$allroles{$role})) {
                   3434:             if ($item ne '') {
                   3435:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  3436:                 if ($restrictions eq '') {
                   3437:                     $thesepriv{$privilege}='F';
                   3438:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   3439:                     $thesepriv{$privilege}.=$restrictions;
                   3440:                 }
                   3441:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   3442:             }
                   3443:         }
                   3444:         my $thesestr='';
1.800     albertel 3445:         foreach my $priv (keys(%thesepriv)) {
                   3446: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   3447: 	}
                   3448:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  3449:     }
                   3450:     return ($author,$adv);
                   3451: }
                   3452: 
1.12      www      3453: # --------------------------------------------------------------- get interface
                   3454: 
                   3455: sub get {
1.131     albertel 3456:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3457:    my $items='';
1.800     albertel 3458:    foreach my $item (@$storearr) {
                   3459:        $items.=&escape($item).'&';
1.191     harris41 3460:    }
1.12      www      3461:    $items=~s/\&$//;
1.620     albertel 3462:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3463:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 3464:    my $uhome=&homeserver($uname,$udomain);
                   3465: 
1.133     albertel 3466:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3467:    my @pairs=split(/\&/,$rep);
1.273     albertel 3468:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   3469:      return @pairs;
                   3470:    }
1.15      www      3471:    my %returnhash=();
1.42      www      3472:    my $i=0;
1.800     albertel 3473:    foreach my $item (@$storearr) {
                   3474:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3475:       $i++;
1.191     harris41 3476:    }
1.15      www      3477:    return %returnhash;
1.27      www      3478: }
                   3479: 
                   3480: # --------------------------------------------------------------- del interface
                   3481: 
                   3482: sub del {
1.133     albertel 3483:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      3484:    my $items='';
1.800     albertel 3485:    foreach my $item (@$storearr) {
                   3486:        $items.=&escape($item).'&';
1.191     harris41 3487:    }
1.27      www      3488:    $items=~s/\&$//;
1.620     albertel 3489:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3490:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3491:    my $uhome=&homeserver($uname,$udomain);
                   3492: 
                   3493:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3494: }
                   3495: 
                   3496: # -------------------------------------------------------------- dump interface
                   3497: 
                   3498: sub dump {
1.755     albertel 3499:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   3500:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3501:     if (!$uname) { $uname=$env{'user.name'}; }
                   3502:     my $uhome=&homeserver($uname,$udomain);
                   3503:     if ($regexp) {
                   3504: 	$regexp=&escape($regexp);
                   3505:     } else {
                   3506: 	$regexp='.';
                   3507:     }
                   3508:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3509:     my @pairs=split(/\&/,$rep);
                   3510:     my %returnhash=();
                   3511:     foreach my $item (@pairs) {
                   3512: 	my ($key,$value)=split(/=/,$item,2);
                   3513: 	$key = &unescape($key);
                   3514: 	next if ($key =~ /^error: 2 /);
                   3515: 	$returnhash{$key}=&thaw_unescape($value);
                   3516:     }
                   3517:     return %returnhash;
1.407     www      3518: }
                   3519: 
1.717     albertel 3520: # --------------------------------------------------------- dumpstore interface
                   3521: 
                   3522: sub dumpstore {
                   3523:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 3524:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3525:    if (!$uname) { $uname=$env{'user.name'}; }
                   3526:    my $uhome=&homeserver($uname,$udomain);
                   3527:    if ($regexp) {
                   3528:        $regexp=&escape($regexp);
                   3529:    } else {
                   3530:        $regexp='.';
                   3531:    }
                   3532:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3533:    my @pairs=split(/\&/,$rep);
                   3534:    my %returnhash=();
                   3535:    foreach my $item (@pairs) {
                   3536:        my ($key,$value)=split(/=/,$item,2);
                   3537:        next if ($key =~ /^error: 2 /);
                   3538:        $returnhash{$key}=&thaw_unescape($value);
                   3539:    }
                   3540:    return %returnhash;
1.717     albertel 3541: }
                   3542: 
1.407     www      3543: # -------------------------------------------------------------- keys interface
                   3544: 
                   3545: sub getkeys {
                   3546:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 3547:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3548:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      3549:    my $uhome=&homeserver($uname,$udomain);
                   3550:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   3551:    my @keyarray=();
1.800     albertel 3552:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  3553:       next if ($key =~ /^error: 2 /);
1.800     albertel 3554:       push(@keyarray,&unescape($key));
1.407     www      3555:    }
                   3556:    return @keyarray;
1.318     matthew  3557: }
                   3558: 
1.319     matthew  3559: # --------------------------------------------------------------- currentdump
                   3560: sub currentdump {
1.328     matthew  3561:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 3562:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   3563:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   3564:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  3565:    my $uhome = &homeserver($sname,$sdom);
                   3566:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  3567:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  3568:    #
1.318     matthew  3569:    my %returnhash=();
1.319     matthew  3570:    #
                   3571:    if ($rep eq "unknown_cmd") { 
                   3572:        # an old lond will not know currentdump
                   3573:        # Do a dump and make it look like a currentdump
1.822     albertel 3574:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  3575:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   3576:        my %hash = @tmp;
                   3577:        @tmp=();
1.424     matthew  3578:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  3579:    } else {
                   3580:        my @pairs=split(/\&/,$rep);
1.800     albertel 3581:        foreach my $pair (@pairs) {
                   3582:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  3583:            my ($symb,$param) = split(/:/,$key);
                   3584:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 3585:                                                         &thaw_unescape($value);
1.319     matthew  3586:        }
1.191     harris41 3587:    }
1.12      www      3588:    return %returnhash;
1.424     matthew  3589: }
                   3590: 
                   3591: sub convert_dump_to_currentdump{
                   3592:     my %hash = %{shift()};
                   3593:     my %returnhash;
                   3594:     # Code ripped from lond, essentially.  The only difference
                   3595:     # here is the unescaping done by lonnet::dump().  Conceivably
                   3596:     # we might run in to problems with parameter names =~ /^v\./
                   3597:     while (my ($key,$value) = each(%hash)) {
                   3598:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 3599: 	$symb  = &unescape($symb);
                   3600: 	$param = &unescape($param);
1.424     matthew  3601:         next if ($v eq 'version' || $symb eq 'keys');
                   3602:         next if (exists($returnhash{$symb}) &&
                   3603:                  exists($returnhash{$symb}->{$param}) &&
                   3604:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   3605:         $returnhash{$symb}->{$param}=$value;
                   3606:         $returnhash{$symb}->{'v.'.$param}=$v;
                   3607:     }
                   3608:     #
                   3609:     # Remove all of the keys in the hashes which keep track of
                   3610:     # the version of the parameter.
                   3611:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   3612:         # use a foreach because we are going to delete from the hash.
                   3613:         foreach my $key (keys(%$param_hash)) {
                   3614:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   3615:         }
                   3616:     }
                   3617:     return \%returnhash;
1.12      www      3618: }
                   3619: 
1.627     albertel 3620: # ------------------------------------------------------ critical inc interface
                   3621: 
                   3622: sub cinc {
                   3623:     return &inc(@_,'critical');
                   3624: }
                   3625: 
1.449     matthew  3626: # --------------------------------------------------------------- inc interface
                   3627: 
                   3628: sub inc {
1.627     albertel 3629:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 3630:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3631:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  3632:     my $uhome=&homeserver($uname,$udomain);
                   3633:     my $items='';
                   3634:     if (! ref($store)) {
                   3635:         # got a single value, so use that instead
                   3636:         $items = &escape($store).'=&';
                   3637:     } elsif (ref($store) eq 'SCALAR') {
                   3638:         $items = &escape($$store).'=&';        
                   3639:     } elsif (ref($store) eq 'ARRAY') {
                   3640:         $items = join('=&',map {&escape($_);} @{$store});
                   3641:     } elsif (ref($store) eq 'HASH') {
                   3642:         while (my($key,$value) = each(%{$store})) {
                   3643:             $items.= &escape($key).'='.&escape($value).'&';
                   3644:         }
                   3645:     }
                   3646:     $items=~s/\&$//;
1.627     albertel 3647:     if ($critical) {
                   3648: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3649:     } else {
                   3650: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3651:     }
1.449     matthew  3652: }
                   3653: 
1.12      www      3654: # --------------------------------------------------------------- put interface
                   3655: 
                   3656: sub put {
1.134     albertel 3657:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3658:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3659:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3660:    my $uhome=&homeserver($uname,$udomain);
1.12      www      3661:    my $items='';
1.800     albertel 3662:    foreach my $item (keys(%$storehash)) {
                   3663:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3664:    }
1.12      www      3665:    $items=~s/\&$//;
1.134     albertel 3666:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      3667: }
                   3668: 
1.631     albertel 3669: # ------------------------------------------------------------ newput interface
                   3670: 
                   3671: sub newput {
                   3672:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   3673:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3674:    if (!$uname) { $uname=$env{'user.name'}; }
                   3675:    my $uhome=&homeserver($uname,$udomain);
                   3676:    my $items='';
                   3677:    foreach my $key (keys(%$storehash)) {
                   3678:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   3679:    }
                   3680:    $items=~s/\&$//;
                   3681:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   3682: }
                   3683: 
                   3684: # ---------------------------------------------------------  putstore interface
                   3685: 
1.524     raeburn  3686: sub putstore {
1.715     albertel 3687:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 3688:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3689:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  3690:    my $uhome=&homeserver($uname,$udomain);
                   3691:    my $items='';
1.715     albertel 3692:    foreach my $key (keys(%$storehash)) {
                   3693:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  3694:    }
1.715     albertel 3695:    $items=~s/\&$//;
1.716     albertel 3696:    my $esc_symb=&escape($symb);
                   3697:    my $esc_v=&escape($version);
1.715     albertel 3698:    my $reply =
1.716     albertel 3699:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 3700: 	      $uhome);
                   3701:    if ($reply eq 'unknown_cmd') {
1.716     albertel 3702:        # gfall back to way things use to be done
1.715     albertel 3703:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   3704: 			    $uname);
1.524     raeburn  3705:    }
1.715     albertel 3706:    return $reply;
                   3707: }
                   3708: 
                   3709: sub old_putstore {
1.716     albertel 3710:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   3711:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3712:     if (!$uname) { $uname=$env{'user.name'}; }
                   3713:     my $uhome=&homeserver($uname,$udomain);
                   3714:     my %newstorehash;
1.800     albertel 3715:     foreach my $item (keys(%$storehash)) {
                   3716: 	my $key = $version.':'.&escape($symb).':'.$item;
                   3717: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 3718:     }
                   3719:     my $items='';
                   3720:     my %allitems = ();
1.800     albertel 3721:     foreach my $item (keys(%newstorehash)) {
                   3722: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 3723: 	    my $key = $1.':keys:'.$2;
                   3724: 	    $allitems{$key} .= $3.':';
                   3725: 	}
1.800     albertel 3726: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 3727:     }
1.800     albertel 3728:     foreach my $item (keys(%allitems)) {
                   3729: 	$allitems{$item} =~ s/\:$//;
                   3730: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 3731:     }
                   3732:     $items=~s/\&$//;
                   3733:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  3734: }
                   3735: 
1.47      www      3736: # ------------------------------------------------------ critical put interface
                   3737: 
                   3738: sub cput {
1.134     albertel 3739:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3740:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3741:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3742:    my $uhome=&homeserver($uname,$udomain);
1.47      www      3743:    my $items='';
1.800     albertel 3744:    foreach my $item (keys(%$storehash)) {
                   3745:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3746:    }
1.47      www      3747:    $items=~s/\&$//;
1.134     albertel 3748:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3749: }
                   3750: 
                   3751: # -------------------------------------------------------------- eget interface
                   3752: 
                   3753: sub eget {
1.133     albertel 3754:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3755:    my $items='';
1.800     albertel 3756:    foreach my $item (@$storearr) {
                   3757:        $items.=&escape($item).'&';
1.191     harris41 3758:    }
1.12      www      3759:    $items=~s/\&$//;
1.620     albertel 3760:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3761:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3762:    my $uhome=&homeserver($uname,$udomain);
                   3763:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3764:    my @pairs=split(/\&/,$rep);
                   3765:    my %returnhash=();
1.42      www      3766:    my $i=0;
1.800     albertel 3767:    foreach my $item (@$storearr) {
                   3768:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3769:       $i++;
1.191     harris41 3770:    }
1.12      www      3771:    return %returnhash;
                   3772: }
                   3773: 
1.667     albertel 3774: # ------------------------------------------------------------ tmpput interface
                   3775: sub tmpput {
1.802     raeburn  3776:     my ($storehash,$server,$context)=@_;
1.667     albertel 3777:     my $items='';
1.800     albertel 3778:     foreach my $item (keys(%$storehash)) {
                   3779: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 3780:     }
                   3781:     $items=~s/\&$//;
1.802     raeburn  3782:     if (defined($context)) {
                   3783:         $items .= ':'.&escape($context);
                   3784:     }
1.667     albertel 3785:     return &reply("tmpput:$items",$server);
                   3786: }
                   3787: 
                   3788: # ------------------------------------------------------------ tmpget interface
                   3789: sub tmpget {
1.688     albertel 3790:     my ($token,$server)=@_;
                   3791:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3792:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 3793:     my %returnhash;
                   3794:     foreach my $item (split(/\&/,$rep)) {
                   3795: 	my ($key,$value)=split(/=/,$item);
                   3796: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   3797:     }
                   3798:     return %returnhash;
                   3799: }
                   3800: 
1.688     albertel 3801: # ------------------------------------------------------------ tmpget interface
                   3802: sub tmpdel {
                   3803:     my ($token,$server)=@_;
                   3804:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3805:     return &reply("tmpdel:$token",$server);
                   3806: }
                   3807: 
1.765     albertel 3808: # -------------------------------------------------- portfolio access checking
                   3809: 
                   3810: sub portfolio_access {
1.766     albertel 3811:     my ($requrl) = @_;
1.765     albertel 3812:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   3813:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  3814:     if ($result) {
                   3815:         my %setters;
                   3816:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3817:             my ($startblock,$endblock) =
                   3818:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   3819:             if ($startblock && $endblock) {
                   3820:                 return 'B';
                   3821:             }
                   3822:         } else {
                   3823:             my ($startblock,$endblock) =
                   3824:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   3825:             if ($startblock && $endblock) {
                   3826:                 return 'B';
                   3827:             }
                   3828:         }
                   3829:     }
1.765     albertel 3830:     if ($result eq 'ok') {
1.766     albertel 3831:        return 'F';
1.765     albertel 3832:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 3833:        return 'A';
1.765     albertel 3834:     }
1.766     albertel 3835:     return '';
1.765     albertel 3836: }
                   3837: 
                   3838: sub get_portfolio_access {
1.767     albertel 3839:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   3840: 
                   3841:     if (!ref($access_hash)) {
                   3842: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   3843: 	my %access_controls = &get_access_controls($current_perms,$group,
                   3844: 						   $file_name);
                   3845: 	$access_hash = $access_controls{$file_name};
                   3846:     }
                   3847: 
1.765     albertel 3848:     my ($public,$guest,@domains,@users,@courses,@groups);
                   3849:     my $now = time;
                   3850:     if (ref($access_hash) eq 'HASH') {
                   3851:         foreach my $key (keys(%{$access_hash})) {
                   3852:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   3853:             if ($start > $now) {
                   3854:                 next;
                   3855:             }
                   3856:             if ($end && $end<$now) {
                   3857:                 next;
                   3858:             }
                   3859:             if ($scope eq 'public') {
                   3860:                 $public = $key;
                   3861:                 last;
                   3862:             } elsif ($scope eq 'guest') {
                   3863:                 $guest = $key;
                   3864:             } elsif ($scope eq 'domains') {
                   3865:                 push(@domains,$key);
                   3866:             } elsif ($scope eq 'users') {
                   3867:                 push(@users,$key);
                   3868:             } elsif ($scope eq 'course') {
                   3869:                 push(@courses,$key);
                   3870:             } elsif ($scope eq 'group') {
                   3871:                 push(@groups,$key);
                   3872:             }
                   3873:         }
                   3874:         if ($public) {
                   3875:             return 'ok';
                   3876:         }
                   3877:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3878:             if ($guest) {
                   3879:                 return $guest;
                   3880:             }
                   3881:         } else {
                   3882:             if (@domains > 0) {
                   3883:                 foreach my $domkey (@domains) {
                   3884:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   3885:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   3886:                             return 'ok';
                   3887:                         }
                   3888:                     }
                   3889:                 }
                   3890:             }
                   3891:             if (@users > 0) {
                   3892:                 foreach my $userkey (@users) {
1.865     raeburn  3893:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   3894:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   3895:                             if (ref($item) eq 'HASH') {
                   3896:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   3897:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   3898:                                     return 'ok';
                   3899:                                 }
                   3900:                             }
                   3901:                         }
                   3902:                     } 
1.765     albertel 3903:                 }
                   3904:             }
                   3905:             my %roleshash;
                   3906:             my @courses_and_groups = @courses;
                   3907:             push(@courses_and_groups,@groups); 
                   3908:             if (@courses_and_groups > 0) {
                   3909:                 my (%allgroups,%allroles); 
                   3910:                 my ($start,$end,$role,$sec,$group);
                   3911:                 foreach my $envkey (%env) {
1.811     albertel 3912:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 3913:                         my $cid = $2.'_'.$3; 
                   3914:                         if ($1 eq 'gr') {
                   3915:                             $group = $4;
                   3916:                             $allgroups{$cid}{$group} = $env{$envkey};
                   3917:                         } else {
                   3918:                             if ($4 eq '') {
                   3919:                                 $sec = 'none';
                   3920:                             } else {
                   3921:                                 $sec = $4;
                   3922:                             }
                   3923:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3924:                         }
1.811     albertel 3925:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 3926:                         my $cid = $2.'_'.$3;
                   3927:                         if ($4 eq '') {
                   3928:                             $sec = 'none';
                   3929:                         } else {
                   3930:                             $sec = $4;
                   3931:                         }
                   3932:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3933:                     }
                   3934:                 }
                   3935:                 if (keys(%allroles) == 0) {
                   3936:                     return;
                   3937:                 }
                   3938:                 foreach my $key (@courses_and_groups) {
                   3939:                     my %content = %{$$access_hash{$key}};
                   3940:                     my $cnum = $content{'number'};
                   3941:                     my $cdom = $content{'domain'};
                   3942:                     my $cid = $cdom.'_'.$cnum;
                   3943:                     if (!exists($allroles{$cid})) {
                   3944:                         next;
                   3945:                     }    
                   3946:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   3947:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   3948:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   3949:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   3950:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   3951:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   3952:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   3953:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   3954:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   3955:                                         if (grep/^all$/,@sections) {
                   3956:                                             return 'ok';
                   3957:                                         } else {
                   3958:                                             if (grep/^$sec$/,@sections) {
                   3959:                                                 return 'ok';
                   3960:                                             }
                   3961:                                         }
                   3962:                                     }
                   3963:                                 }
                   3964:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   3965:                                     if (grep/^none$/,@groups) {
                   3966:                                         return 'ok';
                   3967:                                     }
                   3968:                                 } else {
                   3969:                                     if (grep/^all$/,@groups) {
                   3970:                                         return 'ok';
                   3971:                                     } 
                   3972:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   3973:                                         if (grep/^$group$/,@groups) {
                   3974:                                             return 'ok';
                   3975:                                         }
                   3976:                                     }
                   3977:                                 } 
                   3978:                             }
                   3979:                         }
                   3980:                     }
                   3981:                 }
                   3982:             }
                   3983:             if ($guest) {
                   3984:                 return $guest;
                   3985:             }
                   3986:         }
                   3987:     }
                   3988:     return;
                   3989: }
                   3990: 
                   3991: sub course_group_datechecker {
                   3992:     my ($dates,$now,$status) = @_;
                   3993:     my ($start,$end) = split(/\./,$dates);
                   3994:     if (!$start && !$end) {
                   3995:         return 'ok';
                   3996:     }
                   3997:     if (grep/^active$/,@{$status}) {
                   3998:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   3999:             return 'ok';
                   4000:         }
                   4001:     }
                   4002:     if (grep/^previous$/,@{$status}) {
                   4003:         if ($end > $now ) {
                   4004:             return 'ok';
                   4005:         }
                   4006:     }
                   4007:     if (grep/^future$/,@{$status}) {
                   4008:         if ($start > $now) {
                   4009:             return 'ok';
                   4010:         }
                   4011:     }
                   4012:     return; 
                   4013: }
                   4014: 
                   4015: sub parse_portfolio_url {
                   4016:     my ($url) = @_;
                   4017: 
                   4018:     my ($type,$udom,$unum,$group,$file_name);
                   4019:     
1.823     albertel 4020:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 4021: 	$type = 1;
                   4022:         $udom = $1;
                   4023:         $unum = $2;
                   4024:         $file_name = $3;
1.823     albertel 4025:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 4026: 	$type = 2;
                   4027:         $udom = $1;
                   4028:         $unum = $2;
                   4029:         $group = $3;
                   4030:         $file_name = $3.'/'.$4;
                   4031:     }
                   4032:     if (wantarray) {
                   4033: 	return ($type,$udom,$unum,$file_name,$group);
                   4034:     }
                   4035:     return $type;
                   4036: }
                   4037: 
                   4038: sub is_portfolio_url {
                   4039:     my ($url) = @_;
                   4040:     return scalar(&parse_portfolio_url($url));
                   4041: }
                   4042: 
1.798     raeburn  4043: sub is_portfolio_file {
                   4044:     my ($file) = @_;
1.820     raeburn  4045:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  4046:         return 1;
                   4047:     }
                   4048:     return;
                   4049: }
                   4050: 
                   4051: 
1.341     www      4052: # ---------------------------------------------- Custom access rule evaluation
                   4053: 
                   4054: sub customaccess {
                   4055:     my ($priv,$uri)=@_;
1.807     albertel 4056:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      4057:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 4058:     $udom = &LONCAPA::clean_domain($udom);
                   4059:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      4060:     my $access=0;
1.800     albertel 4061:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 4062: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   4063: 	if ($type eq 'user') {
                   4064: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 4065: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 4066: 		if ($tdom) {
                   4067: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   4068: 		}
1.896     albertel 4069: 		if ($tuname) {
                   4070: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 4071: 		}
                   4072: 		$access=($effect eq 'allow');
                   4073: 		last;
                   4074: 	    }
                   4075: 	} else {
                   4076: 	    if ($role) {
                   4077: 		if ($role ne $urole) { next; }
                   4078: 	    }
                   4079: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   4080: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   4081: 		if ($tdom) {
                   4082: 		    if ($tdom ne $udom) { next; }
                   4083: 		}
                   4084: 		if ($tcrs) {
                   4085: 		    if ($tcrs ne $ucrs) { next; }
                   4086: 		}
                   4087: 		if ($tsec) {
                   4088: 		    if ($tsec ne $usec) { next; }
                   4089: 		}
                   4090: 		$access=($effect eq 'allow');
                   4091: 		last;
                   4092: 	    }
                   4093: 	    if ($realm eq '' && $role eq '') {
                   4094: 		$access=($effect eq 'allow');
                   4095: 	    }
1.402     bowersj2 4096: 	}
1.341     www      4097:     }
                   4098:     return $access;
                   4099: }
                   4100: 
1.103     harris41 4101: # ------------------------------------------------- Check for a user privilege
1.12      www      4102: 
                   4103: sub allowed {
1.810     raeburn  4104:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 4105:     my $ver_orguri=$uri;
1.439     www      4106:     $uri=&deversion($uri);
1.152     www      4107:     my $orguri=$uri;
1.52      www      4108:     $uri=&declutter($uri);
1.809     raeburn  4109: 
1.810     raeburn  4110:     if ($priv eq 'evb') {
                   4111: # Evade communication block restrictions for specified role in a course
                   4112:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   4113:             return $1;
                   4114:         } else {
                   4115:             return;
                   4116:         }
                   4117:     }
                   4118: 
1.620     albertel 4119:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      4120: # Free bre access to adm and meta resources
1.775     albertel 4121:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 4122: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   4123: 	&& ($priv eq 'bre')) {
1.14      www      4124: 	return 'F';
1.159     www      4125:     }
                   4126: 
1.545     banghart 4127: # Free bre access to user's own portfolio contents
1.714     raeburn  4128:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  4129:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  4130: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  4131:         my %setters;
                   4132:         my ($startblock,$endblock) = 
                   4133:             &Apache::loncommon::blockcheck(\%setters,'port');
                   4134:         if ($startblock && $endblock) {
                   4135:             return 'B';
                   4136:         } else {
                   4137:             return 'F';
                   4138:         }
1.545     banghart 4139:     }
                   4140: 
1.762     raeburn  4141: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  4142:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   4143:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   4144:         if (exists($env{'request.course.id'})) {
                   4145:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4146:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4147:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   4148:                 my $courseprivid=$env{'request.course.id'};
                   4149:                 $courseprivid=~s/\_/\//;
                   4150:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   4151:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   4152:                     return $1; 
1.762     raeburn  4153:                 } else {
                   4154:                     if ($env{'request.course.sec'}) {
                   4155:                         $courseprivid.='/'.$env{'request.course.sec'};
                   4156:                     }
                   4157:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   4158:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   4159:                         return $2;
                   4160:                     }
1.714     raeburn  4161:                 }
                   4162:             }
                   4163:         }
                   4164:     }
                   4165: 
1.159     www      4166: # Free bre to public access
                   4167: 
                   4168:     if ($priv eq 'bre') {
1.238     www      4169:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 4170: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      4171:            return 'F'; 
                   4172:         }
1.238     www      4173:         if ($copyright eq 'priv') {
                   4174:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4175: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      4176: 		return '';
                   4177:             }
                   4178:         }
                   4179:         if ($copyright eq 'domain') {
                   4180:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4181: 	    unless (($env{'user.domain'} eq $1) ||
                   4182:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      4183: 		return '';
                   4184:             }
1.262     matthew  4185:         }
1.620     albertel 4186:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  4187:             # Library role, so allow browsing of resources in this domain.
                   4188:             return 'F';
1.238     www      4189:         }
1.341     www      4190:         if ($copyright eq 'custom') {
                   4191: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   4192:         }
1.14      www      4193:     }
1.264     matthew  4194:     # Domain coordinator is trying to create a course
1.620     albertel 4195:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  4196:         # uri is the requested domain in this case.
                   4197:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  4198:         # a role of dc for the domain in question.
1.620     albertel 4199:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  4200:     }
1.29      www      4201: 
1.52      www      4202:     my $thisallowed='';
                   4203:     my $statecond=0;
                   4204:     my $courseprivid='';
                   4205: 
                   4206: # Course
                   4207: 
1.620     albertel 4208:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4209:        $thisallowed.=$1;
                   4210:     }
1.29      www      4211: 
1.52      www      4212: # Domain
                   4213: 
1.620     albertel 4214:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 4215:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4216:        $thisallowed.=$1;
                   4217:     }
1.52      www      4218: 
                   4219: # Course: uri itself is a course
1.66      www      4220:     my $courseuri=$uri;
                   4221:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      4222:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      4223: 
1.620     albertel 4224:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 4225:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4226:        $thisallowed.=$1;
                   4227:     }
1.29      www      4228: 
1.665     albertel 4229: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 4230: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 4231:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 4232: 	$thisallowed='';
1.671     raeburn  4233:         my ($match)=&is_on_map($uri);
                   4234:         if ($match) {
                   4235:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   4236:                   =~/\Q$priv\E\&([^\:]*)/) {
                   4237:                 $thisallowed.=$1;
                   4238:             }
                   4239:         } else {
1.705     albertel 4240:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  4241:             if ($refuri) {
                   4242:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  4243:                     $thisallowed='F';
1.671     raeburn  4244:                 } else {
                   4245:                     $refuri=&declutter($refuri);
                   4246:                     my ($match) = &is_on_map($refuri);
                   4247:                     if ($match) {
                   4248:                         $thisallowed='F';
                   4249:                     }
1.669     raeburn  4250:                 }
1.671     raeburn  4251:             }
                   4252:         }
1.314     www      4253:     }
1.492     albertel 4254: 
1.766     albertel 4255:     if ($priv eq 'bre'
                   4256: 	&& $thisallowed ne 'F' 
                   4257: 	&& $thisallowed ne '2'
                   4258: 	&& &is_portfolio_url($uri)) {
                   4259: 	$thisallowed = &portfolio_access($uri);
                   4260:     }
                   4261:     
1.52      www      4262: # Full access at system, domain or course-wide level? Exit.
1.29      www      4263: 
                   4264:     if ($thisallowed=~/F/) {
                   4265: 	return 'F';
                   4266:     }
                   4267: 
1.52      www      4268: # If this is generating or modifying users, exit with special codes
1.29      www      4269: 
1.643     www      4270:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   4271: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 4272: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      4273: # no author name given, so this just checks on the general right to make a co-author in this domain
                   4274: 	    unless ($auname) { return $thisallowed; }
                   4275: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 4276: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   4277: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   4278: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   4279: 	}
1.52      www      4280: 	return $thisallowed;
                   4281:     }
                   4282: #
1.103     harris41 4283: # Gathered so far: system, domain and course wide privileges
1.52      www      4284: #
                   4285: # Course: See if uri or referer is an individual resource that is part of 
                   4286: # the course
                   4287: 
1.620     albertel 4288:     if ($env{'request.course.id'}) {
1.232     www      4289: 
1.620     albertel 4290:        $courseprivid=$env{'request.course.id'};
                   4291:        if ($env{'request.course.sec'}) {
                   4292:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      4293:        }
                   4294:        $courseprivid=~s/\_/\//;
                   4295:        my $checkreferer=1;
1.232     www      4296:        my ($match,$cond)=&is_on_map($uri);
                   4297:        if ($match) {
                   4298:            $statecond=$cond;
1.620     albertel 4299:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4300:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4301:                $thisallowed.=$1;
                   4302:                $checkreferer=0;
                   4303:            }
1.29      www      4304:        }
1.83      www      4305:        
1.148     www      4306:        if ($checkreferer) {
1.620     albertel 4307: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      4308:             unless ($refuri) {
1.800     albertel 4309:                 foreach my $key (keys(%env)) {
                   4310: 		    if ($key=~/^httpref\..*\*/) {
                   4311: 			my $pattern=$key;
1.156     www      4312:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      4313:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   4314:                         $pattern=~s/\//\\\//g;
1.152     www      4315:                         if ($orguri=~/$pattern/) {
1.800     albertel 4316: 			    $refuri=$env{$key};
1.148     www      4317:                         }
                   4318:                     }
1.191     harris41 4319:                 }
1.148     www      4320:             }
1.232     www      4321: 
1.148     www      4322:          if ($refuri) { 
1.152     www      4323: 	  $refuri=&declutter($refuri);
1.232     www      4324:           my ($match,$cond)=&is_on_map($refuri);
                   4325:             if ($match) {
                   4326:               my $refstatecond=$cond;
1.620     albertel 4327:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4328:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4329:                   $thisallowed.=$1;
1.53      www      4330:                   $uri=$refuri;
                   4331:                   $statecond=$refstatecond;
1.52      www      4332:               }
                   4333:           }
1.148     www      4334:         }
1.29      www      4335:        }
1.52      www      4336:    }
1.29      www      4337: 
1.52      www      4338: #
1.103     harris41 4339: # Gathered now: all privileges that could apply, and condition number
1.52      www      4340: # 
                   4341: #
                   4342: # Full or no access?
                   4343: #
1.29      www      4344: 
1.52      www      4345:     if ($thisallowed=~/F/) {
                   4346: 	return 'F';
                   4347:     }
1.29      www      4348: 
1.52      www      4349:     unless ($thisallowed) {
                   4350:         return '';
                   4351:     }
1.29      www      4352: 
1.52      www      4353: # Restrictions exist, deal with them
                   4354: #
                   4355: #   C:according to course preferences
                   4356: #   R:according to resource settings
                   4357: #   L:unless locked
                   4358: #   X:according to user session state
                   4359: #
                   4360: 
                   4361: # Possibly locked functionality, check all courses
1.54      www      4362: # Locks might take effect only after 10 minutes cache expiration for other
                   4363: # courses, and 2 minutes for current course
1.52      www      4364: 
                   4365:     my $envkey;
                   4366:     if ($thisallowed=~/L/) {
1.620     albertel 4367:         foreach $envkey (keys %env) {
1.54      www      4368:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   4369:                my $courseid=$2;
                   4370:                my $roleid=$1.'.'.$2;
1.92      www      4371:                $courseid=~s/^\///;
1.54      www      4372:                my $expiretime=600;
1.620     albertel 4373:                if ($env{'request.role'} eq $roleid) {
1.54      www      4374: 		  $expiretime=120;
                   4375:                }
                   4376: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   4377:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 4378:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 4379: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      4380:                }
1.620     albertel 4381:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4382:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   4383: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   4384:                        &log($env{'user.domain'},$env{'user.name'},
                   4385:                             $env{'user.home'},
1.57      www      4386:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      4387:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4388:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4389: 		       return '';
                   4390:                    }
                   4391:                }
1.620     albertel 4392:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4393:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   4394: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   4395:                        &log($env{'user.domain'},$env{'user.name'},
                   4396:                             $env{'user.home'},
1.57      www      4397:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      4398:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4399:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4400: 		       return '';
                   4401:                    }
                   4402:                }
                   4403: 	   }
1.29      www      4404:        }
1.52      www      4405:     }
                   4406:    
                   4407: #
                   4408: # Rest of the restrictions depend on selected course
                   4409: #
                   4410: 
1.620     albertel 4411:     unless ($env{'request.course.id'}) {
1.766     albertel 4412: 	if ($thisallowed eq 'A') {
                   4413: 	    return 'A';
1.814     raeburn  4414:         } elsif ($thisallowed eq 'B') {
                   4415:             return 'B';
1.766     albertel 4416: 	} else {
                   4417: 	    return '1';
                   4418: 	}
1.52      www      4419:     }
1.29      www      4420: 
1.52      www      4421: #
                   4422: # Now user is definitely in a course
                   4423: #
1.53      www      4424: 
                   4425: 
                   4426: # Course preferences
                   4427: 
                   4428:    if ($thisallowed=~/C/) {
1.620     albertel 4429:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   4430:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   4431:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 4432: 	   =~/\Q$rolecode\E/) {
1.689     albertel 4433: 	   if ($priv ne 'pch') { 
                   4434: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4435: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   4436: 			$env{'request.course.id'});
                   4437: 	   }
1.237     www      4438:            return '';
                   4439:        }
                   4440: 
1.620     albertel 4441:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 4442: 	   =~/\Q$unamedom\E/) {
1.689     albertel 4443: 	   if ($priv ne 'pch') { 
                   4444: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   4445: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   4446: 			$env{'request.course.id'});
                   4447: 	   }
1.54      www      4448:            return '';
                   4449:        }
1.53      www      4450:    }
                   4451: 
                   4452: # Resource preferences
                   4453: 
                   4454:    if ($thisallowed=~/R/) {
1.620     albertel 4455:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 4456:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 4457: 	   if ($priv ne 'pch') { 
                   4458: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4459: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   4460: 	   }
                   4461: 	   return '';
1.54      www      4462:        }
1.53      www      4463:    }
1.30      www      4464: 
1.246     www      4465: # Restricted by state or randomout?
1.30      www      4466: 
1.52      www      4467:    if ($thisallowed=~/X/) {
1.620     albertel 4468:       if ($env{'acc.randomout'}) {
1.579     albertel 4469: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 4470:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      4471:             return ''; 
                   4472:          }
1.247     www      4473:       }
                   4474:       if (&condval($statecond)) {
1.52      www      4475: 	 return '2';
                   4476:       } else {
                   4477:          return '';
                   4478:       }
                   4479:    }
1.30      www      4480: 
1.766     albertel 4481:     if ($thisallowed eq 'A') {
                   4482: 	return 'A';
1.814     raeburn  4483:     } elsif ($thisallowed eq 'B') {
                   4484:         return 'B';
1.766     albertel 4485:     }
1.52      www      4486:    return 'F';
1.232     www      4487: }
                   4488: 
1.710     albertel 4489: sub split_uri_for_cond {
                   4490:     my $uri=&deversion(&declutter(shift));
                   4491:     my @uriparts=split(/\//,$uri);
                   4492:     my $filename=pop(@uriparts);
                   4493:     my $pathname=join('/',@uriparts);
                   4494:     return ($pathname,$filename);
                   4495: }
1.232     www      4496: # --------------------------------------------------- Is a resource on the map?
                   4497: 
                   4498: sub is_on_map {
1.710     albertel 4499:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 4500:     #Trying to find the conditional for the file
1.620     albertel 4501:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 4502: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      4503:     if ($match) {
1.289     bowersj2 4504: 	return (1,$1);
                   4505:     } else {
1.434     www      4506: 	return (0,0);
1.289     bowersj2 4507:     }
1.12      www      4508: }
                   4509: 
1.427     www      4510: # --------------------------------------------------------- Get symb from alias
                   4511: 
                   4512: sub get_symb_from_alias {
                   4513:     my $symb=shift;
                   4514:     my ($map,$resid,$url)=&decode_symb($symb);
                   4515: # Already is a symb
                   4516:     if ($url) { return $symb; }
                   4517: # Must be an alias
                   4518:     my $aliassymb='';
                   4519:     my %bighash;
1.620     albertel 4520:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      4521:                             &GDBM_READER(),0640)) {
                   4522:         my $rid=$bighash{'mapalias_'.$symb};
                   4523: 	if ($rid) {
                   4524: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 4525: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   4526: 				    $resid,$bighash{'src_'.$rid});
1.427     www      4527: 	}
                   4528:         untie %bighash;
                   4529:     }
                   4530:     return $aliassymb;
                   4531: }
                   4532: 
1.12      www      4533: # ----------------------------------------------------------------- Define Role
                   4534: 
                   4535: sub definerole {
                   4536:   if (allowed('mcr','/')) {
                   4537:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 4538:     foreach my $role (split(':',$sysrole)) {
                   4539: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4540:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   4541:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   4542: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4543:                return "refused:s:$crole&$cqual"; 
                   4544:             }
                   4545:         }
1.191     harris41 4546:     }
1.800     albertel 4547:     foreach my $role (split(':',$domrole)) {
                   4548: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4549:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   4550:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   4551: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      4552:                return "refused:d:$crole&$cqual"; 
                   4553:             }
                   4554:         }
1.191     harris41 4555:     }
1.800     albertel 4556:     foreach my $role (split(':',$courole)) {
                   4557: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4558:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   4559:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   4560: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4561:                return "refused:c:$crole&$cqual"; 
                   4562:             }
                   4563:         }
1.191     harris41 4564:     }
1.620     albertel 4565:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   4566:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4567: 	        "rolesdef_$rolename=".
                   4568:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 4569:     return reply($command,$env{'user.home'});
1.12      www      4570:   } else {
                   4571:     return 'refused';
                   4572:   }
1.105     harris41 4573: }
                   4574: 
                   4575: # ---------------- Make a metadata query against the network of library servers
                   4576: 
                   4577: sub metadata_query {
1.244     matthew  4578:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 4579:     my %rhash;
1.845     albertel 4580:     my %libserv = &all_library();
1.244     matthew  4581:     my @server_list = (defined($server_array) ? @$server_array
                   4582:                                               : keys(%libserv) );
                   4583:     for my $server (@server_list) {
1.118     harris41 4584: 	unless ($custom or $customshow) {
                   4585: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   4586: 	    $rhash{$server}=$reply;
                   4587: 	}
                   4588: 	else {
                   4589: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   4590: 			     &escape($custom).':'.&escape($customshow),
                   4591: 			     $server);
                   4592: 	    $rhash{$server}=$reply;
                   4593: 	}
1.112     harris41 4594:     }
1.118     harris41 4595:     return \%rhash;
1.240     www      4596: }
                   4597: 
                   4598: # ----------------------------------------- Send log queries and wait for reply
                   4599: 
                   4600: sub log_query {
                   4601:     my ($uname,$udom,$query,%filters)=@_;
                   4602:     my $uhome=&homeserver($uname,$udom);
                   4603:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 4604:     my $uhost=&hostname($uhome);
1.800     albertel 4605:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      4606:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   4607:                        $uhome);
1.479     albertel 4608:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      4609:     return get_query_reply($queryid);
                   4610: }
                   4611: 
1.818     raeburn  4612: # -------------------------- Update MySQL table for portfolio file
                   4613: 
                   4614: sub update_portfolio_table {
1.821     raeburn  4615:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.818     raeburn  4616:     my $homeserver = &homeserver($uname,$udom);
                   4617:     my $queryid=
1.821     raeburn  4618:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   4619:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  4620:     my $reply = &get_query_reply($queryid);
                   4621:     return $reply;
                   4622: }
                   4623: 
1.899     raeburn  4624: # -------------------------- Update MySQL allusers table
                   4625: 
                   4626: sub update_allusers_table {
                   4627:     my ($uname,$udom,$names) = @_;
                   4628:     my $homeserver = &homeserver($uname,$udom);
                   4629:     my $queryid=
                   4630:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   4631:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   4632:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   4633:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   4634:                'generation='.&escape($names->{'generation'}).'%%'.
                   4635:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   4636:                'id='.&escape($names->{'id'}),$homeserver);
                   4637:     my $reply = &get_query_reply($queryid);
                   4638:     return $reply;
                   4639: }
                   4640: 
1.508     raeburn  4641: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  4642: 
                   4643: sub fetch_enrollment_query {
1.511     raeburn  4644:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  4645:     my $homeserver;
1.547     raeburn  4646:     my $maxtries = 1;
1.508     raeburn  4647:     if ($context eq 'automated') {
                   4648:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  4649:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  4650:     } else {
                   4651:         $homeserver = &homeserver($cnum,$dom);
                   4652:     }
1.838     albertel 4653:     my $host=&hostname($homeserver);
1.506     raeburn  4654:     my $cmd = '';
1.800     albertel 4655:     foreach my $affiliate (keys %{$affiliatesref}) {
                   4656:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  4657:     }
                   4658:     $cmd =~ s/%%$//;
                   4659:     $cmd = &escape($cmd);
                   4660:     my $query = 'fetchenrollment';
1.620     albertel 4661:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  4662:     unless ($queryid=~/^\Q$host\E\_/) { 
                   4663:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   4664:         return 'error: '.$queryid;
                   4665:     }
1.506     raeburn  4666:     my $reply = &get_query_reply($queryid);
1.547     raeburn  4667:     my $tries = 1;
                   4668:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4669:         $reply = &get_query_reply($queryid);
                   4670:         $tries ++;
                   4671:     }
1.526     raeburn  4672:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 4673:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  4674:     } else {
1.901     albertel 4675:         my @responses = split(/:/,$reply);
1.515     raeburn  4676:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 4677:             foreach my $line (@responses) {
                   4678:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  4679:                 $$replyref{$key} = $value;
                   4680:             }
                   4681:         } else {
1.506     raeburn  4682:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 4683:             foreach my $line (@responses) {
                   4684:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  4685:                 $$replyref{$key} = $value;
                   4686:                 if ($value > 0) {
1.800     albertel 4687:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   4688:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  4689:                         my $destname = $pathname.'/'.$filename;
                   4690:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  4691:                         if ($xml_classlist =~ /^error/) {
                   4692:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   4693:                         } else {
1.506     raeburn  4694:                             if ( open(FILE,">$destname") ) {
                   4695:                                 print FILE &unescape($xml_classlist);
                   4696:                                 close(FILE);
1.526     raeburn  4697:                             } else {
                   4698:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  4699:                             }
                   4700:                         }
                   4701:                     }
                   4702:                 }
                   4703:             }
                   4704:         }
                   4705:         return 'ok';
                   4706:     }
                   4707:     return 'error';
                   4708: }
                   4709: 
1.242     www      4710: sub get_query_reply {
                   4711:     my $queryid=shift;
1.240     www      4712:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   4713:     my $reply='';
                   4714:     for (1..100) {
                   4715: 	sleep 2;
                   4716:         if (-e $replyfile.'.end') {
1.448     albertel 4717: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 4718: 		$reply = join('',<$fh>);
                   4719: 		close($fh);
1.240     www      4720: 	   } else { return 'error: reply_file_error'; }
1.242     www      4721:            return &unescape($reply);
                   4722: 	}
1.240     www      4723:     }
1.242     www      4724:     return 'timeout:'.$queryid;
1.240     www      4725: }
                   4726: 
                   4727: sub courselog_query {
1.241     www      4728: #
                   4729: # possible filters:
                   4730: # url: url or symb
                   4731: # username
                   4732: # domain
                   4733: # action: view, submit, grade
                   4734: # start: timestamp
                   4735: # end: timestamp
                   4736: #
1.240     www      4737:     my (%filters)=@_;
1.620     albertel 4738:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      4739:     if ($filters{'url'}) {
                   4740: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   4741:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   4742:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   4743:     }
1.620     albertel 4744:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4745:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      4746:     return &log_query($cname,$cdom,'courselog',%filters);
                   4747: }
                   4748: 
                   4749: sub userlog_query {
1.858     raeburn  4750: #
                   4751: # possible filters:
                   4752: # action: log check role
                   4753: # start: timestamp
                   4754: # end: timestamp
                   4755: #
1.240     www      4756:     my ($uname,$udom,%filters)=@_;
                   4757:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      4758: }
                   4759: 
1.506     raeburn  4760: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   4761: 
                   4762: sub auto_run {
1.508     raeburn  4763:     my ($cnum,$cdom) = @_;
1.876     raeburn  4764:     my $response = 0;
                   4765:     my $settings;
                   4766:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   4767:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   4768:         $settings = $domconfig{'autoenroll'};
                   4769:         if ($settings->{'run'} eq '1') {
                   4770:             $response = 1;
                   4771:         }
                   4772:     } else {
                   4773:         my $homeserver = &homeserver($cnum,$cdom);
                   4774:         $response = &reply('autorun:'.$cdom,$homeserver);
                   4775:     }
1.506     raeburn  4776:     return $response;
                   4777: }
1.776     albertel 4778: 
1.506     raeburn  4779: sub auto_get_sections {
1.508     raeburn  4780:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   4781:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  4782:     my @secs = ();
1.511     raeburn  4783:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  4784:     unless ($response eq 'refused') {
1.901     albertel 4785:         @secs = split(/:/,$response);
1.506     raeburn  4786:     }
                   4787:     return @secs;
                   4788: }
1.776     albertel 4789: 
1.506     raeburn  4790: sub auto_new_course {
1.508     raeburn  4791:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   4792:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  4793:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  4794:     return $response;
                   4795: }
1.776     albertel 4796: 
1.506     raeburn  4797: sub auto_validate_courseID {
1.508     raeburn  4798:     my ($cnum,$cdom,$inst_course_id) = @_;
                   4799:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4800:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  4801:     return $response;
                   4802: }
1.776     albertel 4803: 
1.506     raeburn  4804: sub auto_create_password {
1.873     raeburn  4805:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   4806:     my ($homeserver,$response);
1.506     raeburn  4807:     my $create_passwd = 0;
                   4808:     my $authchk = '';
1.873     raeburn  4809:     if ($udom =~ /^$match_domain$/) {
                   4810:         $homeserver = &domain($udom,'primary');
                   4811:     }
                   4812:     if ($homeserver eq '') {
                   4813:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   4814:             $homeserver = &homeserver($cnum,$cdom);
                   4815:         }
                   4816:     }
                   4817:     if ($homeserver eq '') {
                   4818:         $authchk = 'nodomain';
1.506     raeburn  4819:     } else {
1.873     raeburn  4820:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   4821:         if ($response eq 'refused') {
                   4822:             $authchk = 'refused';
                   4823:         } else {
1.901     albertel 4824:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  4825:         }
1.506     raeburn  4826:     }
                   4827:     return ($authparam,$create_passwd,$authchk);
                   4828: }
                   4829: 
1.706     raeburn  4830: sub auto_photo_permission {
                   4831:     my ($cnum,$cdom,$students) = @_;
                   4832:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 4833:     my ($outcome,$perm_reqd,$conditions) = 
                   4834: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 4835:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4836: 	return (undef,undef);
                   4837:     }
1.706     raeburn  4838:     return ($outcome,$perm_reqd,$conditions);
                   4839: }
                   4840: 
                   4841: sub auto_checkphotos {
                   4842:     my ($uname,$udom,$pid) = @_;
                   4843:     my $homeserver = &homeserver($uname,$udom);
                   4844:     my ($result,$resulttype);
                   4845:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 4846: 				   &escape($uname).':'.&escape($pid),
                   4847: 				   $homeserver));
1.709     albertel 4848:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4849: 	return (undef,undef);
                   4850:     }
1.706     raeburn  4851:     if ($outcome) {
                   4852:         ($result,$resulttype) = split(/:/,$outcome);
                   4853:     } 
                   4854:     return ($result,$resulttype);
                   4855: }
                   4856: 
                   4857: sub auto_photochoice {
                   4858:     my ($cnum,$cdom) = @_;
                   4859:     my $homeserver = &homeserver($cnum,$cdom);
                   4860:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 4861: 						       &escape($cdom),
                   4862: 						       $homeserver)));
1.709     albertel 4863:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4864: 	return (undef,undef);
                   4865:     }
1.706     raeburn  4866:     return ($update,$comment);
                   4867: }
                   4868: 
                   4869: sub auto_photoupdate {
                   4870:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   4871:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 4872:     my $host=&hostname($homeserver);
1.706     raeburn  4873:     my $cmd = '';
                   4874:     my $maxtries = 1;
1.800     albertel 4875:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   4876:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  4877:     }
                   4878:     $cmd =~ s/%%$//;
                   4879:     $cmd = &escape($cmd);
                   4880:     my $query = 'institutionalphotos';
                   4881:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   4882:     unless ($queryid=~/^\Q$host\E\_/) {
                   4883:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   4884:         return 'error: '.$queryid;
                   4885:     }
                   4886:     my $reply = &get_query_reply($queryid);
                   4887:     my $tries = 1;
                   4888:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4889:         $reply = &get_query_reply($queryid);
                   4890:         $tries ++;
                   4891:     }
                   4892:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   4893:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   4894:     } else {
                   4895:         my @responses = split(/:/,$reply);
                   4896:         my $outcome = shift(@responses); 
                   4897:         foreach my $item (@responses) {
                   4898:             my ($key,$value) = split(/=/,$item);
                   4899:             $$photo{$key} = $value;
                   4900:         }
                   4901:         return $outcome;
                   4902:     }
                   4903:     return 'error';
                   4904: }
                   4905: 
1.521     raeburn  4906: sub auto_instcode_format {
1.793     albertel 4907:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   4908: 	$cat_order) = @_;
1.521     raeburn  4909:     my $courses = '';
1.772     raeburn  4910:     my @homeservers;
1.521     raeburn  4911:     if ($caller eq 'global') {
1.841     albertel 4912: 	my %servers = &get_servers($codedom,'library');
                   4913: 	foreach my $tryserver (keys(%servers)) {
                   4914: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   4915: 		push(@homeservers,$tryserver);
                   4916: 	    }
1.584     raeburn  4917:         }
1.521     raeburn  4918:     } else {
1.772     raeburn  4919:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  4920:     }
1.793     albertel 4921:     foreach my $code (keys(%{$instcodes})) {
                   4922:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  4923:     }
                   4924:     chop($courses);
1.772     raeburn  4925:     my $ok_response = 0;
                   4926:     my $response;
                   4927:     while (@homeservers > 0 && $ok_response == 0) {
                   4928:         my $server = shift(@homeservers); 
                   4929:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   4930:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   4931:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 4932: 		split(/:/,$response);
1.772     raeburn  4933:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   4934:             push(@{$codetitles},&str2array($codetitles_str));
                   4935:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   4936:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   4937:             $ok_response = 1;
                   4938:         }
                   4939:     }
                   4940:     if ($ok_response) {
1.521     raeburn  4941:         return 'ok';
1.772     raeburn  4942:     } else {
                   4943:         return $response;
1.521     raeburn  4944:     }
                   4945: }
                   4946: 
1.792     raeburn  4947: sub auto_instcode_defaults {
                   4948:     my ($domain,$returnhash,$code_order) = @_;
                   4949:     my @homeservers;
1.841     albertel 4950: 
                   4951:     my %servers = &get_servers($domain,'library');
                   4952:     foreach my $tryserver (keys(%servers)) {
                   4953: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   4954: 	    push(@homeservers,$tryserver);
                   4955: 	}
1.792     raeburn  4956:     }
1.841     albertel 4957: 
1.792     raeburn  4958:     my $response;
1.841     albertel 4959:     foreach my $server (@homeservers) {
1.792     raeburn  4960:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 4961:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   4962: 	
                   4963: 	foreach my $pair (split(/\&/,$response)) {
                   4964: 	    my ($name,$value)=split(/\=/,$pair);
                   4965: 	    if ($name eq 'code_order') {
                   4966: 		@{$code_order} = split(/\&/,&unescape($value));
                   4967: 	    } else {
                   4968: 		$returnhash->{&unescape($name)}=&unescape($value);
                   4969: 	    }
                   4970: 	}
                   4971: 	return 'ok';
1.792     raeburn  4972:     }
1.841     albertel 4973: 
                   4974:     return $response;
1.792     raeburn  4975: } 
                   4976: 
1.777     albertel 4977: sub auto_validate_class_sec {
1.773     raeburn  4978:     my ($cdom,$cnum,$owner,$inst_class) = @_;
                   4979:     my $homeserver = &homeserver($cnum,$cdom);
                   4980:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.774     banghart 4981:                         &escape($owner).':'.$cdom,$homeserver);
1.773     raeburn  4982:     return $response;
                   4983: }
                   4984: 
1.679     raeburn  4985: # ------------------------------------------------------- Course Group routines
                   4986: 
                   4987: sub get_coursegroups {
1.809     raeburn  4988:     my ($cdom,$cnum,$group,$namespace) = @_;
                   4989:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  4990: }
                   4991: 
1.679     raeburn  4992: sub modify_coursegroup {
                   4993:     my ($cdom,$cnum,$groupsettings) = @_;
                   4994:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   4995: }
                   4996: 
1.809     raeburn  4997: sub toggle_coursegroup_status {
                   4998:     my ($cdom,$cnum,$group,$action) = @_;
                   4999:     my ($from_namespace,$to_namespace);
                   5000:     if ($action eq 'delete') {
                   5001:         $from_namespace = 'coursegroups';
                   5002:         $to_namespace = 'deleted_groups';
                   5003:     } else {
                   5004:         $from_namespace = 'deleted_groups';
                   5005:         $to_namespace = 'coursegroups';
                   5006:     }
                   5007:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  5008:     if (my $tmp = &error(%curr_group)) {
                   5009:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   5010:         return ('read error',$tmp);
                   5011:     } else {
                   5012:         my %savedsettings = %curr_group; 
1.809     raeburn  5013:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  5014:         my $deloutcome;
                   5015:         if ($result eq 'ok') {
1.809     raeburn  5016:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  5017:         } else {
                   5018:             return ('write error',$result);
                   5019:         }
                   5020:         if ($deloutcome eq 'ok') {
                   5021:             return 'ok';
                   5022:         } else {
                   5023:             return ('delete error',$deloutcome);
                   5024:         }
                   5025:     }
                   5026: }
                   5027: 
1.679     raeburn  5028: sub modify_group_roles {
                   5029:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
                   5030:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   5031:     my $role = 'gr/'.&escape($userprivs);
                   5032:     my ($uname,$udom) = split(/:/,$user);
                   5033:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
1.684     raeburn  5034:     if ($result eq 'ok') {
                   5035:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   5036:     }
1.679     raeburn  5037:     return $result;
                   5038: }
                   5039: 
                   5040: sub modify_coursegroup_membership {
                   5041:     my ($cdom,$cnum,$membership) = @_;
                   5042:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   5043:     return $result;
                   5044: }
                   5045: 
1.682     raeburn  5046: sub get_active_groups {
                   5047:     my ($udom,$uname,$cdom,$cnum) = @_;
                   5048:     my $now = time;
                   5049:     my %groups = ();
                   5050:     foreach my $key (keys(%env)) {
1.811     albertel 5051:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  5052:             my ($start,$end) = split(/\./,$env{$key});
                   5053:             if (($end!=0) && ($end<$now)) { next; }
                   5054:             if (($start!=0) && ($start>$now)) { next; }
                   5055:             if ($1 eq $cdom && $2 eq $cnum) {
                   5056:                 $groups{$3} = $env{$key} ;
                   5057:             }
                   5058:         }
                   5059:     }
                   5060:     return %groups;
                   5061: }
                   5062: 
1.683     raeburn  5063: sub get_group_membership {
                   5064:     my ($cdom,$cnum,$group) = @_;
                   5065:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   5066: }
                   5067: 
                   5068: sub get_users_groups {
                   5069:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  5070:     my @usersgroups;
1.683     raeburn  5071:     my $cachetime=1800;
                   5072: 
                   5073:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  5074:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   5075:     if (defined($cached)) {
1.734     albertel 5076:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  5077:     } else {  
                   5078:         $grouplist = '';
1.816     raeburn  5079:         my $courseurl = &courseid_to_courseurl($courseid);
                   5080:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  5081:         my $access_end = $env{'course.'.$courseid.
                   5082:                               '.default_enrollment_end_date'};
                   5083:         my $now = time;
                   5084:         foreach my $key (keys(%roleshash)) {
                   5085:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   5086:                 my $group = $1;
                   5087:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   5088:                     my $start = $2;
                   5089:                     my $end = $1;
                   5090:                     if ($start == -1) { next; } # deleted from group
                   5091:                     if (($start!=0) && ($start>$now)) { next; }
                   5092:                     if (($end!=0) && ($end<$now)) {
                   5093:                         if ($access_end && $access_end < $now) {
                   5094:                             if ($access_end - $end < 86400) {
                   5095:                                 push(@usersgroups,$group);
1.733     raeburn  5096:                             }
                   5097:                         }
1.817     raeburn  5098:                         next;
1.733     raeburn  5099:                     }
1.817     raeburn  5100:                     push(@usersgroups,$group);
1.683     raeburn  5101:                 }
                   5102:             }
                   5103:         }
1.817     raeburn  5104:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   5105:         $grouplist = join(':',@usersgroups);
                   5106:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  5107:     }
1.733     raeburn  5108:     return @usersgroups;
1.683     raeburn  5109: }
                   5110: 
                   5111: sub devalidate_getgroups_cache {
                   5112:     my ($udom,$uname,$cdom,$cnum)=@_;
                   5113:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 5114: 
1.683     raeburn  5115:     my $hashid="$udom:$uname:$courseid";
                   5116:     &devalidate_cache_new('getgroups',$hashid);
                   5117: }
                   5118: 
1.12      www      5119: # ------------------------------------------------------------------ Plain Text
                   5120: 
                   5121: sub plaintext {
1.742     raeburn  5122:     my ($short,$type,$cid) = @_;
1.758     albertel 5123:     if ($short =~ /^cr/) {
                   5124: 	return (split('/',$short))[-1];
                   5125:     }
1.742     raeburn  5126:     if (!defined($cid)) {
                   5127:         $cid = $env{'request.course.id'};
                   5128:     }
                   5129:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
                   5130:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
                   5131:                                           '.plaintext'});
                   5132:     }
                   5133:     my %rolenames = (
                   5134:                       Course => 'std',
                   5135:                       Group => 'alt1',
                   5136:                     );
                   5137:     if (defined($type) && 
                   5138:          defined($rolenames{$type}) && 
                   5139:          defined($prp{$short}{$rolenames{$type}})) {
                   5140:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   5141:     } else {
                   5142:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   5143:     }
1.12      www      5144: }
                   5145: 
                   5146: # ----------------------------------------------------------------- Assign Role
                   5147: 
                   5148: sub assignrole {
1.357     www      5149:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
1.21      www      5150:     my $mrole;
                   5151:     if ($role =~ /^cr\//) {
1.393     www      5152:         my $cwosec=$url;
1.811     albertel 5153:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      5154: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      5155:            &logthis('Refused custom assignrole: '.
                   5156:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 5157: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      5158:            return 'refused'; 
                   5159:         }
1.21      www      5160:         $mrole='cr';
1.678     raeburn  5161:     } elsif ($role =~ /^gr\//) {
                   5162:         my $cwogrp=$url;
1.811     albertel 5163:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  5164:         unless (&allowed('mdg',$cwogrp)) {
                   5165:             &logthis('Refused group assignrole: '.
                   5166:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   5167:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   5168:             return 'refused';
                   5169:         }
                   5170:         $mrole='gr';
1.21      www      5171:     } else {
1.82      www      5172:         my $cwosec=$url;
1.811     albertel 5173:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.373     www      5174:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
1.104     www      5175:            &logthis('Refused assignrole: '.
                   5176:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 5177: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      5178:            return 'refused'; 
                   5179:         }
1.21      www      5180:         $mrole=$role;
                   5181:     }
1.620     albertel 5182:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5183:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      5184:     if ($end) { $command.='_'.$end; }
1.21      www      5185:     if ($start) {
                   5186: 	if ($end) { 
1.81      www      5187:            $command.='_'.$start; 
1.21      www      5188:         } else {
1.81      www      5189:            $command.='_0_'.$start;
1.21      www      5190:         }
                   5191:     }
1.739     raeburn  5192:     my $origstart = $start;
                   5193:     my $origend = $end;
1.357     www      5194: # actually delete
                   5195:     if ($deleteflag) {
1.373     www      5196: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      5197: # modify command to delete the role
1.620     albertel 5198:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      5199:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 5200: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      5201: # set start and finish to negative values for userrolelog
                   5202:            $start=-1;
                   5203:            $end=-1;
                   5204:         }
                   5205:     }
                   5206: # send command
1.349     www      5207:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      5208: # log new user role if status is ok
1.349     www      5209:     if ($answer eq 'ok') {
1.663     raeburn  5210: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  5211: # for course roles, perform group memberships changes triggered by role change.
                   5212:         unless ($role =~ /^gr/) {
                   5213:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   5214:                                              $origstart);
                   5215:         }
1.349     www      5216:     }
                   5217:     return $answer;
1.169     harris41 5218: }
                   5219: 
                   5220: # -------------------------------------------------- Modify user authentication
1.197     www      5221: # Overrides without validation
                   5222: 
1.169     harris41 5223: sub modifyuserauth {
                   5224:     my ($udom,$uname,$umode,$upass)=@_;
                   5225:     my $uhome=&homeserver($uname,$udom);
1.197     www      5226:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   5227:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 5228:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   5229:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 5230:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   5231: 		     &escape($upass),$uhome);
1.620     albertel 5232:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      5233:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   5234:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   5235:     &log($udom,,$uname,$uhome,
1.620     albertel 5236:         'Authentication changed by '.$env{'user.domain'}.', '.
                   5237:                                      $env{'user.name'}.', '.$umode.
1.197     www      5238:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 5239:     unless ($reply eq 'ok') {
1.197     www      5240:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 5241: 	return 'error: '.$reply;
                   5242:     }   
1.170     harris41 5243:     return 'ok';
1.80      www      5244: }
                   5245: 
1.81      www      5246: # --------------------------------------------------------------- Modify a user
1.80      www      5247: 
1.81      www      5248: sub modifyuser {
1.206     matthew  5249:     my ($udom,    $uname, $uid,
                   5250:         $umode,   $upass, $first,
                   5251:         $middle,  $last,  $gene,
1.387     www      5252:         $forceid, $desiredhome, $email)=@_;
1.807     albertel 5253:     $udom= &LONCAPA::clean_domain($udom);
                   5254:     $uname=&LONCAPA::clean_username($uname);
1.81      www      5255:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      5256:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  5257: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   5258:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   5259:                                      ' desiredhome not specified'). 
1.620     albertel 5260:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   5261:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 5262:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      5263: # ----------------------------------------------------------------- Create User
1.406     albertel 5264:     if (($uhome eq 'no_host') && 
                   5265: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      5266:         my $unhome='';
1.844     albertel 5267:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  5268:             $unhome = $desiredhome;
1.620     albertel 5269: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   5270: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  5271:         } else { # load balancing routine for determining $unhome
1.81      www      5272:             my $loadm=10000000;
1.841     albertel 5273: 	    my %servers = &get_servers($udom,'library');
                   5274: 	    foreach my $tryserver (keys(%servers)) {
                   5275: 		my $answer=reply('load',$tryserver);
                   5276: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   5277: 		    $loadm=$answer;
                   5278: 		    $unhome=$tryserver;
                   5279: 		}
1.80      www      5280: 	    }
                   5281:         }
                   5282:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  5283: 	    return 'error: unable to find a home server for '.$uname.
                   5284:                    ' in domain '.$udom;
1.80      www      5285:         }
                   5286:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   5287:                          &escape($upass),$unhome);
                   5288: 	unless ($reply eq 'ok') {
                   5289:             return 'error: '.$reply;
                   5290:         }   
1.230     stredwic 5291:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      5292:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  5293: 	    return 'error: unable verify users home machine.';
1.80      www      5294:         }
1.209     matthew  5295:     }   # End of creation of new user
1.80      www      5296: # ---------------------------------------------------------------------- Add ID
                   5297:     if ($uid) {
                   5298:        $uid=~tr/A-Z/a-z/;
                   5299:        my %uidhash=&idrget($udom,$uname);
1.196     www      5300:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   5301:          && (!$forceid)) {
1.80      www      5302: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  5303: 	      return 'error: user id "'.$uid.'" does not match '.
                   5304:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      5305:           }
                   5306:        } else {
                   5307: 	  &idput($udom,($uname => $uid));
                   5308:        }
                   5309:     }
                   5310: # -------------------------------------------------------------- Add names, etc
1.313     matthew  5311:     my @tmp=&get('environment',
1.899     raeburn  5312: 		   ['firstname','middlename','lastname','generation','id',
                   5313:                     'permanentemail'],
1.134     albertel 5314: 		   $udom,$uname);
1.313     matthew  5315:     my %names;
                   5316:     if ($tmp[0] =~ m/^error:.*/) { 
                   5317:         %names=(); 
                   5318:     } else {
                   5319:         %names = @tmp;
                   5320:     }
1.388     www      5321: #
                   5322: # Make sure to not trash student environment if instructor does not bother
                   5323: # to supply name and email information
                   5324: #
                   5325:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  5326:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      5327:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  5328:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      5329:     if ($email) {
                   5330:        $email=~s/[^\w\@\.\-\,]//gs;
                   5331:        if ($email=~/\@/) { $names{'notification'} = $email;
                   5332: 			   $names{'critnotification'} = $email;
                   5333: 			   $names{'permanentemail'} = $email; }
                   5334:     }
1.899     raeburn  5335:     if ($uid) { $names{'id'}  = $uid; }
1.134     albertel 5336:     my $reply = &put('environment', \%names, $udom,$uname);
                   5337:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.899     raeburn  5338:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
1.680     www      5339:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.81      www      5340:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      5341:              $umode.', '.$first.', '.$middle.', '.
                   5342: 	     $last.', '.$gene.' by '.
1.620     albertel 5343:              $env{'user.name'}.' at '.$env{'user.domain'});
1.134     albertel 5344:     return 'ok';
1.80      www      5345: }
                   5346: 
1.81      www      5347: # -------------------------------------------------------------- Modify student
1.80      www      5348: 
1.81      www      5349: sub modifystudent {
                   5350:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.515     raeburn  5351:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
1.455     albertel 5352:     if (!$cid) {
1.620     albertel 5353: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5354: 	    return 'not_in_class';
                   5355: 	}
1.80      www      5356:     }
                   5357: # --------------------------------------------------------------- Make the user
1.81      www      5358:     my $reply=&modifyuser
1.209     matthew  5359: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      5360:          $desiredhome,$email);
1.80      www      5361:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  5362:     # This will cause &modify_student_enrollment to get the uid from the
                   5363:     # students environment
                   5364:     $uid = undef if (!$forceid);
1.455     albertel 5365:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.515     raeburn  5366: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
1.297     matthew  5367:     return $reply;
                   5368: }
                   5369: 
                   5370: sub modify_student_enrollment {
1.515     raeburn  5371:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
1.455     albertel 5372:     my ($cdom,$cnum,$chome);
                   5373:     if (!$cid) {
1.620     albertel 5374: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5375: 	    return 'not_in_class';
                   5376: 	}
1.620     albertel 5377: 	$cdom=$env{'course.'.$cid.'.domain'};
                   5378: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 5379:     } else {
                   5380: 	($cdom,$cnum)=split(/_/,$cid);
                   5381:     }
1.620     albertel 5382:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 5383:     if (!$chome) {
1.457     raeburn  5384: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  5385:     }
1.455     albertel 5386:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  5387:     # Make sure the user exists
1.81      www      5388:     my $uhome=&homeserver($uname,$udom);
                   5389:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5390: 	return 'error: no such user';
                   5391:     }
1.297     matthew  5392:     # Get student data if we were not given enough information
                   5393:     if (!defined($first)  || $first  eq '' || 
                   5394:         !defined($last)   || $last   eq '' || 
                   5395:         !defined($uid)    || $uid    eq '' || 
                   5396:         !defined($middle) || $middle eq '' || 
                   5397:         !defined($gene)   || $gene   eq '') {
1.294     matthew  5398:         # They did not supply us with enough data to enroll the student, so
                   5399:         # we need to pick up more information.
1.297     matthew  5400:         my %tmp = &get('environment',
1.294     matthew  5401:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  5402:                        ,$udom,$uname);
                   5403: 
1.800     albertel 5404:         #foreach my $key (keys(%tmp)) {
                   5405:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 5406:         #}
1.294     matthew  5407:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   5408:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   5409:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  5410:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  5411:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   5412:     }
1.556     albertel 5413:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 5414:     my $reply=cput('classlist',
                   5415: 		   {"$uname:$udom" => 
1.515     raeburn  5416: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 5417: 		   $cdom,$cnum);
1.81      www      5418:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   5419: 	return 'error: '.$reply;
1.652     albertel 5420:     } else {
                   5421: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      5422:     }
1.297     matthew  5423:     # Add student role to user
1.83      www      5424:     my $uurl='/'.$cid;
1.81      www      5425:     $uurl=~s/\_/\//g;
                   5426:     if ($usec) {
                   5427: 	$uurl.='/'.$usec;
                   5428:     }
                   5429:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21      www      5430: }
                   5431: 
1.556     albertel 5432: sub format_name {
                   5433:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   5434:     my $name;
                   5435:     if ($first ne 'lastname') {
                   5436: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   5437:     } else {
                   5438: 	if ($lastname=~/\S/) {
                   5439: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   5440: 	    $name=~s/\s+,/,/;
                   5441: 	} else {
                   5442: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   5443: 	}
                   5444:     }
                   5445:     $name=~s/^\s+//;
                   5446:     $name=~s/\s+$//;
                   5447:     $name=~s/\s+/ /g;
                   5448:     return $name;
                   5449: }
                   5450: 
1.84      www      5451: # ------------------------------------------------- Write to course preferences
                   5452: 
                   5453: sub writecoursepref {
                   5454:     my ($courseid,%prefs)=@_;
                   5455:     $courseid=~s/^\///;
                   5456:     $courseid=~s/\_/\//g;
                   5457:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   5458:     my $chome=homeserver($cnum,$cdomain);
                   5459:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   5460: 	return 'error: no such course';
                   5461:     }
                   5462:     my $cstring='';
1.800     albertel 5463:     foreach my $pref (keys(%prefs)) {
                   5464: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 5465:     }
1.84      www      5466:     $cstring=~s/\&$//;
                   5467:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   5468: }
                   5469: 
                   5470: # ---------------------------------------------------------- Make/modify course
                   5471: 
                   5472: sub createcourse {
1.741     raeburn  5473:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
                   5474:         $course_owner,$crstype)=@_;
1.84      www      5475:     $url=&declutter($url);
                   5476:     my $cid='';
1.264     matthew  5477:     unless (&allowed('ccc',$udom)) {
1.84      www      5478:         return 'refused';
                   5479:     }
                   5480: # ------------------------------------------------------------------- Create ID
1.674     www      5481:    my $uname=int(1+rand(9)).
                   5482:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   5483:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      5484:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   5485: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 5486:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      5487:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5488:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   5489:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 5490:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      5491:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5492:            return 'error: unable to generate unique course-ID';
                   5493:        } 
                   5494:    }
1.264     matthew  5495: # ------------------------------------------------ Check supplied server name
1.620     albertel 5496:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.845     albertel 5497:     if (! &is_library($course_server)) {
1.264     matthew  5498:         return 'error:bad server name '.$course_server;
                   5499:     }
1.84      www      5500: # ------------------------------------------------------------- Make the course
                   5501:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  5502:                       $course_server);
1.84      www      5503:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 5504:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      5505:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5506: 	return 'error: no such course';
                   5507:     }
1.271     www      5508: # ----------------------------------------------------------------- Course made
1.516     raeburn  5509: # log existence
                   5510:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
1.741     raeburn  5511:                  ':'.&escape($inst_code).':'.&escape($course_owner).':'.
                   5512:                   &escape($crstype),$uhome);
1.358     www      5513:     &flushcourselogs();
                   5514: # set toplevel url
1.271     www      5515:     my $topurl=$url;
                   5516:     unless ($nonstandard) {
                   5517: # ------------------------------------------ For standard courses, make top url
                   5518:         my $mapurl=&clutter($url);
1.278     www      5519:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 5520:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      5521: <map>
                   5522: <resource id="1" type="start"></resource>
                   5523: <resource id="2" src="$mapurl"></resource>
                   5524: <resource id="3" type="finish"></resource>
                   5525: <link index="1" from="1" to="2"></link>
                   5526: <link index="2" from="2" to="3"></link>
                   5527: </map>
                   5528: ENDINITMAP
                   5529:         $topurl=&declutter(
1.638     albertel 5530:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      5531:                           );
                   5532:     }
                   5533: # ----------------------------------------------------------- Write preferences
1.84      www      5534:     &writecoursepref($udom.'_'.$uname,
                   5535:                      ('description' => $description,
1.271     www      5536:                       'url'         => $topurl));
1.84      www      5537:     return '/'.$udom.'/'.$uname;
                   5538: }
                   5539: 
1.813     albertel 5540: sub is_course {
                   5541:     my ($cdom,$cnum) = @_;
                   5542:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
                   5543: 				undef,'.');
                   5544:     if (exists($courses{$cdom.'_'.$cnum})) {
                   5545:         return 1;
                   5546:     }
                   5547:     return 0;
                   5548: }
                   5549: 
1.21      www      5550: # ---------------------------------------------------------- Assign Custom Role
                   5551: 
                   5552: sub assigncustomrole {
1.357     www      5553:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21      www      5554:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357     www      5555:                        $end,$start,$deleteflag);
1.21      www      5556: }
                   5557: 
                   5558: # ----------------------------------------------------------------- Revoke Role
                   5559: 
                   5560: sub revokerole {
1.357     www      5561:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21      www      5562:     my $now=time;
1.357     www      5563:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21      www      5564: }
                   5565: 
                   5566: # ---------------------------------------------------------- Revoke Custom Role
                   5567: 
                   5568: sub revokecustomrole {
1.357     www      5569:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21      www      5570:     my $now=time;
1.357     www      5571:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
                   5572:            $deleteflag);
1.17      www      5573: }
                   5574: 
1.533     banghart 5575: # ------------------------------------------------------------ Disk usage
1.535     albertel 5576: sub diskusage {
1.533     banghart 5577:     my ($udom,$uname,$directoryRoot)=@_;
                   5578:     $directoryRoot =~ s/\/$//;
1.535     albertel 5579:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
1.514     albertel 5580:     return $listing;
1.512     banghart 5581: }
                   5582: 
1.566     banghart 5583: sub is_locked {
                   5584:     my ($file_name, $domain, $user) = @_;
                   5585:     my @check;
                   5586:     my $is_locked;
                   5587:     push @check, $file_name;
1.613     albertel 5588:     my %locked = &get('file_permissions',\@check,
1.620     albertel 5589: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 5590:     my ($tmp)=keys(%locked);
                   5591:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  5592:     
1.566     banghart 5593:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  5594:         $is_locked = 'false';
                   5595:         foreach my $entry (@{$locked{$file_name}}) {
                   5596:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  5597:                $is_locked = 'true';
                   5598:                last;
1.745     raeburn  5599:            }
                   5600:        }
1.566     banghart 5601:     } else {
                   5602:         $is_locked = 'false';
                   5603:     }
                   5604: }
                   5605: 
1.759     albertel 5606: sub declutter_portfile {
                   5607:     my ($file) = @_;
1.833     albertel 5608:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 5609:     return $file;
                   5610: }
                   5611: 
1.559     banghart 5612: # ------------------------------------------------------------- Mark as Read Only
                   5613: 
                   5614: sub mark_as_readonly {
                   5615:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 5616:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5617:     my ($tmp)=keys(%current_permissions);
                   5618:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 5619:     foreach my $file (@{$files}) {
1.759     albertel 5620: 	$file = &declutter_portfile($file);
1.561     banghart 5621:         push(@{$current_permissions{$file}},$what);
1.559     banghart 5622:     }
1.613     albertel 5623:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5624:     return;
                   5625: }
                   5626: 
1.572     banghart 5627: # ------------------------------------------------------------Save Selected Files
                   5628: 
                   5629: sub save_selected_files {
                   5630:     my ($user, $path, @files) = @_;
                   5631:     my $filename = $user."savedfiles";
1.573     banghart 5632:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 5633:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 5634:     foreach my $file (@files) {
1.620     albertel 5635:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 5636:     }
                   5637:     foreach my $file (@other_files) {
1.574     banghart 5638:         print (OUT $file."\n");
1.572     banghart 5639:     }
1.574     banghart 5640:     close (OUT);
1.572     banghart 5641:     return 'ok';
                   5642: }
                   5643: 
1.574     banghart 5644: sub clear_selected_files {
                   5645:     my ($user) = @_;
                   5646:     my $filename = $user."savedfiles";
                   5647:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5648:     print (OUT undef);
                   5649:     close (OUT);
                   5650:     return ("ok");    
                   5651: }
                   5652: 
1.572     banghart 5653: sub files_in_path {
                   5654:     my ($user, $path) = @_;
                   5655:     my $filename = $user."savedfiles";
                   5656:     my %return_files;
1.574     banghart 5657:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 5658:     while (my $line_in = <IN>) {
1.574     banghart 5659:         chomp ($line_in);
                   5660:         my @paths_and_file = split (m!/!, $line_in);
                   5661:         my $file_part = pop (@paths_and_file);
                   5662:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 5663:         $path_part.='/';
                   5664:         my $path_and_file = $path_part.$file_part;
                   5665:         if ($path_part eq $path) {
                   5666:             $return_files{$file_part}= 'selected';
                   5667:         }
                   5668:     }
1.574     banghart 5669:     close (IN);
                   5670:     return (\%return_files);
1.572     banghart 5671: }
                   5672: 
                   5673: # called in portfolio select mode, to show files selected NOT in current directory
                   5674: sub files_not_in_path {
                   5675:     my ($user, $path) = @_;
                   5676:     my $filename = $user."savedfiles";
                   5677:     my @return_files;
                   5678:     my $path_part;
1.800     albertel 5679:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5680:     while (my $line = <IN>) {
1.572     banghart 5681:         #ok, I know it's clunky, but I want it to work
1.800     albertel 5682:         my @paths_and_file = split(m|/|, $line);
                   5683:         my $file_part = pop(@paths_and_file);
                   5684:         chomp($file_part);
                   5685:         my $path_part = join('/', @paths_and_file);
1.572     banghart 5686:         $path_part .= '/';
                   5687:         my $path_and_file = $path_part.$file_part;
                   5688:         if ($path_part ne $path) {
1.800     albertel 5689:             push(@return_files, ($path_and_file));
1.572     banghart 5690:         }
                   5691:     }
1.800     albertel 5692:     close(OUT);
1.574     banghart 5693:     return (@return_files);
1.572     banghart 5694: }
                   5695: 
1.745     raeburn  5696: #----------------------------------------------Get portfolio file permissions
1.629     banghart 5697: 
1.745     raeburn  5698: sub get_portfile_permissions {
                   5699:     my ($domain,$user) = @_;
1.613     albertel 5700:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5701:     my ($tmp)=keys(%current_permissions);
                   5702:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5703:     return \%current_permissions;
                   5704: }
                   5705: 
                   5706: #---------------------------------------------Get portfolio file access controls
                   5707: 
1.749     raeburn  5708: sub get_access_controls {
1.745     raeburn  5709:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 5710:     my %access;
                   5711:     my $real_file = $file;
                   5712:     $file =~ s/\.meta$//;
1.745     raeburn  5713:     if (defined($file)) {
1.749     raeburn  5714:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   5715:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 5716:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  5717:             }
                   5718:         }
1.745     raeburn  5719:     } else {
1.749     raeburn  5720:         foreach my $key (keys(%{$current_permissions})) {
                   5721:             if ($key =~ /\0accesscontrol$/) {
                   5722:                 if (defined($group)) {
                   5723:                     if ($key !~ m-^\Q$group\E/-) {
                   5724:                         next;
                   5725:                     }
                   5726:                 }
                   5727:                 my ($fullpath) = split(/\0/,$key);
                   5728:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   5729:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   5730:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   5731:                     }
                   5732:                 }
                   5733:             }
                   5734:         }
                   5735:     }
                   5736:     return %access;
                   5737: }
                   5738: 
                   5739: sub modify_access_controls {
                   5740:     my ($file_name,$changes,$domain,$user)=@_;
                   5741:     my ($outcome,$deloutcome);
                   5742:     my %store_permissions;
                   5743:     my %new_values;
                   5744:     my %new_control;
                   5745:     my %translation;
                   5746:     my @deletions = ();
                   5747:     my $now = time;
                   5748:     if (exists($$changes{'activate'})) {
                   5749:         if (ref($$changes{'activate'}) eq 'HASH') {
                   5750:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   5751:             my $numnew = scalar(@newitems);
                   5752:             for (my $i=0; $i<$numnew; $i++) {
                   5753:                 my $newkey = $newitems[$i];
                   5754:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  5755:                 if ($newkey =~ /^\d+:/) { 
                   5756:                     $newkey =~ s/^(\d+)/$newid/;
                   5757:                     $translation{$1} = $newid;
                   5758:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   5759:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   5760:                     $translation{$1} = $newid;
                   5761:                 }
1.749     raeburn  5762:                 $new_values{$file_name."\0".$newkey} = 
                   5763:                                           $$changes{'activate'}{$newitems[$i]};
                   5764:                 $new_control{$newkey} = $now;
                   5765:             }
                   5766:         }
                   5767:     }
                   5768:     my %todelete;
                   5769:     my %changed_items;
                   5770:     foreach my $action ('delete','update') {
                   5771:         if (exists($$changes{$action})) {
                   5772:             if (ref($$changes{$action}) eq 'HASH') {
                   5773:                 foreach my $key (keys(%{$$changes{$action}})) {
                   5774:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   5775:                     if ($action eq 'delete') { 
                   5776:                         $todelete{$itemnum} = 1;
                   5777:                     } else {
                   5778:                         $changed_items{$itemnum} = $key;
                   5779:                     }
                   5780:                 }
1.745     raeburn  5781:             }
                   5782:         }
1.749     raeburn  5783:     }
                   5784:     # get lock on access controls for file.
                   5785:     my $lockhash = {
                   5786:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   5787:                                                        ':'.$env{'user.domain'},
                   5788:                    }; 
                   5789:     my $tries = 0;
                   5790:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5791:    
                   5792:     while (($gotlock ne 'ok') && $tries <3) {
                   5793:         $tries ++;
                   5794:         sleep 1;
                   5795:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5796:     }
                   5797:     if ($gotlock eq 'ok') {
                   5798:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   5799:         my ($tmp)=keys(%curr_permissions);
                   5800:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   5801:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   5802:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   5803:             if (ref($curr_controls) eq 'HASH') {
                   5804:                 foreach my $control_item (keys(%{$curr_controls})) {
                   5805:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   5806:                     if (defined($todelete{$itemnum})) {
                   5807:                         push(@deletions,$file_name."\0".$control_item);
                   5808:                     } else {
                   5809:                         if (defined($changed_items{$itemnum})) {
                   5810:                             $new_control{$changed_items{$itemnum}} = $now;
                   5811:                             push(@deletions,$file_name."\0".$control_item);
                   5812:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   5813:                         } else {
                   5814:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   5815:                         }
                   5816:                     }
1.745     raeburn  5817:                 }
                   5818:             }
                   5819:         }
1.749     raeburn  5820:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   5821:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   5822:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   5823:         #  remove lock
                   5824:         my @del_lock = ($file_name."\0".'locked_access_records');
                   5825:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  5826:         my ($file,$group);
                   5827:         if (&is_course($domain,$user)) {
                   5828:             ($group,$file) = split(/\//,$file_name,2);
                   5829:         } else {
                   5830:             $file = $file_name;
                   5831:         }
                   5832:         my $sqlresult =
                   5833:             &update_portfolio_table($user,$domain,$file,'portfolio_access',
                   5834:                                     $group);
1.749     raeburn  5835:     } else {
                   5836:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  5837:     }
1.749     raeburn  5838:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  5839: }
                   5840: 
1.827     raeburn  5841: sub make_public_indefinitely {
                   5842:     my ($requrl) = @_;
                   5843:     my $now = time;
                   5844:     my $action = 'activate';
                   5845:     my $aclnum = 0;
                   5846:     if (&is_portfolio_url($requrl)) {
                   5847:         my (undef,$udom,$unum,$file_name,$group) =
                   5848:             &parse_portfolio_url($requrl);
                   5849:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   5850:         my %access_controls = &get_access_controls($current_perms,
                   5851:                                                    $group,$file_name);
                   5852:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   5853:             my ($num,$scope,$end,$start) = 
                   5854:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   5855:             if ($scope eq 'public') {
                   5856:                 if ($start <= $now && $end == 0) {
                   5857:                     $action = 'none';
                   5858:                 } else {
                   5859:                     $action = 'update';
                   5860:                     $aclnum = $num;
                   5861:                 }
                   5862:                 last;
                   5863:             }
                   5864:         }
                   5865:         if ($action eq 'none') {
                   5866:              return 'ok';
                   5867:         } else {
                   5868:             my %changes;
                   5869:             my $newend = 0;
                   5870:             my $newstart = $now;
                   5871:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   5872:             $changes{$action}{$newkey} = {
                   5873:                 type => 'public',
                   5874:                 time => {
                   5875:                     start => $newstart,
                   5876:                     end   => $newend,
                   5877:                 },
                   5878:             };
                   5879:             my ($outcome,$deloutcome,$new_values,$translation) =
                   5880:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   5881:             return $outcome;
                   5882:         }
                   5883:     } else {
                   5884:         return 'invalid';
                   5885:     }
                   5886: }
                   5887: 
1.745     raeburn  5888: #------------------------------------------------------Get Marked as Read Only
                   5889: 
                   5890: sub get_marked_as_readonly {
                   5891:     my ($domain,$user,$what,$group) = @_;
                   5892:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 5893:     my @readonly_files;
1.629     banghart 5894:     my $cmp1=$what;
                   5895:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  5896:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5897:         if (defined($group)) {
                   5898:             if ($file_name !~ m-^\Q$group\E/-) {
                   5899:                 next;
                   5900:             }
                   5901:         }
1.561     banghart 5902:         if (ref($value) eq "ARRAY"){
                   5903:             foreach my $stored_what (@{$value}) {
1.629     banghart 5904:                 my $cmp2=$stored_what;
1.759     albertel 5905:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  5906:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  5907:                 }
1.629     banghart 5908:                 if ($cmp1 eq $cmp2) {
1.561     banghart 5909:                     push(@readonly_files, $file_name);
1.745     raeburn  5910:                     last;
1.563     banghart 5911:                 } elsif (!defined($what)) {
                   5912:                     push(@readonly_files, $file_name);
1.745     raeburn  5913:                     last;
1.561     banghart 5914:                 }
                   5915:             }
1.745     raeburn  5916:         }
1.561     banghart 5917:     }
                   5918:     return @readonly_files;
                   5919: }
1.577     banghart 5920: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 5921: 
1.577     banghart 5922: sub get_marked_as_readonly_hash {
1.745     raeburn  5923:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 5924:     my %readonly_files;
1.745     raeburn  5925:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5926:         if (defined($group)) {
                   5927:             if ($file_name !~ m-^\Q$group\E/-) {
                   5928:                 next;
                   5929:             }
                   5930:         }
1.577     banghart 5931:         if (ref($value) eq "ARRAY"){
                   5932:             foreach my $stored_what (@{$value}) {
1.745     raeburn  5933:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 5934:                     foreach my $lock_descriptor(@{$stored_what}) {
                   5935:                         if ($lock_descriptor eq 'graded') {
                   5936:                             $readonly_files{$file_name} = 'graded';
                   5937:                         } elsif ($lock_descriptor eq 'handback') {
                   5938:                             $readonly_files{$file_name} = 'handback';
                   5939:                         } else {
                   5940:                             if (!exists($readonly_files{$file_name})) {
                   5941:                                 $readonly_files{$file_name} = 'locked';
                   5942:                             }
                   5943:                         }
1.745     raeburn  5944:                     }
1.750     banghart 5945:                 } 
1.577     banghart 5946:             }
                   5947:         } 
                   5948:     }
                   5949:     return %readonly_files;
                   5950: }
1.559     banghart 5951: # ------------------------------------------------------------ Unmark as Read Only
                   5952: 
                   5953: sub unmark_as_readonly {
1.629     banghart 5954:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   5955:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  5956:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 5957:     $file_name = &declutter_portfile($file_name);
1.634     albertel 5958:     my $symb_crs = $what;
                   5959:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  5960:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 5961:     my ($tmp)=keys(%current_permissions);
                   5962:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5963:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 5964:     foreach my $file (@readonly_files) {
1.759     albertel 5965: 	my $clean_file = &declutter_portfile($file);
                   5966: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 5967: 	my $current_locks = $current_permissions{$file};
1.563     banghart 5968:         my @new_locks;
                   5969:         my @del_keys;
                   5970:         if (ref($current_locks) eq "ARRAY"){
                   5971:             foreach my $locker (@{$current_locks}) {
1.632     albertel 5972:                 my $compare=$locker;
1.749     raeburn  5973:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  5974:                     $compare=join('',@{$locker});
1.746     raeburn  5975:                     if ($compare ne $symb_crs) {
                   5976:                         push(@new_locks, $locker);
                   5977:                     }
1.563     banghart 5978:                 }
                   5979:             }
1.650     albertel 5980:             if (scalar(@new_locks) > 0) {
1.563     banghart 5981:                 $current_permissions{$file} = \@new_locks;
                   5982:             } else {
                   5983:                 push(@del_keys, $file);
1.613     albertel 5984:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 5985:                 delete($current_permissions{$file});
1.563     banghart 5986:             }
                   5987:         }
1.561     banghart 5988:     }
1.613     albertel 5989:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5990:     return;
                   5991: }
1.512     banghart 5992: 
1.17      www      5993: # ------------------------------------------------------------ Directory lister
                   5994: 
                   5995: sub dirlist {
1.253     stredwic 5996:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
                   5997: 
1.18      www      5998:     $uri=~s/^\///;
                   5999:     $uri=~s/\/$//;
1.253     stredwic 6000:     my ($udom, $uname);
                   6001:     (undef,$udom,$uname)=split(/\//,$uri);
                   6002:     if(defined($userdomain)) {
                   6003:         $udom = $userdomain;
                   6004:     }
                   6005:     if(defined($username)) {
                   6006:         $uname = $username;
                   6007:     }
                   6008: 
                   6009:     my $dirRoot = $perlvar{'lonDocRoot'};
                   6010:     if(defined($alternateDirectoryRoot)) {
                   6011:         $dirRoot = $alternateDirectoryRoot;
                   6012:         $dirRoot =~ s/\/$//;
1.751     banghart 6013:     }
1.253     stredwic 6014: 
                   6015:     if($udom) {
                   6016:         if($uname) {
1.800     albertel 6017:             my $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   6018: 				 &homeserver($uname,$udom));
1.605     matthew  6019:             my @listing_results;
                   6020:             if ($listing eq 'unknown_cmd') {
1.800     albertel 6021:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   6022: 				  &homeserver($uname,$udom));
1.605     matthew  6023:                 @listing_results = split(/:/,$listing);
                   6024:             } else {
                   6025:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6026:             }
                   6027:             return @listing_results;
1.253     stredwic 6028:         } elsif(!defined($alternateDirectoryRoot)) {
1.800     albertel 6029:             my %allusers;
1.841     albertel 6030: 	    my %servers = &get_servers($udom,'library');
                   6031: 	    foreach my $tryserver (keys(%servers)) {
                   6032: 		my $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   6033: 				     $udom, $tryserver);
                   6034: 		my @listing_results;
                   6035: 		if ($listing eq 'unknown_cmd') {
                   6036: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   6037: 				      $udom, $tryserver);
                   6038: 		    @listing_results = split(/:/,$listing);
                   6039: 		} else {
                   6040: 		    @listing_results =
                   6041: 			map { &unescape($_); } split(/:/,$listing);
                   6042: 		}
                   6043: 		if ($listing_results[0] ne 'no_such_dir' && 
                   6044: 		    $listing_results[0] ne 'empty'       &&
                   6045: 		    $listing_results[0] ne 'con_lost') {
                   6046: 		    foreach my $line (@listing_results) {
                   6047: 			my ($entry) = split(/&/,$line,2);
                   6048: 			$allusers{$entry} = 1;
                   6049: 		    }
                   6050: 		}
1.253     stredwic 6051:             }
                   6052:             my $alluserstr='';
1.800     albertel 6053:             foreach my $user (sort(keys(%allusers))) {
                   6054:                 $alluserstr.=$user.'&user:';
1.253     stredwic 6055:             }
                   6056:             $alluserstr=~s/:$//;
                   6057:             return split(/:/,$alluserstr);
                   6058:         } else {
1.800     albertel 6059:             return ('missing user name');
1.253     stredwic 6060:         }
                   6061:     } elsif(!defined($alternateDirectoryRoot)) {
1.841     albertel 6062:         my @all_domains = sort(&all_domains());
                   6063:          foreach my $domain (@all_domains) {
                   6064:              $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   6065:          }
                   6066:          return @all_domains;
                   6067:      } else {
1.800     albertel 6068:         return ('missing domain');
1.275     stredwic 6069:     }
                   6070: }
                   6071: 
                   6072: # --------------------------------------------- GetFileTimestamp
                   6073: # This function utilizes dirlist and returns the date stamp for
                   6074: # when it was last modified.  It will also return an error of -1
                   6075: # if an error occurs
                   6076: 
1.410     matthew  6077: ##
                   6078: ## FIXME: This subroutine assumes its caller knows something about the
                   6079: ## directory structure of the home server for the student ($root).
                   6080: ## Not a good assumption to make.  Since this is for looking up files
                   6081: ## in user directories, the full path should be constructed by lond, not
                   6082: ## whatever machine we request data from.
                   6083: ##
1.275     stredwic 6084: sub GetFileTimestamp {
                   6085:     my ($studentDomain,$studentName,$filename,$root)=@_;
1.807     albertel 6086:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   6087:     $studentName   = &LONCAPA::clean_username($studentName);
1.275     stredwic 6088:     my $subdir=$studentName.'__';
                   6089:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   6090:     my $proname="$studentDomain/$subdir/$studentName";
                   6091:     $proname .= '/'.$filename;
1.375     matthew  6092:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
                   6093:                                               $studentName, $root);
1.275     stredwic 6094:     my @stats = split('&', $fileStat);
                   6095:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  6096:         # @stats contains first the filename, then the stat output
                   6097:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 6098:     } else {
                   6099:         return -1;
1.253     stredwic 6100:     }
1.26      www      6101: }
                   6102: 
1.712     albertel 6103: sub stat_file {
                   6104:     my ($uri) = @_;
1.787     albertel 6105:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 6106: 
1.712     albertel 6107:     my ($udom,$uname,$file,$dir);
                   6108:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   6109: 	($udom,$uname,$file) =
1.811     albertel 6110: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 6111: 	$file = 'userfiles/'.$file;
1.740     www      6112: 	$dir = &propath($udom,$uname);
1.712     albertel 6113:     }
                   6114:     if ($uri =~ m-^/res/-) {
                   6115: 	($udom,$uname) = 
1.807     albertel 6116: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 6117: 	$file = $uri;
                   6118:     }
                   6119: 
                   6120:     if (!$udom || !$uname || !$file) {
                   6121: 	# unable to handle the uri
                   6122: 	return ();
                   6123:     }
                   6124: 
                   6125:     my ($result) = &dirlist($file,$udom,$uname,$dir);
                   6126:     my @stats = split('&', $result);
1.721     banghart 6127:     
1.712     albertel 6128:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   6129: 	shift(@stats); #filename is first
                   6130: 	return @stats;
                   6131:     }
                   6132:     return ();
                   6133: }
                   6134: 
1.26      www      6135: # -------------------------------------------------------- Value of a Condition
                   6136: 
1.713     albertel 6137: # gets the value of a specific preevaluated condition
                   6138: #    stored in the string  $env{user.state.<cid>}
                   6139: # or looks up a condition reference in the bighash and if if hasn't
                   6140: # already been evaluated recurses into docondval to get the value of
                   6141: # the condition, then memoizing it to 
                   6142: #   $env{user.state.<cid>.<condition>}
1.40      www      6143: sub directcondval {
                   6144:     my $number=shift;
1.620     albertel 6145:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 6146: 	&Apache::lonuserstate::evalstate();
                   6147:     }
1.713     albertel 6148:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   6149: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   6150:     } elsif ($number =~ /^_/) {
                   6151: 	my $sub_condition;
                   6152: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   6153: 		&GDBM_READER(),0640)) {
                   6154: 	    $sub_condition=$bighash{'conditions'.$number};
                   6155: 	    untie(%bighash);
                   6156: 	}
                   6157: 	my $value = &docondval($sub_condition);
                   6158: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
                   6159: 	return $value;
                   6160:     }
1.620     albertel 6161:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   6162:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      6163:     } else {
                   6164:        return 2;
                   6165:     }
                   6166: }
                   6167: 
1.713     albertel 6168: # get the collection of conditions for this resource
1.26      www      6169: sub condval {
                   6170:     my $condidx=shift;
1.54      www      6171:     my $allpathcond='';
1.713     albertel 6172:     foreach my $cond (split(/\|/,$condidx)) {
                   6173: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   6174: 	    $allpathcond.=
                   6175: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   6176: 	}
1.191     harris41 6177:     }
1.54      www      6178:     $allpathcond=~s/\|$//;
1.713     albertel 6179:     return &docondval($allpathcond);
                   6180: }
                   6181: 
                   6182: #evaluates an expression of conditions
                   6183: sub docondval {
                   6184:     my ($allpathcond) = @_;
                   6185:     my $result=0;
                   6186:     if ($env{'request.course.id'}
                   6187: 	&& defined($allpathcond)) {
                   6188: 	my $operand='|';
                   6189: 	my @stack;
                   6190: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   6191: 	    if ($chunk eq '(') {
                   6192: 		push @stack,($operand,$result);
                   6193: 	    } elsif ($chunk eq ')') {
                   6194: 		my $before=pop @stack;
                   6195: 		if (pop @stack eq '&') {
                   6196: 		    $result=$result>$before?$before:$result;
                   6197: 		} else {
                   6198: 		    $result=$result>$before?$result:$before;
                   6199: 		}
                   6200: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   6201: 		$operand=$chunk;
                   6202: 	    } else {
                   6203: 		my $new=directcondval($chunk);
                   6204: 		if ($operand eq '&') {
                   6205: 		    $result=$result>$new?$new:$result;
                   6206: 		} else {
                   6207: 		    $result=$result>$new?$result:$new;
                   6208: 		}
                   6209: 	    }
                   6210: 	}
1.26      www      6211:     }
                   6212:     return $result;
1.421     albertel 6213: }
                   6214: 
                   6215: # ---------------------------------------------------- Devalidate courseresdata
                   6216: 
                   6217: sub devalidatecourseresdata {
                   6218:     my ($coursenum,$coursedomain)=@_;
                   6219:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 6220:     &devalidate_cache_new('courseres',$hashid);
1.28      www      6221: }
                   6222: 
1.763     www      6223: 
1.200     www      6224: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     6225: #
                   6226: #  Parameters:
                   6227: #      $coursenum    - Number of the course.
                   6228: #      $coursedomain - Domain at which the course was created.
                   6229: #  Returns:
                   6230: #     A hash of the course parameters along (I think) with timestamps
                   6231: #     and version info.
1.877     foxr     6232: 
1.624     albertel 6233: sub get_courseresdata {
                   6234:     my ($coursenum,$coursedomain)=@_;
1.200     www      6235:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   6236:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 6237:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 6238:     my %dumpreply;
1.417     albertel 6239:     unless (defined($cached)) {
1.624     albertel 6240: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 6241: 	$result=\%dumpreply;
1.251     albertel 6242: 	my ($tmp) = keys(%dumpreply);
                   6243: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 6244: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 6245: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   6246: 	    return $tmp;
1.416     albertel 6247: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 6248: 	    $result=undef;
1.599     albertel 6249: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 6250: 	}
                   6251:     }
1.624     albertel 6252:     return $result;
                   6253: }
                   6254: 
1.633     albertel 6255: sub devalidateuserresdata {
                   6256:     my ($uname,$udom)=@_;
                   6257:     my $hashid="$udom:$uname";
                   6258:     &devalidate_cache_new('userres',$hashid);
                   6259: }
                   6260: 
1.624     albertel 6261: sub get_userresdata {
                   6262:     my ($uname,$udom)=@_;
                   6263:     #most student don\'t have any data set, check if there is some data
                   6264:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   6265: 
                   6266:     my $hashid="$udom:$uname";
                   6267:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   6268:     if (!defined($cached)) {
                   6269: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   6270: 	$result=\%resourcedata;
                   6271: 	&do_cache_new('userres',$hashid,$result,600);
                   6272:     }
                   6273:     my ($tmp)=keys(%$result);
                   6274:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   6275: 	return $result;
                   6276:     }
                   6277:     #error 2 occurs when the .db doesn't exist
                   6278:     if ($tmp!~/error: 2 /) {
1.672     albertel 6279: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 6280: 		 " Trying to get resource data for ".
                   6281: 		 $uname." at ".$udom.": ".
                   6282: 		 $tmp."</font>");
                   6283:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 6284: 	#&EXT_cache_set($udom,$uname);
                   6285: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 6286: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 6287:     }
                   6288:     return $tmp;
                   6289: }
1.879     foxr     6290: #----------------------------------------------- resdata - return resource data
                   6291: #  Purpose:
                   6292: #    Return resource data for either users or for a course.
                   6293: #  Parameters:
                   6294: #     $name      - Course/user name.
                   6295: #     $domain    - Name of the domain the user/course is registered on.
                   6296: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   6297: #     @which     - Array of names of resources desired.
                   6298: #  Returns:
                   6299: #     The value of the first reasource in @which that is found in the
                   6300: #     resource hash.
                   6301: #  Exceptional Conditions:
                   6302: #     If the $type passed in is not valid (not the string 'course' or 
                   6303: #     'user', an undefined  reference is returned.
                   6304: #     If none of the resources are found, an undef is returned
1.624     albertel 6305: sub resdata {
                   6306:     my ($name,$domain,$type,@which)=@_;
                   6307:     my $result;
                   6308:     if ($type eq 'course') {
                   6309: 	$result=&get_courseresdata($name,$domain);
                   6310:     } elsif ($type eq 'user') {
                   6311: 	$result=&get_userresdata($name,$domain);
                   6312:     }
                   6313:     if (!ref($result)) { return $result; }    
1.251     albertel 6314:     foreach my $item (@which) {
1.417     albertel 6315: 	if (defined($result->{$item})) {
                   6316: 	    return $result->{$item};
1.251     albertel 6317: 	}
1.250     albertel 6318:     }
1.291     albertel 6319:     return undef;
1.200     www      6320: }
                   6321: 
1.379     matthew  6322: #
                   6323: # EXT resource caching routines
                   6324: #
                   6325: 
                   6326: sub clear_EXT_cache_status {
1.383     albertel 6327:     &delenv('cache.EXT.');
1.379     matthew  6328: }
                   6329: 
                   6330: sub EXT_cache_status {
                   6331:     my ($target_domain,$target_user) = @_;
1.383     albertel 6332:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 6333:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  6334:         # We know already the user has no data
                   6335:         return 1;
                   6336:     } else {
                   6337:         return 0;
                   6338:     }
                   6339: }
                   6340: 
                   6341: sub EXT_cache_set {
                   6342:     my ($target_domain,$target_user) = @_;
1.383     albertel 6343:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.633     albertel 6344:     #&appenv($cachename => time);
1.379     matthew  6345: }
                   6346: 
1.28      www      6347: # --------------------------------------------------------- Value of a Variable
1.58      www      6348: sub EXT {
1.715     albertel 6349: 
1.395     albertel 6350:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      6351:     unless ($varname) { return ''; }
1.218     albertel 6352:     #get real user name/domain, courseid and symb
                   6353:     my $courseid;
1.359     albertel 6354:     my $publicuser;
1.427     www      6355:     if ($symbparm) {
                   6356: 	$symbparm=&get_symb_from_alias($symbparm);
                   6357:     }
1.218     albertel 6358:     if (!($uname && $udom)) {
1.790     albertel 6359:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 6360:       if (!$symbparm) {	$symbparm=$cursymb; }
                   6361:     } else {
1.620     albertel 6362: 	$courseid=$env{'request.course.id'};
1.218     albertel 6363:     }
1.48      www      6364:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   6365:     my $rest;
1.320     albertel 6366:     if (defined($therest[0])) {
1.48      www      6367:        $rest=join('.',@therest);
                   6368:     } else {
                   6369:        $rest='';
                   6370:     }
1.320     albertel 6371: 
1.57      www      6372:     my $qualifierrest=$qualifier;
                   6373:     if ($rest) { $qualifierrest.='.'.$rest; }
                   6374:     my $spacequalifierrest=$space;
                   6375:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      6376:     if ($realm eq 'user') {
1.48      www      6377: # --------------------------------------------------------------- user.resource
                   6378: 	if ($space eq 'resource') {
1.651     albertel 6379: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   6380: 		  || defined($Apache::lonhomework::parsing_a_task))
                   6381: 		 &&
1.744     albertel 6382: 		 ($symbparm eq &symbread()) ) {	
                   6383: 		# if we are in the middle of processing the resource the
                   6384: 		# get the value we are planning on committing
                   6385:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   6386:                     return $Apache::lonhomework::results{$qualifierrest};
                   6387:                 } else {
                   6388:                     return $Apache::lonhomework::history{$qualifierrest};
                   6389:                 }
1.335     albertel 6390: 	    } else {
1.359     albertel 6391: 		my %restored;
1.620     albertel 6392: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 6393: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   6394: 		} else {
                   6395: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   6396: 		}
1.335     albertel 6397: 		return $restored{$qualifierrest};
                   6398: 	    }
1.48      www      6399: # ----------------------------------------------------------------- user.access
                   6400:         } elsif ($space eq 'access') {
1.218     albertel 6401: 	    # FIXME - not supporting calls for a specific user
1.48      www      6402:             return &allowed($qualifier,$rest);
                   6403: # ------------------------------------------ user.preferences, user.environment
                   6404:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 6405: 	    if (($uname eq $env{'user.name'}) &&
                   6406: 		($udom eq $env{'user.domain'})) {
                   6407: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 6408: 	    } else {
1.359     albertel 6409: 		my %returnhash;
                   6410: 		if (!$publicuser) {
                   6411: 		    %returnhash=&userenvironment($udom,$uname,
                   6412: 						 $qualifierrest);
                   6413: 		}
1.218     albertel 6414: 		return $returnhash{$qualifierrest};
                   6415: 	    }
1.48      www      6416: # ----------------------------------------------------------------- user.course
                   6417:         } elsif ($space eq 'course') {
1.218     albertel 6418: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 6419:             return $env{join('.',('request.course',$qualifier))};
1.48      www      6420: # ------------------------------------------------------------------- user.role
                   6421:         } elsif ($space eq 'role') {
1.218     albertel 6422: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 6423:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      6424:             if ($qualifier eq 'value') {
                   6425: 		return $role;
                   6426:             } elsif ($qualifier eq 'extent') {
                   6427:                 return $where;
                   6428:             }
                   6429: # ----------------------------------------------------------------- user.domain
                   6430:         } elsif ($space eq 'domain') {
1.218     albertel 6431:             return $udom;
1.48      www      6432: # ------------------------------------------------------------------- user.name
                   6433:         } elsif ($space eq 'name') {
1.218     albertel 6434:             return $uname;
1.48      www      6435: # ---------------------------------------------------- Any other user namespace
1.29      www      6436:         } else {
1.359     albertel 6437: 	    my %reply;
                   6438: 	    if (!$publicuser) {
                   6439: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   6440: 	    }
                   6441: 	    return $reply{$qualifierrest};
1.48      www      6442:         }
1.236     www      6443:     } elsif ($realm eq 'query') {
                   6444: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 6445:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   6446: 						[$spacequalifierrest]);
1.620     albertel 6447: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      6448:    } elsif ($realm eq 'request') {
1.48      www      6449: # ------------------------------------------------------------- request.browser
                   6450:         if ($space eq 'browser') {
1.430     www      6451: 	    if ($qualifier eq 'textremote') {
1.676     albertel 6452: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      6453: 		    return 1;
                   6454: 		} else {
                   6455: 		    return 0;
                   6456: 		}
                   6457: 	    } else {
1.620     albertel 6458: 		return $env{'browser.'.$qualifier};
1.430     www      6459: 	    }
1.57      www      6460: # ------------------------------------------------------------ request.filename
                   6461:         } else {
1.620     albertel 6462:             return $env{'request.'.$spacequalifierrest};
1.29      www      6463:         }
1.28      www      6464:     } elsif ($realm eq 'course') {
1.48      www      6465: # ---------------------------------------------------------- course.description
1.620     albertel 6466:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      6467:     } elsif ($realm eq 'resource') {
1.165     www      6468: 
1.620     albertel 6469: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 6470: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   6471: 	}
1.693     albertel 6472: 
                   6473: 	if ($space eq 'title') {
                   6474: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   6475: 	    return &gettitle($symbparm);
                   6476: 	}
                   6477: 	
                   6478: 	if ($space eq 'map') {
                   6479: 	    my ($map) = &decode_symb($symbparm);
                   6480: 	    return &symbread($map);
                   6481: 	}
1.905     albertel 6482: 	if ($space eq 'filename') {
                   6483: 	    if ($symbparm) {
                   6484: 		return &clutter((&decode_symb($symbparm))[2]);
                   6485: 	    }
                   6486: 	    return &hreflocation('',$env{'request.filename'});
                   6487: 	}
1.693     albertel 6488: 
                   6489: 	my ($section, $group, @groups);
1.593     albertel 6490: 	my ($courselevelm,$courselevel);
1.539     albertel 6491: 	if ($symbparm && defined($courseid) && 
1.620     albertel 6492: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      6493: 
1.218     albertel 6494: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      6495: 
1.60      www      6496: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 6497: 	    my $symbp=$symbparm;
1.735     albertel 6498: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 6499: 
                   6500: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   6501: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   6502: 
1.620     albertel 6503: 	    if (($env{'user.name'} eq $uname) &&
                   6504: 		($env{'user.domain'} eq $udom)) {
                   6505: 		$section=$env{'request.course.sec'};
1.733     raeburn  6506:                 @groups = split(/:/,$env{'request.course.groups'});  
                   6507:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 6508: 	    } else {
1.539     albertel 6509: 		if (! defined($usection)) {
1.551     albertel 6510: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 6511: 		} else {
                   6512: 		    $section = $usection;
                   6513: 		}
1.733     raeburn  6514:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 6515: 	    }
                   6516: 
                   6517: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   6518: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   6519: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   6520: 
1.593     albertel 6521: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 6522: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 6523: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      6524: 
1.60      www      6525: # ----------------------------------------------------------- first, check user
1.624     albertel 6526: 
                   6527: 	    my $userreply=&resdata($uname,$udom,'user',
                   6528: 				       ($courselevelr,$courselevelm,
                   6529: 					$courselevel));
                   6530: 	    if (defined($userreply)) { return $userreply; }
1.95      www      6531: 
1.594     albertel 6532: # ------------------------------------------------ second, check some of course
1.684     raeburn  6533:             my $coursereply;
1.691     raeburn  6534:             if (@groups > 0) {
                   6535:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   6536:                                        $mapparm,$spacequalifierrest);
1.684     raeburn  6537:                 if (defined($coursereply)) { return $coursereply; }
                   6538:             }
1.96      www      6539: 
1.684     raeburn  6540: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.624     albertel 6541: 				     $env{'course.'.$courseid.'.domain'},
                   6542: 				     'course',
                   6543: 				     ($seclevelr,$seclevelm,$seclevel,
                   6544: 				      $courselevelr));
1.287     albertel 6545: 	    if (defined($coursereply)) { return $coursereply; }
1.200     www      6546: 
1.60      www      6547: # ------------------------------------------------------ third, check map parms
1.218     albertel 6548: 	    my %parmhash=();
                   6549: 	    my $thisparm='';
                   6550: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 6551: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 6552: 		    &GDBM_READER(),0640)) {
1.218     albertel 6553: 		$thisparm=$parmhash{$symbparm};
                   6554: 		untie(%parmhash);
                   6555: 	    }
                   6556: 	    if ($thisparm) { return $thisparm; }
                   6557: 	}
1.594     albertel 6558: # ------------------------------------------ fourth, look in resource metadata
1.71      www      6559: 
1.218     albertel 6560: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 6561: 	my $filename;
                   6562: 	if (!$symbparm) { $symbparm=&symbread(); }
                   6563: 	if ($symbparm) {
1.409     www      6564: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 6565: 	} else {
1.620     albertel 6566: 	    $filename=$env{'request.filename'};
1.282     albertel 6567: 	}
                   6568: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.288     albertel 6569: 	if (defined($metadata)) { return $metadata; }
1.282     albertel 6570: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.288     albertel 6571: 	if (defined($metadata)) { return $metadata; }
1.142     www      6572: 
1.594     albertel 6573: # ---------------------------------------------- fourth, look in rest pf course
1.593     albertel 6574: 	if ($symbparm && defined($courseid) && 
1.620     albertel 6575: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 6576: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   6577: 				     $env{'course.'.$courseid.'.domain'},
                   6578: 				     'course',
                   6579: 				     ($courselevelm,$courselevel));
1.593     albertel 6580: 	    if (defined($coursereply)) { return $coursereply; }
                   6581: 	}
1.145     www      6582: # ------------------------------------------------------------------ Cascade up
1.218     albertel 6583: 	unless ($space eq '0') {
1.336     albertel 6584: 	    my @parts=split(/_/,$space);
                   6585: 	    my $id=pop(@parts);
                   6586: 	    my $part=join('_',@parts);
                   6587: 	    if ($part eq '') { $part='0'; }
                   6588: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 6589: 				 $symbparm,$udom,$uname,$section,1);
1.337     albertel 6590: 	    if (defined($partgeneral)) { return $partgeneral; }
1.218     albertel 6591: 	}
1.395     albertel 6592: 	if ($recurse) { return undef; }
                   6593: 	my $pack_def=&packages_tab_default($filename,$varname);
                   6594: 	if (defined($pack_def)) { return $pack_def; }
1.71      www      6595: 
1.48      www      6596: # ---------------------------------------------------- Any other user namespace
                   6597:     } elsif ($realm eq 'environment') {
                   6598: # ----------------------------------------------------------------- environment
1.620     albertel 6599: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   6600: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 6601: 	} else {
1.770     albertel 6602: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   6603: 		return '';
                   6604: 	    }
1.219     albertel 6605: 	    my %returnhash=&userenvironment($udom,$uname,
                   6606: 					    $spacequalifierrest);
                   6607: 	    return $returnhash{$spacequalifierrest};
                   6608: 	}
1.28      www      6609:     } elsif ($realm eq 'system') {
1.48      www      6610: # ----------------------------------------------------------------- system.time
                   6611: 	if ($space eq 'time') {
                   6612: 	    return time;
                   6613:         }
1.696     albertel 6614:     } elsif ($realm eq 'server') {
                   6615: # ----------------------------------------------------------------- system.time
                   6616: 	if ($space eq 'name') {
                   6617: 	    return $ENV{'SERVER_NAME'};
                   6618:         }
1.28      www      6619:     }
1.48      www      6620:     return '';
1.61      www      6621: }
                   6622: 
1.691     raeburn  6623: sub check_group_parms {
                   6624:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   6625:     my @groupitems = ();
                   6626:     my $resultitem;
                   6627:     my @levels = ($symbparm,$mapparm,$what);
                   6628:     foreach my $group (@{$groups}) {
                   6629:         foreach my $level (@levels) {
                   6630:              my $item = $courseid.'.['.$group.'].'.$level;
                   6631:              push(@groupitems,$item);
                   6632:         }
                   6633:     }
                   6634:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   6635:                             $env{'course.'.$courseid.'.domain'},
                   6636:                                      'course',@groupitems);
                   6637:     return $coursereply;
                   6638: }
                   6639: 
                   6640: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  6641:     my ($courseid,@groups) = @_;
                   6642:     @groups = sort(@groups);
1.691     raeburn  6643:     return @groups;
                   6644: }
                   6645: 
1.395     albertel 6646: sub packages_tab_default {
                   6647:     my ($uri,$varname)=@_;
                   6648:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 6649: 
                   6650:     my (@extension,@specifics,$do_default);
                   6651:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 6652: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 6653: 	if ($pack_type eq 'default') {
                   6654: 	    $do_default=1;
                   6655: 	} elsif ($pack_type eq 'extension') {
                   6656: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 6657: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 6658: 	    # only look at packages defaults for packages that this id is
1.738     albertel 6659: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   6660: 	}
                   6661:     }
                   6662:     # first look for a package that matches the requested part id
                   6663:     foreach my $package (@specifics) {
                   6664: 	my (undef,$pack_type,$pack_part)=@{$package};
                   6665: 	next if ($pack_part ne $part);
                   6666: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6667: 	    return $packagetab{"$pack_type&$name&default"};
                   6668: 	}
                   6669:     }
                   6670:     # look for any possible matching non extension_ package
                   6671:     foreach my $package (@specifics) {
                   6672: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 6673: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6674: 	    return $packagetab{"$pack_type&$name&default"};
                   6675: 	}
1.585     albertel 6676: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 6677: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   6678: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 6679: 	}
                   6680:     }
1.738     albertel 6681:     # look for any posible extension_ match
                   6682:     foreach my $package (@extension) {
                   6683: 	my ($package,$pack_type)=@{$package};
                   6684: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6685: 	    return $packagetab{"$pack_type&$name&default"};
                   6686: 	}
                   6687: 	if (defined($packagetab{$package."&$name&default"})) {
                   6688: 	    return $packagetab{$package."&$name&default"};
                   6689: 	}
                   6690:     }
                   6691:     # look for a global default setting
                   6692:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   6693: 	return $packagetab{"default&$name&default"};
                   6694:     }
1.395     albertel 6695:     return undef;
                   6696: }
                   6697: 
1.334     albertel 6698: sub add_prefix_and_part {
                   6699:     my ($prefix,$part)=@_;
                   6700:     my $keyroot;
                   6701:     if (defined($prefix) && $prefix !~ /^__/) {
                   6702: 	# prefix that has a part already
                   6703: 	$keyroot=$prefix;
                   6704:     } elsif (defined($prefix)) {
                   6705: 	# prefix that is missing a part
                   6706: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   6707:     } else {
                   6708: 	# no prefix at all
                   6709: 	if (defined($part)) { $keyroot='_'.$part; }
                   6710:     }
                   6711:     return $keyroot;
                   6712: }
                   6713: 
1.71      www      6714: # ---------------------------------------------------------------- Get metadata
                   6715: 
1.599     albertel 6716: my %metaentry;
1.71      www      6717: sub metadata {
1.176     www      6718:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      6719:     $uri=&declutter($uri);
1.288     albertel 6720:     # if it is a non metadata possible uri return quickly
1.529     albertel 6721:     if (($uri eq '') || 
                   6722: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 6723: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.423     albertel 6724:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
1.807     albertel 6725: 	($uri =~ m|home/$match_username/public_html/|)) {
1.468     albertel 6726: 	return undef;
1.288     albertel 6727:     }
1.73      www      6728:     my $filename=$uri;
                   6729:     $uri=~s/\.meta$//;
1.172     www      6730: #
                   6731: # Is the metadata already cached?
1.177     www      6732: # Look at timestamp of caching
1.172     www      6733: # Everything is cached by the main uri, libraries are never directly cached
                   6734: #
1.428     albertel 6735:     if (!defined($liburi)) {
1.599     albertel 6736: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 6737: 	if (defined($cached)) { return $result->{':'.$what}; }
                   6738:     }
                   6739:     {
1.172     www      6740: #
                   6741: # Is this a recursive call for a library?
                   6742: #
1.599     albertel 6743: #	if (! exists($metacache{$uri})) {
                   6744: #	    $metacache{$uri}={};
                   6745: #	}
1.171     www      6746:         if ($liburi) {
                   6747: 	    $liburi=&declutter($liburi);
                   6748:             $filename=$liburi;
1.401     bowersj2 6749:         } else {
1.599     albertel 6750: 	    &devalidate_cache_new('meta',$uri);
                   6751: 	    undef(%metaentry);
1.401     bowersj2 6752: 	}
1.140     www      6753:         my %metathesekeys=();
1.73      www      6754:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 6755: 	my $metastring;
1.768     albertel 6756: 	if ($uri !~ m -^(editupload)/-) {
1.543     albertel 6757: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 6758: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 6759: 	    $metastring=&getfile($file);
1.489     albertel 6760: 	}
1.208     albertel 6761:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      6762:         my $token;
1.140     www      6763:         undef %metathesekeys;
1.71      www      6764:         while ($token=$parser->get_token) {
1.339     albertel 6765: 	    if ($token->[0] eq 'S') {
                   6766: 		if (defined($token->[2]->{'package'})) {
1.172     www      6767: #
                   6768: # This is a package - get package info
                   6769: #
1.339     albertel 6770: 		    my $package=$token->[2]->{'package'};
                   6771: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6772: 		    if (defined($token->[2]->{'id'})) { 
                   6773: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   6774: 		    }
1.599     albertel 6775: 		    if ($metaentry{':packages'}) {
                   6776: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 6777: 		    } else {
1.599     albertel 6778: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 6779: 		    }
1.736     albertel 6780: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 6781: 			my $part=$keyroot;
                   6782: 			$part=~s/^\_//;
1.736     albertel 6783: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   6784: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   6785: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 6786: 			    # ignore package.tab specified default values
                   6787:                             # here &package_tab_default() will fetch those
                   6788: 			    if ($subp eq 'default') { next; }
1.736     albertel 6789: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 6790: 			    my $unikey;
                   6791: 			    if ($pack =~ /_0$/) {
                   6792: 				$unikey='parameter_0_'.$name;
                   6793: 				$part=0;
                   6794: 			    } else {
                   6795: 				$unikey='parameter'.$keyroot.'_'.$name;
                   6796: 			    }
1.339     albertel 6797: 			    if ($subp eq 'display') {
                   6798: 				$value.=' [Part: '.$part.']';
                   6799: 			    }
1.599     albertel 6800: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 6801: 			    $metathesekeys{$unikey}=1;
1.599     albertel 6802: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6803: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 6804: 			    }
1.599     albertel 6805: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   6806: 				$metaentry{':'.$unikey}=
                   6807: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 6808: 			    }
1.339     albertel 6809: 			}
                   6810: 		    }
                   6811: 		} else {
1.172     www      6812: #
                   6813: # This is not a package - some other kind of start tag
1.339     albertel 6814: #
                   6815: 		    my $entry=$token->[1];
                   6816: 		    my $unikey;
                   6817: 		    if ($entry eq 'import') {
                   6818: 			$unikey='';
                   6819: 		    } else {
                   6820: 			$unikey=$entry;
                   6821: 		    }
                   6822: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6823: 
                   6824: 		    if (defined($token->[2]->{'id'})) { 
                   6825: 			$unikey.='_'.$token->[2]->{'id'}; 
                   6826: 		    }
1.175     www      6827: 
1.339     albertel 6828: 		    if ($entry eq 'import') {
1.175     www      6829: #
                   6830: # Importing a library here
1.339     albertel 6831: #
                   6832: 			if ($depthcount<20) {
                   6833: 			    my $location=$parser->get_text('/import');
                   6834: 			    my $dir=$filename;
                   6835: 			    $dir=~s|[^/]*$||;
                   6836: 			    $location=&filelocation($dir,$location);
1.736     albertel 6837: 			    my $metadata = 
                   6838: 				&metadata($uri,'keys', $location,$unikey,
                   6839: 					  $depthcount+1);
                   6840: 			    foreach my $meta (split(',',$metadata)) {
                   6841: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   6842: 				$metathesekeys{$meta}=1;
1.339     albertel 6843: 			    }
                   6844: 			}
                   6845: 		    } else { 
                   6846: 			
                   6847: 			if (defined($token->[2]->{'name'})) { 
                   6848: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   6849: 			}
                   6850: 			$metathesekeys{$unikey}=1;
1.736     albertel 6851: 			foreach my $param (@{$token->[3]}) {
                   6852: 			    $metaentry{':'.$unikey.'.'.$param} =
                   6853: 				$token->[2]->{$param};
1.339     albertel 6854: 			}
                   6855: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 6856: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 6857: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   6858: 		 # only ws inside the tag, and not in default, so use default
                   6859: 		 # as value
1.599     albertel 6860: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 6861: 			} elsif ( $internaltext =~ /\S/ ) {
                   6862: 		  # something interesting inside the tag
                   6863: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 6864: 			} else {
1.908     albertel 6865: 		  # no interesting values, don't set a default
1.339     albertel 6866: 			}
1.172     www      6867: # end of not-a-package not-a-library import
1.339     albertel 6868: 		    }
1.172     www      6869: # end of not-a-package start tag
1.339     albertel 6870: 		}
1.172     www      6871: # the next is the end of "start tag"
1.339     albertel 6872: 	    }
                   6873: 	}
1.483     albertel 6874: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 6875: 	$extension = lc($extension);
                   6876: 	if ($extension eq 'htm') { $extension='html'; }
                   6877: 
1.737     albertel 6878: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 6879: 	    #no specific packages #how's our extension
                   6880: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 6881: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 6882: 					 \%metathesekeys);
                   6883: 	}
1.883     albertel 6884: 
                   6885: 	if (!exists($metaentry{':packages'})
                   6886: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 6887: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 6888: 		#no specific packages well let's get default then
                   6889: 		if ($key!~/^default&/) { next; }
1.488     albertel 6890: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 6891: 					     \%metathesekeys);
                   6892: 	    }
                   6893: 	}
1.338     www      6894: # are there custom rights to evaluate
1.599     albertel 6895: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 6896: 
1.338     www      6897:     #
                   6898:     # Importing a rights file here
1.339     albertel 6899:     #
                   6900: 	    unless ($depthcount) {
1.599     albertel 6901: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 6902: 		my $dir=$filename;
                   6903: 		$dir=~s|[^/]*$||;
                   6904: 		$location=&filelocation($dir,$location);
1.736     albertel 6905: 		my $rights_metadata =
                   6906: 		    &metadata($uri,'keys',$location,'_rights',
                   6907: 			      $depthcount+1);
                   6908: 		foreach my $rights (split(',',$rights_metadata)) {
                   6909: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   6910: 		    $metathesekeys{$rights}=1;
1.339     albertel 6911: 		}
                   6912: 	    }
                   6913: 	}
1.737     albertel 6914: 	# uniqifiy package listing
                   6915: 	my %seen;
                   6916: 	my @uniq_packages =
                   6917: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   6918: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   6919: 
                   6920: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 6921: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   6922: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.699     albertel 6923: 	&do_cache_new('meta',$uri,\%metaentry,60*60);
1.177     www      6924: # this is the end of "was not already recently cached
1.71      www      6925:     }
1.599     albertel 6926:     return $metaentry{':'.$what};
1.261     albertel 6927: }
                   6928: 
1.488     albertel 6929: sub metadata_create_package_def {
1.483     albertel 6930:     my ($uri,$key,$package,$metathesekeys)=@_;
                   6931:     my ($pack,$name,$subp)=split(/\&/,$key);
                   6932:     if ($subp eq 'default') { next; }
                   6933:     
1.599     albertel 6934:     if (defined($metaentry{':packages'})) {
                   6935: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 6936:     } else {
1.599     albertel 6937: 	$metaentry{':packages'}=$package;
1.483     albertel 6938:     }
                   6939:     my $value=$packagetab{$key};
                   6940:     my $unikey;
                   6941:     $unikey='parameter_0_'.$name;
1.599     albertel 6942:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 6943:     $$metathesekeys{$unikey}=1;
1.599     albertel 6944:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6945: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 6946:     }
1.599     albertel 6947:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   6948: 	$metaentry{':'.$unikey}=
                   6949: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 6950:     }
                   6951: }
                   6952: 
1.261     albertel 6953: sub metadata_generate_part0 {
                   6954:     my ($metadata,$metacache,$uri) = @_;
                   6955:     my %allnames;
1.737     albertel 6956:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 6957: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 6958: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   6959: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 6960: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 6961: 	    $allnames{$name}=$part;
                   6962: 	  }
                   6963: 	}
                   6964:     }
                   6965:     foreach my $name (keys(%allnames)) {
                   6966:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 6967:       my $key=":parameter_0_$name";
1.261     albertel 6968:       $$metacache{"$key.part"}='0';
                   6969:       $$metacache{"$key.name"}=$name;
1.428     albertel 6970:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 6971: 					   $allnames{$name}.'_'.$name.
                   6972: 					   '.type'};
1.428     albertel 6973:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 6974: 			     '.display'};
1.644     www      6975:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 6976:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 6977:       $$metacache{"$key.display"}=$olddis;
                   6978:     }
1.71      www      6979: }
                   6980: 
1.764     albertel 6981: # ------------------------------------------------------ Devalidate title cache
                   6982: 
                   6983: sub devalidate_title_cache {
                   6984:     my ($url)=@_;
                   6985:     if (!$env{'request.course.id'}) { return; }
                   6986:     my $symb=&symbread($url);
                   6987:     if (!$symb) { return; }
                   6988:     my $key=$env{'request.course.id'}."\0".$symb;
                   6989:     &devalidate_cache_new('title',$key);
                   6990: }
                   6991: 
1.301     www      6992: # ------------------------------------------------- Get the title of a resource
                   6993: 
                   6994: sub gettitle {
                   6995:     my $urlsymb=shift;
                   6996:     my $symb=&symbread($urlsymb);
1.534     albertel 6997:     if ($symb) {
1.620     albertel 6998: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 6999: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 7000: 	if (defined($cached)) { 
                   7001: 	    return $result;
                   7002: 	}
1.534     albertel 7003: 	my ($map,$resid,$url)=&decode_symb($symb);
                   7004: 	my $title='';
1.907     albertel 7005: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   7006: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   7007: 	} else {
                   7008: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   7009: 		    &GDBM_READER(),0640)) {
                   7010: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   7011: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   7012: 		untie(%bighash);
                   7013: 	    }
1.534     albertel 7014: 	}
                   7015: 	$title=~s/\&colon\;/\:/gs;
                   7016: 	if ($title) {
1.599     albertel 7017: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 7018: 	}
                   7019: 	$urlsymb=$url;
                   7020:     }
                   7021:     my $title=&metadata($urlsymb,'title');
                   7022:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   7023:     return $title;
1.301     www      7024: }
1.613     albertel 7025: 
1.614     albertel 7026: sub get_slot {
                   7027:     my ($which,$cnum,$cdom)=@_;
                   7028:     if (!$cnum || !$cdom) {
1.790     albertel 7029: 	(undef,my $courseid)=&whichuser();
1.620     albertel 7030: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   7031: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 7032:     }
1.703     albertel 7033:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   7034:     my %slotinfo;
                   7035:     if (exists($remembered{$key})) {
                   7036: 	$slotinfo{$which} = $remembered{$key};
                   7037:     } else {
                   7038: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   7039: 	&Apache::lonhomework::showhash(%slotinfo);
                   7040: 	my ($tmp)=keys(%slotinfo);
                   7041: 	if ($tmp=~/^error:/) { return (); }
                   7042: 	$remembered{$key} = $slotinfo{$which};
                   7043:     }
1.616     albertel 7044:     if (ref($slotinfo{$which}) eq 'HASH') {
                   7045: 	return %{$slotinfo{$which}};
                   7046:     }
                   7047:     return $slotinfo{$which};
1.614     albertel 7048: }
1.31      www      7049: # ------------------------------------------------- Update symbolic store links
                   7050: 
                   7051: sub symblist {
                   7052:     my ($mapname,%newhash)=@_;
1.438     www      7053:     $mapname=&deversion(&declutter($mapname));
1.31      www      7054:     my %hash;
1.620     albertel 7055:     if (($env{'request.course.fn'}) && (%newhash)) {
                   7056:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 7057:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 7058: 	    foreach my $url (keys %newhash) {
                   7059: 		next if ($url eq 'last_known'
                   7060: 			 && $env{'form.no_update_last_known'});
                   7061: 		$hash{declutter($url)}=&encode_symb($mapname,
                   7062: 						    $newhash{$url}->[1],
                   7063: 						    $newhash{$url}->[0]);
1.191     harris41 7064:             }
1.31      www      7065:             if (untie(%hash)) {
                   7066: 		return 'ok';
                   7067:             }
                   7068:         }
                   7069:     }
                   7070:     return 'error';
1.212     www      7071: }
                   7072: 
                   7073: # --------------------------------------------------------------- Verify a symb
                   7074: 
                   7075: sub symbverify {
1.510     www      7076:     my ($symb,$thisurl)=@_;
                   7077:     my $thisfn=$thisurl;
1.439     www      7078:     $thisfn=&declutter($thisfn);
1.215     www      7079: # direct jump to resource in page or to a sequence - will construct own symbs
                   7080:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   7081: # check URL part
1.409     www      7082:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      7083: 
1.431     www      7084:     unless ($url eq $thisfn) { return 0; }
1.213     www      7085: 
1.216     www      7086:     $symb=&symbclean($symb);
1.510     www      7087:     $thisurl=&deversion($thisurl);
1.439     www      7088:     $thisfn=&deversion($thisfn);
1.213     www      7089: 
                   7090:     my %bighash;
                   7091:     my $okay=0;
1.431     www      7092: 
1.620     albertel 7093:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 7094:                             &GDBM_READER(),0640)) {
1.510     www      7095:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      7096:         unless ($ids) { 
1.510     www      7097:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      7098:         }
                   7099:         if ($ids) {
                   7100: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 7101: 	    foreach my $id (split(/\,/,$ids)) {
                   7102: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      7103:                if (
                   7104:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   7105:    eq $symb) { 
1.620     albertel 7106: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 7107: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 7108: 		       $okay=1; 
                   7109: 		   }
                   7110: 	       }
1.216     www      7111: 	   }
                   7112:         }
1.213     www      7113: 	untie(%bighash);
                   7114:     }
                   7115:     return $okay;
1.31      www      7116: }
                   7117: 
1.210     www      7118: # --------------------------------------------------------------- Clean-up symb
                   7119: 
                   7120: sub symbclean {
                   7121:     my $symb=shift;
1.568     albertel 7122:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      7123: # remove version from map
                   7124:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      7125: 
1.210     www      7126: # remove version from URL
                   7127:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      7128: 
1.507     www      7129: # remove wrapper
                   7130: 
1.510     www      7131:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 7132:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      7133:     return $symb;
1.409     www      7134: }
                   7135: 
                   7136: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 7137: 
                   7138: sub encode_symb {
                   7139:     my ($map,$resid,$url)=@_;
                   7140:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   7141: }
1.409     www      7142: 
                   7143: sub decode_symb {
1.568     albertel 7144:     my $symb=shift;
                   7145:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   7146:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      7147:     return (&fixversion($map),$resid,&fixversion($url));
                   7148: }
                   7149: 
                   7150: sub fixversion {
                   7151:     my $fn=shift;
1.609     banghart 7152:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      7153:     my %bighash;
                   7154:     my $uri=&clutter($fn);
1.620     albertel 7155:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      7156: # is this cached?
1.599     albertel 7157:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      7158:     if (defined($cached)) { return $result; }
                   7159: # unfortunately not cached, or expired
1.620     albertel 7160:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      7161: 	    &GDBM_READER(),0640)) {
                   7162:  	if ($bighash{'version_'.$uri}) {
                   7163:  	    my $version=$bighash{'version_'.$uri};
1.444     www      7164:  	    unless (($version eq 'mostrecent') || 
                   7165: 		    ($version==&getversion($uri))) {
1.440     www      7166:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   7167:  	    }
                   7168:  	}
                   7169:  	untie %bighash;
1.413     www      7170:     }
1.599     albertel 7171:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      7172: }
                   7173: 
                   7174: sub deversion {
                   7175:     my $url=shift;
                   7176:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   7177:     return $url;
1.210     www      7178: }
                   7179: 
1.31      www      7180: # ------------------------------------------------------ Return symb list entry
                   7181: 
                   7182: sub symbread {
1.249     www      7183:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 7184:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 7185:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      7186: # no filename provided? try from environment
1.44      www      7187:     unless ($thisfn) {
1.620     albertel 7188:         if ($env{'request.symb'}) {
                   7189: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 7190: 	}
1.620     albertel 7191: 	$thisfn=$env{'request.filename'};
1.44      www      7192:     }
1.569     albertel 7193:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      7194: # is that filename actually a symb? Verify, clean, and return
                   7195:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 7196: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 7197: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 7198: 	}
1.242     www      7199:     }
1.44      www      7200:     $thisfn=declutter($thisfn);
1.31      www      7201:     my %hash;
1.37      www      7202:     my %bighash;
                   7203:     my $syval='';
1.620     albertel 7204:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  7205:         my $targetfn = $thisfn;
1.609     banghart 7206:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  7207:             $targetfn = 'adm/wrapper/'.$thisfn;
                   7208:         }
1.687     albertel 7209: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   7210: 	    $targetfn=$1;
                   7211: 	}
1.620     albertel 7212:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 7213:                       &GDBM_READER(),0640)) {
1.481     raeburn  7214: 	    $syval=$hash{$targetfn};
1.37      www      7215:             untie(%hash);
                   7216:         }
                   7217: # ---------------------------------------------------------- There was an entry
                   7218:         if ($syval) {
1.601     albertel 7219: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 7220: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.601     albertel 7221: 		    #&appenv('request.ambiguous' => $thisfn);
1.620     albertel 7222: 		    #return $env{$cache_str}='';
1.601     albertel 7223: 		#}    
                   7224: 		#$syval.=$1;
                   7225: 	    #}
1.37      www      7226:         } else {
                   7227: # ------------------------------------------------------- Was not in symb table
1.620     albertel 7228:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 7229:                             &GDBM_READER(),0640)) {
1.37      www      7230: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      7231:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      7232:               unless ($ids) { 
                   7233:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      7234:               }
                   7235:               unless ($ids) {
                   7236: # alias?
                   7237: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      7238:               }
1.37      www      7239:               if ($ids) {
                   7240: # ------------------------------------------------------------------- Has ID(s)
                   7241:                  my @possibilities=split(/\,/,$ids);
1.39      www      7242:                  if ($#possibilities==0) {
                   7243: # ----------------------------------------------- There is only one possibility
1.37      www      7244: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 7245: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   7246: 						    $resid,$thisfn);
1.249     www      7247:                  } elsif (!$donotrecurse) {
1.39      www      7248: # ------------------------------------------ There is more than one possibility
                   7249:                      my $realpossible=0;
1.800     albertel 7250:                      foreach my $id (@possibilities) {
                   7251: 			 my $file=$bighash{'src_'.$id};
1.39      www      7252:                          if (&allowed('bre',$file)) {
1.800     albertel 7253:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      7254:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   7255: 				$realpossible++;
1.626     albertel 7256:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   7257: 						    $resid,$thisfn);
1.39      www      7258:                             }
                   7259: 			 }
1.191     harris41 7260:                      }
1.39      www      7261: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      7262:                  } else {
                   7263:                      $syval='';
1.37      www      7264:                  }
                   7265: 	      }
                   7266:               untie(%bighash)
1.481     raeburn  7267:            }
1.31      www      7268:         }
1.62      www      7269:         if ($syval) {
1.620     albertel 7270: 	    return $env{$cache_str}=$syval;
1.62      www      7271:         }
1.31      www      7272:     }
1.44      www      7273:     &appenv('request.ambiguous' => $thisfn);
1.620     albertel 7274:     return $env{$cache_str}='';
1.31      www      7275: }
                   7276: 
                   7277: # ---------------------------------------------------------- Return random seed
                   7278: 
1.32      www      7279: sub numval {
                   7280:     my $txt=shift;
                   7281:     $txt=~tr/A-J/0-9/;
                   7282:     $txt=~tr/a-j/0-9/;
                   7283:     $txt=~tr/K-T/0-9/;
                   7284:     $txt=~tr/k-t/0-9/;
                   7285:     $txt=~tr/U-Z/0-5/;
                   7286:     $txt=~tr/u-z/0-5/;
                   7287:     $txt=~s/\D//g;
1.564     albertel 7288:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      7289:     return int($txt);
1.368     albertel 7290: }
                   7291: 
1.484     albertel 7292: sub numval2 {
                   7293:     my $txt=shift;
                   7294:     $txt=~tr/A-J/0-9/;
                   7295:     $txt=~tr/a-j/0-9/;
                   7296:     $txt=~tr/K-T/0-9/;
                   7297:     $txt=~tr/k-t/0-9/;
                   7298:     $txt=~tr/U-Z/0-5/;
                   7299:     $txt=~tr/u-z/0-5/;
                   7300:     $txt=~s/\D//g;
                   7301:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7302:     my $total;
                   7303:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 7304:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 7305:     return int($total);
                   7306: }
                   7307: 
1.575     albertel 7308: sub numval3 {
                   7309:     use integer;
                   7310:     my $txt=shift;
                   7311:     $txt=~tr/A-J/0-9/;
                   7312:     $txt=~tr/a-j/0-9/;
                   7313:     $txt=~tr/K-T/0-9/;
                   7314:     $txt=~tr/k-t/0-9/;
                   7315:     $txt=~tr/U-Z/0-5/;
                   7316:     $txt=~tr/u-z/0-5/;
                   7317:     $txt=~s/\D//g;
                   7318:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7319:     my $total;
                   7320:     foreach my $val (@txts) { $total+=$val; }
                   7321:     if ($_64bit) { $total=(($total<<32)>>32); }
                   7322:     return $total;
                   7323: }
                   7324: 
1.675     albertel 7325: sub digest {
                   7326:     my ($data)=@_;
                   7327:     my $digest=&Digest::MD5::md5($data);
                   7328:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   7329:     my ($e,$f);
                   7330:     {
                   7331:         use integer;
                   7332:         $e=($a+$b);
                   7333:         $f=($c+$d);
                   7334:         if ($_64bit) {
                   7335:             $e=(($e<<32)>>32);
                   7336:             $f=(($f<<32)>>32);
                   7337:         }
                   7338:     }
                   7339:     if (wantarray) {
                   7340: 	return ($e,$f);
                   7341:     } else {
                   7342: 	my $g;
                   7343: 	{
                   7344: 	    use integer;
                   7345: 	    $g=($e+$f);
                   7346: 	    if ($_64bit) {
                   7347: 		$g=(($g<<32)>>32);
                   7348: 	    }
                   7349: 	}
                   7350: 	return $g;
                   7351:     }
                   7352: }
                   7353: 
1.368     albertel 7354: sub latest_rnd_algorithm_id {
1.675     albertel 7355:     return '64bit5';
1.366     albertel 7356: }
1.32      www      7357: 
1.503     albertel 7358: sub get_rand_alg {
                   7359:     my ($courseid)=@_;
1.790     albertel 7360:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 7361:     if ($courseid) {
1.620     albertel 7362: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 7363:     }
                   7364:     return &latest_rnd_algorithm_id();
                   7365: }
                   7366: 
1.562     albertel 7367: sub validCODE {
                   7368:     my ($CODE)=@_;
                   7369:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   7370:     return 0;
                   7371: }
                   7372: 
1.491     albertel 7373: sub getCODE {
1.620     albertel 7374:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 7375:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   7376: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   7377: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 7378: 	return $Apache::lonhomework::history{'resource.CODE'};
                   7379:     }
                   7380:     return undef;
                   7381: }
                   7382: 
1.31      www      7383: sub rndseed {
1.155     albertel 7384:     my ($symb,$courseid,$domain,$username)=@_;
1.790     albertel 7385:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 7386:     if (!defined($symb)) {
1.366     albertel 7387: 	unless ($symb=$wsymb) { return time; }
                   7388:     }
                   7389:     if (!$courseid) { $courseid=$wcourseid; }
                   7390:     if (!$domain) { $domain=$wdomain; }
                   7391:     if (!$username) { $username=$wusername }
1.503     albertel 7392:     my $which=&get_rand_alg();
1.803     albertel 7393: 
1.491     albertel 7394:     if (defined(&getCODE())) {
1.675     albertel 7395: 	if ($which eq '64bit5') {
                   7396: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   7397: 	} elsif ($which eq '64bit4') {
1.575     albertel 7398: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   7399: 	} else {
                   7400: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   7401: 	}
1.675     albertel 7402:     } elsif ($which eq '64bit5') {
                   7403: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 7404:     } elsif ($which eq '64bit4') {
                   7405: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 7406:     } elsif ($which eq '64bit3') {
                   7407: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 7408:     } elsif ($which eq '64bit2') {
                   7409: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 7410:     } elsif ($which eq '64bit') {
                   7411: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   7412:     }
                   7413:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   7414: }
                   7415: 
                   7416: sub rndseed_32bit {
                   7417:     my ($symb,$courseid,$domain,$username)=@_;
                   7418:     {
                   7419: 	use integer;
                   7420: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   7421: 	my $symbseed=numval($symb) << 22;
                   7422: 	my $namechck=unpack("%32C*",$username) << 17;
                   7423: 	my $nameseed=numval($username) << 12;
                   7424: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   7425: 	my $courseseed=unpack("%32C*",$courseid);
                   7426: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 7427: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7428: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 7429: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 7430: 	return $num;
                   7431:     }
                   7432: }
                   7433: 
                   7434: sub rndseed_64bit {
                   7435:     my ($symb,$courseid,$domain,$username)=@_;
                   7436:     {
                   7437: 	use integer;
                   7438: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   7439: 	my $symbseed=numval($symb) << 10;
                   7440: 	my $namechck=unpack("%32S*",$username);
                   7441: 	
                   7442: 	my $nameseed=numval($username) << 21;
                   7443: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   7444: 	my $courseseed=unpack("%32S*",$courseid);
                   7445: 	
                   7446: 	my $num1=$symbchck+$symbseed+$namechck;
                   7447: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7448: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7449: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 7450: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 7451: 	return "$num1,$num2";
1.155     albertel 7452:     }
1.366     albertel 7453: }
                   7454: 
1.443     albertel 7455: sub rndseed_64bit2 {
                   7456:     my ($symb,$courseid,$domain,$username)=@_;
                   7457:     {
                   7458: 	use integer;
                   7459: 	# strings need to be an even # of cahracters long, it it is odd the
                   7460:         # last characters gets thrown away
                   7461: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7462: 	my $symbseed=numval($symb) << 10;
                   7463: 	my $namechck=unpack("%32S*",$username.' ');
                   7464: 	
                   7465: 	my $nameseed=numval($username) << 21;
1.501     albertel 7466: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7467: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7468: 	
                   7469: 	my $num1=$symbchck+$symbseed+$namechck;
                   7470: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7471: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7472: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 7473: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 7474: 	return "$num1,$num2";
                   7475:     }
                   7476: }
                   7477: 
                   7478: sub rndseed_64bit3 {
                   7479:     my ($symb,$courseid,$domain,$username)=@_;
                   7480:     {
                   7481: 	use integer;
                   7482: 	# strings need to be an even # of cahracters long, it it is odd the
                   7483:         # last characters gets thrown away
                   7484: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7485: 	my $symbseed=numval2($symb) << 10;
                   7486: 	my $namechck=unpack("%32S*",$username.' ');
                   7487: 	
                   7488: 	my $nameseed=numval2($username) << 21;
1.443     albertel 7489: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7490: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7491: 	
                   7492: 	my $num1=$symbchck+$symbseed+$namechck;
                   7493: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7494: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7495: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 7496: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   7497: 	
1.503     albertel 7498: 	return "$num1:$num2";
1.443     albertel 7499:     }
                   7500: }
                   7501: 
1.575     albertel 7502: sub rndseed_64bit4 {
                   7503:     my ($symb,$courseid,$domain,$username)=@_;
                   7504:     {
                   7505: 	use integer;
                   7506: 	# strings need to be an even # of cahracters long, it it is odd the
                   7507:         # last characters gets thrown away
                   7508: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7509: 	my $symbseed=numval3($symb) << 10;
                   7510: 	my $namechck=unpack("%32S*",$username.' ');
                   7511: 	
                   7512: 	my $nameseed=numval3($username) << 21;
                   7513: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7514: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7515: 	
                   7516: 	my $num1=$symbchck+$symbseed+$namechck;
                   7517: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7518: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7519: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 7520: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   7521: 	
                   7522: 	return "$num1:$num2";
                   7523:     }
                   7524: }
                   7525: 
1.675     albertel 7526: sub rndseed_64bit5 {
                   7527:     my ($symb,$courseid,$domain,$username)=@_;
                   7528:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   7529:     return "$num1:$num2";
                   7530: }
                   7531: 
1.366     albertel 7532: sub rndseed_CODE_64bit {
                   7533:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 7534:     {
1.366     albertel 7535: 	use integer;
1.443     albertel 7536: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 7537: 	my $symbseed=numval2($symb);
1.491     albertel 7538: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   7539: 	my $CODEseed=numval(&getCODE());
1.443     albertel 7540: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 7541: 	my $num1=$symbseed+$CODEchck;
                   7542: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 7543: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   7544: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 7545: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   7546: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 7547: 	return "$num1:$num2";
1.366     albertel 7548:     }
                   7549: }
                   7550: 
1.575     albertel 7551: sub rndseed_CODE_64bit4 {
                   7552:     my ($symb,$courseid,$domain,$username)=@_;
                   7553:     {
                   7554: 	use integer;
                   7555: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   7556: 	my $symbseed=numval3($symb);
                   7557: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   7558: 	my $CODEseed=numval3(&getCODE());
                   7559: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7560: 	my $num1=$symbseed+$CODEchck;
                   7561: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 7562: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   7563: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 7564: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   7565: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   7566: 	return "$num1:$num2";
                   7567:     }
                   7568: }
                   7569: 
1.675     albertel 7570: sub rndseed_CODE_64bit5 {
                   7571:     my ($symb,$courseid,$domain,$username)=@_;
                   7572:     my $code = &getCODE();
                   7573:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   7574:     return "$num1:$num2";
                   7575: }
                   7576: 
1.366     albertel 7577: sub setup_random_from_rndseed {
                   7578:     my ($rndseed)=@_;
1.503     albertel 7579:     if ($rndseed =~/([,:])/) {
                   7580: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 7581: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   7582:     } else {
                   7583: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 7584:     }
1.36      albertel 7585: }
                   7586: 
1.474     albertel 7587: sub latest_receipt_algorithm_id {
1.835     albertel 7588:     return 'receipt3';
1.474     albertel 7589: }
                   7590: 
1.480     www      7591: sub recunique {
                   7592:     my $fucourseid=shift;
                   7593:     my $unique;
1.835     albertel 7594:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   7595: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 7596: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      7597:     } else {
                   7598: 	$unique=$perlvar{'lonReceipt'};
                   7599:     }
                   7600:     return unpack("%32C*",$unique);
                   7601: }
                   7602: 
                   7603: sub recprefix {
                   7604:     my $fucourseid=shift;
                   7605:     my $prefix;
1.835     albertel 7606:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   7607: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 7608: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      7609:     } else {
                   7610: 	$prefix=$perlvar{'lonHostID'};
                   7611:     }
                   7612:     return unpack("%32C*",$prefix);
                   7613: }
                   7614: 
1.76      www      7615: sub ireceipt {
1.474     albertel 7616:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 7617: 
                   7618:     my $return =&recprefix($fucourseid).'-';
                   7619: 
                   7620:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   7621: 	$env{'request.state'} eq 'construct') {
                   7622: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   7623: 	return $return;
                   7624:     }
                   7625: 
1.76      www      7626:     my $cuname=unpack("%32C*",$funame);
                   7627:     my $cudom=unpack("%32C*",$fudom);
                   7628:     my $cucourseid=unpack("%32C*",$fucourseid);
                   7629:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      7630:     my $cunique=&recunique($fucourseid);
1.474     albertel 7631:     my $cpart=unpack("%32S*",$part);
1.835     albertel 7632:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   7633: 
1.790     albertel 7634: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 7635: 			       
                   7636: 	$return.= ($cunique%$cuname+
                   7637: 		   $cunique%$cudom+
                   7638: 		   $cusymb%$cuname+
                   7639: 		   $cusymb%$cudom+
                   7640: 		   $cucourseid%$cuname+
                   7641: 		   $cucourseid%$cudom+
                   7642: 		   $cpart%$cuname+
                   7643: 		   $cpart%$cudom);
                   7644:     } else {
                   7645: 	$return.= ($cunique%$cuname+
                   7646: 		   $cunique%$cudom+
                   7647: 		   $cusymb%$cuname+
                   7648: 		   $cusymb%$cudom+
                   7649: 		   $cucourseid%$cuname+
                   7650: 		   $cucourseid%$cudom);
                   7651:     }
                   7652:     return $return;
1.76      www      7653: }
                   7654: 
                   7655: sub receipt {
1.474     albertel 7656:     my ($part)=@_;
1.790     albertel 7657:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 7658:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      7659: }
1.260     ng       7660: 
1.790     albertel 7661: sub whichuser {
                   7662:     my ($passedsymb)=@_;
                   7663:     my ($symb,$courseid,$domain,$name,$publicuser);
                   7664:     if (defined($env{'form.grade_symb'})) {
                   7665: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   7666: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   7667: 	if (!$allowed &&
                   7668: 	    exists($env{'request.course.sec'}) &&
                   7669: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   7670: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   7671: 			      '/'.$env{'request.course.sec'});
                   7672: 	}
                   7673: 	if ($allowed) {
                   7674: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   7675: 	    $courseid=$tmp_courseid;
                   7676: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   7677: 	    ($name)=&get_env_multiple('form.grade_username');
                   7678: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   7679: 	}
                   7680:     }
                   7681:     if (!$passedsymb) {
                   7682: 	$symb=&symbread();
                   7683:     } else {
                   7684: 	$symb=$passedsymb;
                   7685:     }
                   7686:     $courseid=$env{'request.course.id'};
                   7687:     $domain=$env{'user.domain'};
                   7688:     $name=$env{'user.name'};
                   7689:     if ($name eq 'public' && $domain eq 'public') {
                   7690: 	if (!defined($env{'form.username'})) {
                   7691: 	    $env{'form.username'}.=time.rand(10000000);
                   7692: 	}
                   7693: 	$name.=$env{'form.username'};
                   7694:     }
                   7695:     return ($symb,$courseid,$domain,$name,$publicuser);
                   7696: 
                   7697: }
                   7698: 
1.36      albertel 7699: # ------------------------------------------------------------ Serves up a file
1.472     albertel 7700: # returns either the contents of the file or 
                   7701: # -1 if the file doesn't exist
1.481     raeburn  7702: #
                   7703: # if the target is a file that was uploaded via DOCS, 
                   7704: # a check will be made to see if a current copy exists on the local server,
                   7705: # if it does this will be served, otherwise a copy will be retrieved from
                   7706: # the home server for the course and stored in /home/httpd/html/userfiles on
                   7707: # the local server.   
1.472     albertel 7708: 
1.36      albertel 7709: sub getfile {
1.538     albertel 7710:     my ($file) = @_;
1.609     banghart 7711:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 7712:     &repcopy($file);
                   7713:     return &readfile($file);
                   7714: }
                   7715: 
                   7716: sub repcopy_userfile {
                   7717:     my ($file)=@_;
1.609     banghart 7718:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 7719:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 7720:     my ($cdom,$cnum,$filename) = 
1.811     albertel 7721: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 7722:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   7723:     if (-e "$file") {
1.828     www      7724: # we already have a local copy, check it out
1.538     albertel 7725: 	my @fileinfo = stat($file);
1.828     www      7726: 	my $rtncode;
                   7727: 	my $info;
1.538     albertel 7728: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 7729: 	if ($lwpresp ne 'ok') {
1.828     www      7730: # there is no such file anymore, even though we had a local copy
1.482     albertel 7731: 	    if ($rtncode eq '404') {
1.538     albertel 7732: 		unlink($file);
1.482     albertel 7733: 	    }
                   7734: 	    return -1;
                   7735: 	}
                   7736: 	if ($info < $fileinfo[9]) {
1.828     www      7737: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  7738: 	    return 'ok';
1.828     www      7739: 	} else {
                   7740: # the file is outdated, get rid of it
                   7741: 	    unlink($file);
1.482     albertel 7742: 	}
1.828     www      7743:     }
                   7744: # one way or the other, at this point, we don't have the file
                   7745: # construct the correct path for the file
                   7746:     my @parts = ($cdom,$cnum); 
                   7747:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   7748: 	push @parts, split(/\//,$1);
                   7749:     }
                   7750:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   7751:     foreach my $part (@parts) {
                   7752: 	$path .= '/'.$part;
                   7753: 	if (!-e $path) {
                   7754: 	    mkdir($path,0770);
1.482     albertel 7755: 	}
                   7756:     }
1.828     www      7757: # now the path exists for sure
                   7758: # get a user agent
                   7759:     my $ua=new LWP::UserAgent;
                   7760:     my $transferfile=$file.'.in.transfer';
                   7761: # FIXME: this should flock
                   7762:     if (-e $transferfile) { return 'ok'; }
                   7763:     my $request;
                   7764:     $uri=~s/^\///;
1.838     albertel 7765:     $request=new HTTP::Request('GET','http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri);
1.828     www      7766:     my $response=$ua->request($request,$transferfile);
                   7767: # did it work?
                   7768:     if ($response->is_error()) {
                   7769: 	unlink($transferfile);
                   7770: 	&logthis("Userfile repcopy failed for $uri");
                   7771: 	return -1;
                   7772:     }
                   7773: # worked, rename the transfer file
                   7774:     rename($transferfile,$file);
1.607     raeburn  7775:     return 'ok';
1.481     raeburn  7776: }
                   7777: 
1.517     albertel 7778: sub tokenwrapper {
                   7779:     my $uri=shift;
1.552     albertel 7780:     $uri=~s|^http\://([^/]+)||;
                   7781:     $uri=~s|^/||;
1.620     albertel 7782:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 7783:     my $token=$1;
1.552     albertel 7784:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   7785:     if ($udom && $uname && $file) {
                   7786: 	$file=~s|(\?\.*)*$||;
1.620     albertel 7787:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
1.838     albertel 7788:         return 'http://'.&hostname(&homeserver($uname,$udom)).'/'.$uri.
1.517     albertel 7789:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   7790:                                '&tokenissued='.$perlvar{'lonHostID'};
                   7791:     } else {
                   7792:         return '/adm/notfound.html';
                   7793:     }
                   7794: }
                   7795: 
1.828     www      7796: # call with reqtype HEAD: get last modification time
                   7797: # call with reqtype GET: get the file contents
                   7798: # Do not call this with reqtype GET for large files! It loads everything into memory
                   7799: #
1.481     raeburn  7800: sub getuploaded {
                   7801:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   7802:     $uri=~s/^\///;
1.838     albertel 7803:     $uri = 'http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri;
1.481     raeburn  7804:     my $ua=new LWP::UserAgent;
                   7805:     my $request=new HTTP::Request($reqtype,$uri);
                   7806:     my $response=$ua->request($request);
                   7807:     $$rtncode = $response->code;
1.482     albertel 7808:     if (! $response->is_success()) {
                   7809: 	return 'failed';
                   7810:     }      
                   7811:     if ($reqtype eq 'HEAD') {
1.486     www      7812: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 7813:     } elsif ($reqtype eq 'GET') {
                   7814: 	$$info = $response->content;
1.472     albertel 7815:     }
1.482     albertel 7816:     return 'ok';
1.36      albertel 7817: }
                   7818: 
1.481     raeburn  7819: sub readfile {
                   7820:     my $file = shift;
                   7821:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   7822:     my $fh;
                   7823:     open($fh,"<$file");
                   7824:     my $a='';
1.800     albertel 7825:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  7826:     return $a;
                   7827: }
                   7828: 
1.36      albertel 7829: sub filelocation {
1.590     banghart 7830:     my ($dir,$file) = @_;
                   7831:     my $location;
                   7832:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 7833: 
                   7834:     if ($file =~ m-^/adm/-) {
                   7835: 	$file=~s-^/adm/wrapper/-/-;
                   7836: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   7837:     }
1.882     albertel 7838: 
1.590     banghart 7839:     if ($file=~m:^/~:) { # is a contruction space reference
                   7840:         $location = $file;
                   7841:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 7842:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 7843: 	# is a correct contruction space reference
                   7844:         $location = $file;
1.609     banghart 7845:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 7846:         my ($udom,$uname,$filename)=
1.811     albertel 7847:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 7848:         my $home=&homeserver($uname,$udom);
                   7849:         my $is_me=0;
                   7850:         my @ids=&current_machine_ids();
                   7851:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   7852:         if ($is_me) {
1.740     www      7853:   	    $location=&propath($udom,$uname).
1.590     banghart 7854:   	      '/userfiles/'.$filename;
                   7855:         } else {
                   7856:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   7857:   	      $udom.'/'.$uname.'/'.$filename;
                   7858:         }
1.882     albertel 7859:     } elsif ($file =~ m-^/adm/-) {
                   7860: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 7861:     } else {
                   7862:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   7863:         $file=~s:^/res/:/:;
                   7864:         if ( !( $file =~ m:^/:) ) {
                   7865:             $location = $dir. '/'.$file;
                   7866:         } else {
                   7867:             $location = '/home/httpd/html/res'.$file;
                   7868:         }
1.59      albertel 7869:     }
1.590     banghart 7870:     $location=~s://+:/:g; # remove duplicate /
                   7871:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
                   7872:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   7873:     return $location;
1.46      www      7874: }
1.36      albertel 7875: 
1.46      www      7876: sub hreflocation {
                   7877:     my ($dir,$file)=@_;
1.460     albertel 7878:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666     albertel 7879: 	$file=filelocation($dir,$file);
1.700     albertel 7880:     } elsif ($file=~m-^/adm/-) {
                   7881: 	$file=~s-^/adm/wrapper/-/-;
                   7882: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 7883:     }
                   7884:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   7885: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 7886:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   7887: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 7888:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 7889: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 7890: 	    -/uploaded/$1/$2/-x;
1.46      www      7891:     }
1.913     albertel 7892:     if ($file=~ m{^/userfiles/}) {
                   7893: 	$file =~ s{^/userfiles/}{/uploaded/};
                   7894:     }
1.462     albertel 7895:     return $file;
1.465     albertel 7896: }
                   7897: 
                   7898: sub current_machine_domains {
1.853     albertel 7899:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   7900: }
                   7901: 
                   7902: sub machine_domains {
                   7903:     my ($hostname) = @_;
1.465     albertel 7904:     my @domains;
1.838     albertel 7905:     my %hostname = &all_hostnames();
1.465     albertel 7906:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  7907: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 7908: 	if ($hostname eq $name) {
1.844     albertel 7909: 	    push(@domains,&host_domain($id));
1.465     albertel 7910: 	}
                   7911:     }
                   7912:     return @domains;
                   7913: }
                   7914: 
                   7915: sub current_machine_ids {
1.853     albertel 7916:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   7917: }
                   7918: 
                   7919: sub machine_ids {
                   7920:     my ($hostname) = @_;
                   7921:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 7922:     my @ids;
1.888     albertel 7923:     my %name_to_host = &all_names();
1.889     albertel 7924:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   7925: 	return @{ $name_to_host{$hostname} };
                   7926:     }
                   7927:     return;
1.31      www      7928: }
                   7929: 
1.824     raeburn  7930: sub additional_machine_domains {
                   7931:     my @domains;
                   7932:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   7933:     while( my $line = <$fh>) {
                   7934:         $line =~ s/\s//g;
                   7935:         push(@domains,$line);
                   7936:     }
                   7937:     return @domains;
                   7938: }
                   7939: 
                   7940: sub default_login_domain {
                   7941:     my $domain = $perlvar{'lonDefDomain'};
                   7942:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   7943:     foreach my $posdom (&current_machine_domains(),
                   7944:                         &additional_machine_domains()) {
                   7945:         if (lc($posdom) eq lc($testdomain)) {
                   7946:             $domain=$posdom;
                   7947:             last;
                   7948:         }
                   7949:     }
                   7950:     return $domain;
                   7951: }
                   7952: 
1.31      www      7953: # ------------------------------------------------------------- Declutters URLs
                   7954: 
                   7955: sub declutter {
                   7956:     my $thisfn=shift;
1.569     albertel 7957:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 7958:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      7959:     $thisfn=~s/^\///;
1.697     albertel 7960:     $thisfn=~s|^adm/wrapper/||;
                   7961:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      7962:     $thisfn=~s/^res\///;
1.235     www      7963:     $thisfn=~s/\?.+$//;
1.268     www      7964:     return $thisfn;
                   7965: }
                   7966: 
                   7967: # ------------------------------------------------------------- Clutter up URLs
                   7968: 
                   7969: sub clutter {
                   7970:     my $thisfn='/'.&declutter(shift);
1.887     albertel 7971:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 7972: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      7973:        $thisfn='/res'.$thisfn; 
                   7974:     }
1.694     albertel 7975:     if ($thisfn !~m|/adm|) {
1.695     albertel 7976: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 7977: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 7978: 	} else {
                   7979: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   7980: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 7981: 	    if ($embstyle eq 'ssi'
                   7982: 		|| ($embstyle eq 'hdn')
                   7983: 		|| ($embstyle eq 'rat')
                   7984: 		|| ($embstyle eq 'prv')
                   7985: 		|| ($embstyle eq 'ign')) {
                   7986: 		#do nothing with these
                   7987: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 7988: 		|| ($embstyle eq 'emb')
                   7989: 		|| ($embstyle eq 'wrp')) {
                   7990: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 7991: 	    } elsif ($embstyle eq 'unk'
                   7992: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 7993: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 7994: 	    } else {
1.718     www      7995: #		&logthis("Got a blank emb style");
1.695     albertel 7996: 	    }
1.694     albertel 7997: 	}
                   7998:     }
1.31      www      7999:     return $thisfn;
1.12      www      8000: }
                   8001: 
1.787     albertel 8002: sub clutter_with_no_wrapper {
                   8003:     my $uri = &clutter(shift);
                   8004:     if ($uri =~ m-^/adm/-) {
                   8005: 	$uri =~ s-^/adm/wrapper/-/-;
                   8006: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   8007:     }
                   8008:     return $uri;
                   8009: }
                   8010: 
1.557     albertel 8011: sub freeze_escape {
                   8012:     my ($value)=@_;
                   8013:     if (ref($value)) {
                   8014: 	$value=&nfreeze($value);
                   8015: 	return '__FROZEN__'.&escape($value);
                   8016:     }
                   8017:     return &escape($value);
                   8018: }
                   8019: 
1.11      www      8020: 
1.557     albertel 8021: sub thaw_unescape {
                   8022:     my ($value)=@_;
                   8023:     if ($value =~ /^__FROZEN__/) {
                   8024: 	substr($value,0,10,undef);
                   8025: 	$value=&unescape($value);
                   8026: 	return &thaw($value);
                   8027:     }
                   8028:     return &unescape($value);
                   8029: }
                   8030: 
1.436     albertel 8031: sub correct_line_ends {
                   8032:     my ($result)=@_;
                   8033:     $$result =~s/\r\n/\n/mg;
                   8034:     $$result =~s/\r/\n/mg;
1.415     albertel 8035: }
1.1       albertel 8036: # ================================================================ Main Program
                   8037: 
1.184     www      8038: sub goodbye {
1.204     albertel 8039:    &logthis("Starting Shut down");
1.443     albertel 8040: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 8041:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 8042: #converted
1.599     albertel 8043: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 8044:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   8045: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   8046: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 8047: #1.1 only
1.870     albertel 8048: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   8049: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   8050: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   8051: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   8052:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 8053:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   8054:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      8055:    &flushcourselogs();
                   8056:    &logthis("Shutting down");
                   8057: }
                   8058: 
1.852     albertel 8059: sub get_dns {
1.869     albertel 8060:     my ($url,$func,$ignore_cache) = @_;
                   8061:     if (!$ignore_cache) {
                   8062: 	my ($content,$cached)=
                   8063: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   8064: 	if ($cached) {
                   8065: 	    &$func($content);
                   8066: 	    return;
                   8067: 	}
                   8068:     }
                   8069: 
                   8070:     my %alldns;
1.852     albertel 8071:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   8072:     foreach my $dns (<$config>) {
                   8073: 	next if ($dns !~ /^\^(\S*)/x);
1.869     albertel 8074: 	$alldns{$1} = 1;
                   8075:     }
                   8076:     while (%alldns) {
                   8077: 	my ($dns) = keys(%alldns);
                   8078: 	delete($alldns{$dns});
1.852     albertel 8079: 	my $ua=new LWP::UserAgent;
                   8080: 	my $request=new HTTP::Request('GET',"http://$dns$url");
                   8081: 	my $response=$ua->request($request);
                   8082: 	next if ($response->is_error());
                   8083: 	my @content = split("\n",$response->content);
1.869     albertel 8084: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 8085: 	&$func(\@content);
1.869     albertel 8086: 	return;
1.852     albertel 8087:     }
                   8088:     close($config);
1.871     albertel 8089:     my $which = (split('/',$url))[3];
                   8090:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   8091:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 8092:     my @content = <$config>;
                   8093:     &$func(\@content);
                   8094:     return;
1.852     albertel 8095: }
1.327     albertel 8096: # ------------------------------------------------------------ Read domain file
                   8097: {
1.852     albertel 8098:     my $loaded;
1.846     albertel 8099:     my %domain;
                   8100: 
1.852     albertel 8101:     sub parse_domain_tab {
                   8102: 	my ($lines) = @_;
                   8103: 	foreach my $line (@$lines) {
                   8104: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      8105: 
1.846     albertel 8106: 	    chomp($line);
1.852     albertel 8107: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 8108: 	    my %this_domain;
                   8109: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   8110: 			       'lang_def', 'city', 'longi', 'lati',
                   8111: 			       'primary') {
                   8112: 		$this_domain{$field} = shift(@elements);
                   8113: 	    }
                   8114: 	    $domain{$name} = \%this_domain;
1.852     albertel 8115: 	}
                   8116:     }
1.864     albertel 8117: 
                   8118:     sub reset_domain_info {
                   8119: 	undef($loaded);
                   8120: 	undef(%domain);
                   8121:     }
                   8122: 
1.852     albertel 8123:     sub load_domain_tab {
1.869     albertel 8124: 	my ($ignore_cache) = @_;
                   8125: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 8126: 	my $fh;
                   8127: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   8128: 	    my @lines = <$fh>;
                   8129: 	    &parse_domain_tab(\@lines);
1.448     albertel 8130: 	}
1.852     albertel 8131: 	close($fh);
                   8132: 	$loaded = 1;
1.327     albertel 8133:     }
1.846     albertel 8134: 
                   8135:     sub domain {
1.852     albertel 8136: 	&load_domain_tab() if (!$loaded);
                   8137: 
1.846     albertel 8138: 	my ($name,$what) = @_;
                   8139: 	return if ( !exists($domain{$name}) );
                   8140: 
                   8141: 	if (!$what) {
                   8142: 	    return $domain{$name}{'description'};
                   8143: 	}
                   8144: 	return $domain{$name}{$what};
                   8145:     }
1.327     albertel 8146: }
                   8147: 
                   8148: 
1.1       albertel 8149: # ------------------------------------------------------------- Read hosts file
                   8150: {
1.838     albertel 8151:     my %hostname;
1.844     albertel 8152:     my %hostdom;
1.845     albertel 8153:     my %libserv;
1.852     albertel 8154:     my $loaded;
1.888     albertel 8155:     my %name_to_host;
1.852     albertel 8156: 
                   8157:     sub parse_hosts_tab {
                   8158: 	my ($file) = @_;
                   8159: 	foreach my $configline (@$file) {
                   8160: 	    next if ($configline =~ /^(\#|\s*$ )/x);
                   8161: 	    next if ($configline =~ /^\^/);
                   8162: 	    chomp($configline);
                   8163: 	    my ($id,$domain,$role,$name)=split(/:/,$configline);
                   8164: 	    $name=~s/\s//g;
                   8165: 	    if ($id && $domain && $role && $name) {
                   8166: 		$hostname{$id}=$name;
1.888     albertel 8167: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 8168: 		$hostdom{$id}=$domain;
                   8169: 		if ($role eq 'library') { $libserv{$id}=$name; }
                   8170: 	    }
                   8171: 	}
                   8172:     }
1.864     albertel 8173:     
                   8174:     sub reset_hosts_info {
1.897     albertel 8175: 	&purge_remembered();
1.864     albertel 8176: 	&reset_domain_info();
                   8177: 	&reset_hosts_ip_info();
1.892     albertel 8178: 	undef(%name_to_host);
1.864     albertel 8179: 	undef(%hostname);
                   8180: 	undef(%hostdom);
                   8181: 	undef(%libserv);
                   8182: 	undef($loaded);
                   8183:     }
1.1       albertel 8184: 
1.852     albertel 8185:     sub load_hosts_tab {
1.869     albertel 8186: 	my ($ignore_cache) = @_;
                   8187: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 8188: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   8189: 	my @config = <$config>;
                   8190: 	&parse_hosts_tab(\@config);
                   8191: 	close($config);
                   8192: 	$loaded=1;
1.1       albertel 8193:     }
1.852     albertel 8194: 
1.838     albertel 8195:     sub hostname {
1.852     albertel 8196: 	&load_hosts_tab() if (!$loaded);
                   8197: 
1.838     albertel 8198: 	my ($lonid) = @_;
                   8199: 	return $hostname{$lonid};
                   8200:     }
1.845     albertel 8201: 
1.838     albertel 8202:     sub all_hostnames {
1.852     albertel 8203: 	&load_hosts_tab() if (!$loaded);
                   8204: 
1.838     albertel 8205: 	return %hostname;
                   8206:     }
1.845     albertel 8207: 
1.888     albertel 8208:     sub all_names {
                   8209: 	&load_hosts_tab() if (!$loaded);
                   8210: 
                   8211: 	return %name_to_host;
                   8212:     }
                   8213: 
1.845     albertel 8214:     sub is_library {
1.852     albertel 8215: 	&load_hosts_tab() if (!$loaded);
                   8216: 
1.845     albertel 8217: 	return exists($libserv{$_[0]});
                   8218:     }
                   8219: 
                   8220:     sub all_library {
1.852     albertel 8221: 	&load_hosts_tab() if (!$loaded);
                   8222: 
1.845     albertel 8223: 	return %libserv;
                   8224:     }
                   8225: 
1.841     albertel 8226:     sub get_servers {
1.852     albertel 8227: 	&load_hosts_tab() if (!$loaded);
                   8228: 
1.841     albertel 8229: 	my ($domain,$type) = @_;
                   8230: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   8231: 	                                          : %hostname;
                   8232: 	my %result;
1.842     albertel 8233: 	if (ref($domain) eq 'ARRAY') {
                   8234: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 8235: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 8236: 		    $result{$host} = $hostname;
                   8237: 		}
                   8238: 	    }
                   8239: 	} else {
                   8240: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   8241: 		if ($hostdom{$host} eq $domain) {
                   8242: 		    $result{$host} = $hostname;
                   8243: 		}
1.841     albertel 8244: 	    }
                   8245: 	}
                   8246: 	return %result;
                   8247:     }
1.845     albertel 8248: 
1.844     albertel 8249:     sub host_domain {
1.852     albertel 8250: 	&load_hosts_tab() if (!$loaded);
                   8251: 
1.844     albertel 8252: 	my ($lonid) = @_;
                   8253: 	return $hostdom{$lonid};
                   8254:     }
                   8255: 
1.841     albertel 8256:     sub all_domains {
1.852     albertel 8257: 	&load_hosts_tab() if (!$loaded);
                   8258: 
1.841     albertel 8259: 	my %seen;
                   8260: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   8261: 	return @uniq;
                   8262:     }
1.1       albertel 8263: }
                   8264: 
1.847     albertel 8265: { 
                   8266:     my %iphost;
1.856     albertel 8267:     my %name_to_ip;
                   8268:     my %lonid_to_ip;
1.869     albertel 8269: 
1.847     albertel 8270:     sub get_hosts_from_ip {
                   8271: 	my ($ip) = @_;
                   8272: 	my %iphosts = &get_iphost();
                   8273: 	if (ref($iphosts{$ip})) {
                   8274: 	    return @{$iphosts{$ip}};
                   8275: 	}
                   8276: 	return;
1.839     albertel 8277:     }
1.864     albertel 8278:     
                   8279:     sub reset_hosts_ip_info {
                   8280: 	undef(%iphost);
                   8281: 	undef(%name_to_ip);
                   8282: 	undef(%lonid_to_ip);
                   8283:     }
1.856     albertel 8284: 
                   8285:     sub get_host_ip {
                   8286: 	my ($lonid) = @_;
                   8287: 	if (exists($lonid_to_ip{$lonid})) {
                   8288: 	    return $lonid_to_ip{$lonid};
                   8289: 	}
                   8290: 	my $name=&hostname($lonid);
                   8291:    	my $ip = gethostbyname($name);
                   8292: 	return if (!$ip || length($ip) ne 4);
                   8293: 	$ip=inet_ntoa($ip);
                   8294: 	$name_to_ip{$name}   = $ip;
                   8295: 	$lonid_to_ip{$lonid} = $ip;
                   8296: 	return $ip;
                   8297:     }
1.847     albertel 8298:     
                   8299:     sub get_iphost {
1.869     albertel 8300: 	my ($ignore_cache) = @_;
1.894     albertel 8301: 
1.869     albertel 8302: 	if (!$ignore_cache) {
                   8303: 	    if (%iphost) {
                   8304: 		return %iphost;
                   8305: 	    }
                   8306: 	    my ($ip_info,$cached)=
                   8307: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   8308: 	    if ($cached) {
                   8309: 		%iphost      = %{$ip_info->[0]};
                   8310: 		%name_to_ip  = %{$ip_info->[1]};
                   8311: 		%lonid_to_ip = %{$ip_info->[2]};
                   8312: 		return %iphost;
                   8313: 	    }
                   8314: 	}
1.894     albertel 8315: 
                   8316: 	# get yesterday's info for fallback
                   8317: 	my %old_name_to_ip;
                   8318: 	my ($ip_info,$cached)=
                   8319: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   8320: 	if ($cached) {
                   8321: 	    %old_name_to_ip = %{$ip_info->[1]};
                   8322: 	}
                   8323: 
1.888     albertel 8324: 	my %name_to_host = &all_names();
                   8325: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 8326: 	    my $ip;
                   8327: 	    if (!exists($name_to_ip{$name})) {
                   8328: 		$ip = gethostbyname($name);
                   8329: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 8330: 		    if (defined($old_name_to_ip{$name})) {
                   8331: 			$ip = $old_name_to_ip{$name};
                   8332: 			&logthis("Can't find $name defaulting to old $ip");
                   8333: 		    } else {
                   8334: 			&logthis("Name $name no IP found");
                   8335: 			next;
                   8336: 		    }
                   8337: 		} else {
                   8338: 		    $ip=inet_ntoa($ip);
1.847     albertel 8339: 		}
                   8340: 		$name_to_ip{$name} = $ip;
                   8341: 	    } else {
                   8342: 		$ip = $name_to_ip{$name};
1.653     albertel 8343: 	    }
1.888     albertel 8344: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   8345: 		$lonid_to_ip{$id} = $ip;
                   8346: 	    }
                   8347: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 8348: 	}
1.869     albertel 8349: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   8350: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 8351: 				      48*60*60);
1.869     albertel 8352: 
1.847     albertel 8353: 	return %iphost;
1.598     albertel 8354:     }
                   8355: }
                   8356: 
1.862     albertel 8357: BEGIN {
                   8358: 
                   8359: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   8360:     unless ($readit) {
                   8361: {
                   8362:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   8363:     %perlvar = (%perlvar,%{$configvars});
                   8364: }
                   8365: 
                   8366: 
1.1       albertel 8367: # ------------------------------------------------------ Read spare server file
                   8368: {
1.448     albertel 8369:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 8370: 
                   8371:     while (my $configline=<$config>) {
                   8372:        chomp($configline);
1.284     matthew  8373:        if ($configline) {
1.784     albertel 8374: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 8375: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 8376: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 8377:        }
                   8378:     }
1.448     albertel 8379:     close($config);
1.1       albertel 8380: }
1.11      www      8381: # ------------------------------------------------------------ Read permissions
                   8382: {
1.448     albertel 8383:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      8384: 
                   8385:     while (my $configline=<$config>) {
1.448     albertel 8386: 	chomp($configline);
                   8387: 	if ($configline) {
                   8388: 	    my ($role,$perm)=split(/ /,$configline);
                   8389: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   8390: 	}
1.11      www      8391:     }
1.448     albertel 8392:     close($config);
1.11      www      8393: }
                   8394: 
                   8395: # -------------------------------------------- Read plain texts for permissions
                   8396: {
1.448     albertel 8397:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      8398: 
                   8399:     while (my $configline=<$config>) {
1.448     albertel 8400: 	chomp($configline);
                   8401: 	if ($configline) {
1.742     raeburn  8402: 	    my ($short,@plain)=split(/:/,$configline);
                   8403:             %{$prp{$short}} = ();
                   8404: 	    if (@plain > 0) {
                   8405:                 $prp{$short}{'std'} = $plain[0];
                   8406:                 for (my $i=1; $i<@plain; $i++) {
                   8407:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   8408:                 }
                   8409:             }
1.448     albertel 8410: 	}
1.135     www      8411:     }
1.448     albertel 8412:     close($config);
1.135     www      8413: }
                   8414: 
                   8415: # ---------------------------------------------------------- Read package table
                   8416: {
1.448     albertel 8417:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      8418: 
                   8419:     while (my $configline=<$config>) {
1.483     albertel 8420: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 8421: 	chomp($configline);
                   8422: 	my ($short,$plain)=split(/:/,$configline);
                   8423: 	my ($pack,$name)=split(/\&/,$short);
                   8424: 	if ($plain ne '') {
                   8425: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   8426: 	    $packagetab{$short}=$plain; 
                   8427: 	}
1.11      www      8428:     }
1.448     albertel 8429:     close($config);
1.329     matthew  8430: }
                   8431: 
                   8432: # ------------- set up temporary directory
                   8433: {
                   8434:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   8435: 
1.11      www      8436: }
                   8437: 
1.794     albertel 8438: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   8439: 				'compress_threshold'=> 20_000,
                   8440:  			        });
1.185     www      8441: 
1.281     www      8442: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      8443: $dumpcount=0;
1.22      www      8444: 
1.163     harris41 8445: &logtouch();
1.672     albertel 8446: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      8447: $readit=1;
1.564     albertel 8448:     {
                   8449: 	use integer;
                   8450: 	my $test=(2**32)+1;
1.568     albertel 8451: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 8452: 	&logthis(" Detected 64bit platform ($_64bit)");
                   8453:     }
1.195     www      8454: }
1.1       albertel 8455: }
1.179     www      8456: 
1.1       albertel 8457: 1;
1.191     harris41 8458: __END__
                   8459: 
1.243     albertel 8460: =pod
                   8461: 
1.191     harris41 8462: =head1 NAME
                   8463: 
1.243     albertel 8464: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 8465: 
                   8466: =head1 SYNOPSIS
                   8467: 
1.243     albertel 8468: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 8469: 
                   8470:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   8471: 
1.243     albertel 8472: Common parameters:
                   8473: 
                   8474: =over 4
                   8475: 
                   8476: =item *
                   8477: 
                   8478: $uname : an internal username (if $cname expecting a course Id specifically)
                   8479: 
                   8480: =item *
                   8481: 
                   8482: $udom : a domain (if $cdom expecting a course's domain specifically)
                   8483: 
                   8484: =item *
                   8485: 
                   8486: $symb : a resource instance identifier
                   8487: 
                   8488: =item *
                   8489: 
                   8490: $namespace : the name of a .db file that contains the data needed or
                   8491: being set.
                   8492: 
                   8493: =back
                   8494: 
1.394     bowersj2 8495: =head1 OVERVIEW
1.191     harris41 8496: 
1.394     bowersj2 8497: lonnet provides subroutines which interact with the
                   8498: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   8499: about classes, users, and resources.
1.243     albertel 8500: 
                   8501: For many of these objects you can also use this to store data about
                   8502: them or modify them in various ways.
1.191     harris41 8503: 
1.394     bowersj2 8504: =head2 Symbs
1.191     harris41 8505: 
1.394     bowersj2 8506: To identify a specific instance of a resource, LON-CAPA uses symbols
                   8507: or "symbs"X<symb>. These identifiers are built from the URL of the
                   8508: map, the resource number of the resource in the map, and the URL of
                   8509: the resource itself. The latter is somewhat redundant, but might help
                   8510: if maps change.
                   8511: 
                   8512: An example is
                   8513: 
                   8514:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   8515: 
                   8516: The respective map entry is
                   8517: 
                   8518:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   8519:   title="Problem 2">
                   8520:  </resource>
                   8521: 
                   8522: Symbs are used by the random number generator, as well as to store and
                   8523: restore data specific to a certain instance of for example a problem.
                   8524: 
                   8525: =head2 Storing And Retrieving Data
                   8526: 
                   8527: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   8528: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   8529: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   8530: is is the non-critical message twin of cstore. These functions are for
                   8531: handlers to store a perl hash to a user's permanent data space in an
                   8532: easy manner, and to retrieve it again on another call. It is expected
                   8533: that a handler would use this once at the beginning to retrieve data,
                   8534: and then again once at the end to send only the new data back.
                   8535: 
                   8536: The data is stored in the user's data directory on the user's
                   8537: homeserver under the ID of the course.
                   8538: 
                   8539: The hash that is returned by restore will have all of the previous
                   8540: value for all of the elements of the hash.
                   8541: 
                   8542: Example:
                   8543: 
                   8544:  #creating a hash
                   8545:  my %hash;
                   8546:  $hash{'foo'}='bar';
                   8547: 
                   8548:  #storing it
                   8549:  &Apache::lonnet::cstore(\%hash);
                   8550: 
                   8551:  #changing a value
                   8552:  $hash{'foo'}='notbar';
                   8553: 
                   8554:  #adding a new value
                   8555:  $hash{'bar'}='foo';
                   8556:  &Apache::lonnet::cstore(\%hash);
                   8557: 
                   8558:  #retrieving the hash
                   8559:  my %history=&Apache::lonnet::restore();
                   8560: 
                   8561:  #print the hash
                   8562:  foreach my $key (sort(keys(%history))) {
                   8563:    print("\%history{$key} = $history{$key}");
                   8564:  }
                   8565: 
                   8566: Will print out:
1.191     harris41 8567: 
1.394     bowersj2 8568:  %history{1:foo} = bar
                   8569:  %history{1:keys} = foo:timestamp
                   8570:  %history{1:timestamp} = 990455579
                   8571:  %history{2:bar} = foo
                   8572:  %history{2:foo} = notbar
                   8573:  %history{2:keys} = foo:bar:timestamp
                   8574:  %history{2:timestamp} = 990455580
                   8575:  %history{bar} = foo
                   8576:  %history{foo} = notbar
                   8577:  %history{timestamp} = 990455580
                   8578:  %history{version} = 2
                   8579: 
                   8580: Note that the special hash entries C<keys>, C<version> and
                   8581: C<timestamp> were added to the hash. C<version> will be equal to the
                   8582: total number of versions of the data that have been stored. The
                   8583: C<timestamp> attribute will be the UNIX time the hash was
                   8584: stored. C<keys> is available in every historical section to list which
                   8585: keys were added or changed at a specific historical revision of a
                   8586: hash.
                   8587: 
                   8588: B<Warning>: do not store the hash that restore returns directly. This
                   8589: will cause a mess since it will restore the historical keys as if the
                   8590: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 8591: 
1.394     bowersj2 8592: Calling convention:
1.191     harris41 8593: 
1.394     bowersj2 8594:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   8595:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 8596: 
1.394     bowersj2 8597: For more detailed information, see lonnet specific documentation.
1.191     harris41 8598: 
1.394     bowersj2 8599: =head1 RETURN MESSAGES
1.191     harris41 8600: 
1.394     bowersj2 8601: =over 4
1.191     harris41 8602: 
1.394     bowersj2 8603: =item * B<con_lost>: unable to contact remote host
1.191     harris41 8604: 
1.394     bowersj2 8605: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   8606: when the connection is brought back up
1.191     harris41 8607: 
1.394     bowersj2 8608: =item * B<con_failed>: unable to contact remote host and unable to save message
                   8609: for later delivery
1.191     harris41 8610: 
1.394     bowersj2 8611: =item * B<error:>: an error a occured, a description of the error follows the :
1.191     harris41 8612: 
1.394     bowersj2 8613: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 8614: that was requested
1.191     harris41 8615: 
1.243     albertel 8616: =back
1.191     harris41 8617: 
1.243     albertel 8618: =head1 PUBLIC SUBROUTINES
1.191     harris41 8619: 
1.243     albertel 8620: =head2 Session Environment Functions
1.191     harris41 8621: 
1.243     albertel 8622: =over 4
1.191     harris41 8623: 
1.394     bowersj2 8624: =item * 
                   8625: X<appenv()>
                   8626: B<appenv(%hash)>: the value of %hash is written to
                   8627: the user envirnoment file, and will be restored for each access this
1.620     albertel 8628: user makes during this session, also modifies the %env for the current
1.394     bowersj2 8629: process
1.191     harris41 8630: 
                   8631: =item *
1.394     bowersj2 8632: X<delenv()>
                   8633: B<delenv($regexp)>: removes all items from the session
                   8634: environment file that matches the regular expression in $regexp. The
1.620     albertel 8635: values are also delted from the current processes %env.
1.191     harris41 8636: 
1.795     albertel 8637: =item * get_env_multiple($name) 
                   8638: 
                   8639: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   8640: values may be defined and end up as an array ref.
                   8641: 
                   8642: returns an array of values
                   8643: 
1.243     albertel 8644: =back
                   8645: 
                   8646: =head2 User Information
1.191     harris41 8647: 
1.243     albertel 8648: =over 4
1.191     harris41 8649: 
                   8650: =item *
1.394     bowersj2 8651: X<queryauthenticate()>
                   8652: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 8653: authentication scheme
                   8654: 
                   8655: =item *
1.394     bowersj2 8656: X<authenticate()>
                   8657: B<authenticate($uname,$upass,$udom)>: try to
                   8658: authenticate user from domain's lib servers (first use the current
                   8659: one). C<$upass> should be the users password.
1.191     harris41 8660: 
                   8661: =item *
1.394     bowersj2 8662: X<homeserver()>
                   8663: B<homeserver($uname,$udom)>: find the server which has
                   8664: the user's directory and files (there must be only one), this caches
                   8665: the answer, and also caches if there is a borken connection.
1.191     harris41 8666: 
                   8667: =item *
1.394     bowersj2 8668: X<idget()>
                   8669: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   8670: (IDs are a unique resource in a domain, there must be only 1 ID per
                   8671: username, and only 1 username per ID in a specific domain) (returns
                   8672: hash: id=>name,id=>name)
1.191     harris41 8673: 
                   8674: =item *
1.394     bowersj2 8675: X<idrget()>
                   8676: B<idrget($udom,@unames)>: find the IDs behind a list of
                   8677: usernames (returns hash: name=>id,name=>id)
1.191     harris41 8678: 
                   8679: =item *
1.394     bowersj2 8680: X<idput()>
                   8681: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 8682: 
                   8683: =item *
1.394     bowersj2 8684: X<rolesinit()>
                   8685: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 8686: 
                   8687: =item *
1.551     albertel 8688: X<getsection()>
                   8689: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 8690: course $cname, return section name/number or '' for "not in course"
                   8691: and '-1' for "no section"
                   8692: 
                   8693: =item *
1.394     bowersj2 8694: X<userenvironment()>
                   8695: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 8696: passed in @what from the requested user's environment, returns a hash
                   8697: 
1.858     raeburn  8698: =item * 
                   8699: X<userlog_query()>
1.859     albertel 8700: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   8701: activity.log file. %filters defines filters applied when parsing the
                   8702: log file. These can be start or end timestamps, or the type of action
                   8703: - log to look for Login or Logout events, check for Checkin or
                   8704: Checkout, role for role selection. The response is in the form
                   8705: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   8706: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  8707: 
1.243     albertel 8708: =back
                   8709: 
                   8710: =head2 User Roles
                   8711: 
                   8712: =over 4
                   8713: 
                   8714: =item *
                   8715: 
1.810     raeburn  8716: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 8717:  F: full access
                   8718:  U,I,K: authentication modes (cxx only)
                   8719:  '': forbidden
                   8720:  1: user needs to choose course
                   8721:  2: browse allowed
1.766     albertel 8722:  A: passphrase authentication needed
1.243     albertel 8723: 
                   8724: =item *
                   8725: 
                   8726: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   8727: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   8728: and course level
                   8729: 
                   8730: =item *
                   8731: 
                   8732: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   8733: explanation of a user role term
                   8734: 
1.832     raeburn  8735: =item *
                   8736: 
1.858     raeburn  8737: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms) :
                   8738: All arguments are optional. Returns a hash of a roles, either for
                   8739: co-author/assistant author roles for a user's Construction Space
1.906     albertel 8740: (default), or if $context is 'userroles', roles for the user himself,
1.858     raeburn  8741: In the hash, keys are set to colon-sparated $uname,$udom,and $role,
                   8742: and value is set to colon-separated start and end times for the role.
                   8743: If no username and domain are specified, will default to current
                   8744: user/domain. Types, roles, and roledoms are references to arrays,
                   8745: of role statuses (active, future or previous), roles 
                   8746: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   8747: to restrict the list of roles reported. If no array ref is 
                   8748: provided for types, will default to return only active roles.
1.834     albertel 8749: 
1.243     albertel 8750: =back
                   8751: 
                   8752: =head2 User Modification
                   8753: 
                   8754: =over 4
                   8755: 
                   8756: =item *
                   8757: 
                   8758: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
                   8759: user for the level given by URL.  Optional start and end dates (leave empty
                   8760: string or zero for "no date")
1.191     harris41 8761: 
                   8762: =item *
                   8763: 
1.243     albertel 8764: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   8765: change a users, password, possible return values are: ok,
                   8766: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   8767: refused
1.191     harris41 8768: 
                   8769: =item *
                   8770: 
1.243     albertel 8771: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 8772: 
                   8773: =item *
                   8774: 
1.243     albertel 8775: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
                   8776: modify user
1.191     harris41 8777: 
                   8778: =item *
                   8779: 
1.286     matthew  8780: modifystudent
                   8781: 
                   8782: modify a students enrollment and identification information.
                   8783: The course id is resolved based on the current users environment.  
                   8784: This means the envoking user must be a course coordinator or otherwise
                   8785: associated with a course.
                   8786: 
1.297     matthew  8787: This call is essentially a wrapper for lonnet::modifyuser and
                   8788: lonnet::modify_student_enrollment
1.286     matthew  8789: 
                   8790: Inputs: 
                   8791: 
                   8792: =over 4
                   8793: 
                   8794: =item B<$udom> Students loncapa domain
                   8795: 
                   8796: =item B<$uname> Students loncapa login name
                   8797: 
                   8798: =item B<$uid> Students id/student number
                   8799: 
                   8800: =item B<$umode> Students authentication mode
                   8801: 
                   8802: =item B<$upass> Students password
                   8803: 
                   8804: =item B<$first> Students first name
                   8805: 
                   8806: =item B<$middle> Students middle name
                   8807: 
                   8808: =item B<$last> Students last name
                   8809: 
                   8810: =item B<$gene> Students generation
                   8811: 
                   8812: =item B<$usec> Students section in course
                   8813: 
                   8814: =item B<$end> Unix time of the roles expiration
                   8815: 
                   8816: =item B<$start> Unix time of the roles start date
                   8817: 
                   8818: =item B<$forceid> If defined, allow $uid to be changed
                   8819: 
                   8820: =item B<$desiredhome> server to use as home server for student
                   8821: 
                   8822: =back
1.297     matthew  8823: 
                   8824: =item *
                   8825: 
                   8826: modify_student_enrollment
                   8827: 
                   8828: Change a students enrollment status in a class.  The environment variable
                   8829: 'role.request.course' must be defined for this function to proceed.
                   8830: 
                   8831: Inputs:
                   8832: 
                   8833: =over 4
                   8834: 
                   8835: =item $udom, students domain
                   8836: 
                   8837: =item $uname, students name
                   8838: 
                   8839: =item $uid, students user id
                   8840: 
                   8841: =item $first, students first name
                   8842: 
                   8843: =item $middle
                   8844: 
                   8845: =item $last
                   8846: 
                   8847: =item $gene
                   8848: 
                   8849: =item $usec
                   8850: 
                   8851: =item $end
                   8852: 
                   8853: =item $start
                   8854: 
                   8855: =back
                   8856: 
1.191     harris41 8857: 
                   8858: =item *
                   8859: 
1.243     albertel 8860: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   8861: custom role; give a custom role to a user for the level given by URL.  Specify
                   8862: name and domain of role author, and role name
1.191     harris41 8863: 
                   8864: =item *
                   8865: 
1.243     albertel 8866: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 8867: 
                   8868: =item *
                   8869: 
1.243     albertel 8870: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   8871: 
                   8872: =back
                   8873: 
                   8874: =head2 Course Infomation
                   8875: 
                   8876: =over 4
1.191     harris41 8877: 
                   8878: =item *
                   8879: 
1.631     albertel 8880: coursedescription($courseid) : returns a hash of information about the
                   8881: specified course id, including all environment settings for the
                   8882: course, the description of the course will be in the hash under the
                   8883: key 'description'
1.191     harris41 8884: 
                   8885: =item *
                   8886: 
1.624     albertel 8887: resdata($name,$domain,$type,@which) : request for current parameter
                   8888: setting for a specific $type, where $type is either 'course' or 'user',
                   8889: @what should be a list of parameters to ask about. This routine caches
                   8890: answers for 5 minutes.
1.243     albertel 8891: 
1.877     foxr     8892: =item *
                   8893: 
                   8894: get_courseresdata($courseid, $domain) : dump the entire course resource
                   8895: data base, returning a hash that is keyed by the resource name and has
                   8896: values that are the resource value.  I believe that the timestamps and
                   8897: versions are also returned.
                   8898: 
                   8899: 
1.243     albertel 8900: =back
                   8901: 
                   8902: =head2 Course Modification
                   8903: 
                   8904: =over 4
1.191     harris41 8905: 
                   8906: =item *
                   8907: 
1.243     albertel 8908: writecoursepref($courseid,%prefs) : write preferences (environment
                   8909: database) for a course
1.191     harris41 8910: 
                   8911: =item *
                   8912: 
1.243     albertel 8913: createcourse($udom,$description,$url) : make/modify course
                   8914: 
                   8915: =back
                   8916: 
                   8917: =head2 Resource Subroutines
                   8918: 
                   8919: =over 4
1.191     harris41 8920: 
                   8921: =item *
                   8922: 
1.243     albertel 8923: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 8924: 
                   8925: =item *
                   8926: 
1.243     albertel 8927: repcopy($filename) : subscribes to the requested file, and attempts to
                   8928: replicate from the owning library server, Might return
1.607     raeburn  8929: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   8930: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 8931: resource. Expects the local filesystem pathname
                   8932: (/home/httpd/html/res/....)
                   8933: 
                   8934: =back
                   8935: 
                   8936: =head2 Resource Information
                   8937: 
                   8938: =over 4
1.191     harris41 8939: 
                   8940: =item *
                   8941: 
1.243     albertel 8942: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   8943: a vairety of different possible values, $varname should be a request
                   8944: string, and the other parameters can be used to specify who and what
                   8945: one is asking about.
                   8946: 
                   8947: Possible values for $varname are environment.lastname (or other item
                   8948: from the envirnment hash), user.name (or someother aspect about the
                   8949: user), resource.0.maxtries (or some other part and parameter of a
                   8950: resource)
1.204     albertel 8951: 
                   8952: =item *
                   8953: 
1.243     albertel 8954: directcondval($number) : get current value of a condition; reads from a state
                   8955: string
1.204     albertel 8956: 
                   8957: =item *
                   8958: 
1.243     albertel 8959: condval($condidx) : value of condition index based on state
1.204     albertel 8960: 
                   8961: =item *
                   8962: 
1.243     albertel 8963: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   8964: resource's metadata, $what should be either a specific key, or either
                   8965: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   8966: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   8967: 
                   8968: this function automatically caches all requests
1.191     harris41 8969: 
                   8970: =item *
                   8971: 
1.243     albertel 8972: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   8973: network of library servers; returns file handle of where SQL and regex results
                   8974: will be stored for query
1.191     harris41 8975: 
                   8976: =item *
                   8977: 
1.243     albertel 8978: symbread($filename) : return symbolic list entry (filename argument optional);
                   8979: returns the data handle
1.191     harris41 8980: 
                   8981: =item *
                   8982: 
1.243     albertel 8983: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 8984: a possible symb for the URL in $thisfn, and if is an encryypted
                   8985: resource that the user accessed using /enc/ returns a 1 on success, 0
                   8986: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 8987: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 8988: 
1.191     harris41 8989: 
                   8990: =item *
                   8991: 
1.243     albertel 8992: symbclean($symb) : removes versions numbers from a symb, returns the
                   8993: cleaned symb
1.191     harris41 8994: 
                   8995: =item *
                   8996: 
1.243     albertel 8997: is_on_map($uri) : checks if the $uri is somewhere on the current
                   8998: course map, user must be in a course for it to work.
1.191     harris41 8999: 
                   9000: =item *
                   9001: 
1.243     albertel 9002: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 9003: 
                   9004: =item *
                   9005: 
1.243     albertel 9006: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   9007: a random seed, all arguments are optional, if they aren't sent it uses the
                   9008: environment to derive them. Note: if symb isn't sent and it can't get one
                   9009: from &symbread it will use the current time as its return value
1.191     harris41 9010: 
                   9011: =item *
                   9012: 
1.243     albertel 9013: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   9014: unfakeable, receipt
1.191     harris41 9015: 
                   9016: =item *
                   9017: 
1.620     albertel 9018: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 9019: 
                   9020: =item *
                   9021: 
1.243     albertel 9022: countacc($url) : count the number of accesses to a given URL
1.191     harris41 9023: 
                   9024: =item *
                   9025: 
1.243     albertel 9026: 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 9027: 
                   9028: =item *
                   9029: 
1.243     albertel 9030: 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 9031: 
                   9032: =item *
                   9033: 
1.243     albertel 9034: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 9035: 
                   9036: =item *
                   9037: 
1.243     albertel 9038: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   9039: forcing spreadsheet to reevaluate the resource scores next time.
                   9040: 
                   9041: =back
                   9042: 
                   9043: =head2 Storing/Retreiving Data
                   9044: 
                   9045: =over 4
1.191     harris41 9046: 
                   9047: =item *
                   9048: 
1.243     albertel 9049: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   9050: for this url; hashref needs to be given and should be a \%hashname; the
                   9051: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 9052: be derived from the env
1.191     harris41 9053: 
                   9054: =item *
                   9055: 
1.243     albertel 9056: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   9057: uses critical subroutine
1.191     harris41 9058: 
                   9059: =item *
                   9060: 
1.243     albertel 9061: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   9062: all args are optional
1.191     harris41 9063: 
                   9064: =item *
                   9065: 
1.717     albertel 9066: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   9067: dumps the complete (or key matching regexp) namespace into a hash
                   9068: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   9069: normally &store()ed into
                   9070: 
                   9071: $range should be either an integer '100' (give me the first 100
                   9072:                                            matching records)
                   9073:               or be  two integers sperated by a - with no spaces
                   9074:                  '30-50' (give me the 30th through the 50th matching
                   9075:                           records)
                   9076: 
                   9077: 
                   9078: =item *
                   9079: 
                   9080: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   9081: replaces a &store() version of data with a replacement set of data
                   9082: for a particular resource in a namespace passed in the $storehash hash 
                   9083: reference
                   9084: 
                   9085: =item *
                   9086: 
1.243     albertel 9087: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   9088: works very similar to store/cstore, but all data is stored in a
                   9089: temporary location and can be reset using tmpreset, $storehash should
                   9090: be a hash reference, returns nothing on success
1.191     harris41 9091: 
                   9092: =item *
                   9093: 
1.243     albertel 9094: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   9095: similar to restore, but all data is stored in a temporary location and
                   9096: can be reset using tmpreset. Returns a hash of values on success,
                   9097: error string otherwise.
1.191     harris41 9098: 
                   9099: =item *
                   9100: 
1.243     albertel 9101: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   9102: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 9103: 
                   9104: =item *
                   9105: 
1.243     albertel 9106: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   9107: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 9108: 
                   9109: =item *
                   9110: 
1.243     albertel 9111: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   9112: namesp ($udom and $uname are optional)
1.191     harris41 9113: 
                   9114: =item *
                   9115: 
1.702     albertel 9116: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 9117: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 9118: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  9119: 
1.702     albertel 9120: $range should be either an integer '100' (give me the first 100
                   9121:                                            matching records)
                   9122:               or be  two integers sperated by a - with no spaces
                   9123:                  '30-50' (give me the 30th through the 50th matching
                   9124:                           records)
1.449     matthew  9125: =item *
                   9126: 
                   9127: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   9128: $store can be a scalar, an array reference, or if the amount to be 
                   9129: incremented is > 1, a hash reference.
                   9130: 
                   9131: ($udom and $uname are optional)
1.191     harris41 9132: 
                   9133: =item *
                   9134: 
1.243     albertel 9135: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   9136: ($udom and $uname are optional)
1.191     harris41 9137: 
                   9138: =item *
                   9139: 
1.243     albertel 9140: cput($namespace,$storehash,$udom,$uname) : critical put
                   9141: ($udom and $uname are optional)
1.191     harris41 9142: 
                   9143: =item *
                   9144: 
1.748     albertel 9145: newput($namespace,$storehash,$udom,$uname) :
                   9146: 
                   9147: Attempts to store the items in the $storehash, but only if they don't
                   9148: currently exist, if this succeeds you can be certain that you have 
                   9149: successfully created a new key value pair in the $namespace db.
                   9150: 
                   9151: 
                   9152: Args:
                   9153:  $namespace: name of database to store values to
                   9154:  $storehash: hashref to store to the db
                   9155:  $udom: (optional) domain of user containing the db
                   9156:  $uname: (optional) name of user caontaining the db
                   9157: 
                   9158: Returns:
                   9159:  'ok' -> succeeded in storing all keys of $storehash
                   9160:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   9161:                         least <key> already existed in the db (other
                   9162:                         requested keys may also already exist)
                   9163:  'error: <msg>' -> unable to tie the DB or other erorr occured
                   9164:  'con_lost' -> unable to contact request server
                   9165:  'refused' -> action was not allowed by remote machine
                   9166: 
                   9167: 
                   9168: =item *
                   9169: 
1.243     albertel 9170: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   9171: reference filled in from namesp (encrypts the return communication)
                   9172: ($udom and $uname are optional)
1.191     harris41 9173: 
                   9174: =item *
                   9175: 
1.243     albertel 9176: log($udom,$name,$home,$message) : write to permanent log for user; use
                   9177: critical subroutine
                   9178: 
1.806     raeburn  9179: =item *
                   9180: 
1.860     raeburn  9181: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   9182: array reference filled in from namespace found in domain level on either
                   9183: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  9184: 
                   9185: =item *
                   9186: 
1.860     raeburn  9187: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   9188: domain level either on specified domain server ($uhome) or primary domain 
                   9189: server ($udom and $uhome are optional)
1.806     raeburn  9190: 
1.243     albertel 9191: =back
                   9192: 
                   9193: =head2 Network Status Functions
                   9194: 
                   9195: =over 4
1.191     harris41 9196: 
                   9197: =item *
                   9198: 
                   9199: dirlist($uri) : return directory list based on URI
                   9200: 
                   9201: =item *
                   9202: 
1.243     albertel 9203: spareserver() : find server with least workload from spare.tab
                   9204: 
                   9205: =back
                   9206: 
                   9207: =head2 Apache Request
                   9208: 
                   9209: =over 4
1.191     harris41 9210: 
                   9211: =item *
                   9212: 
1.243     albertel 9213: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   9214: localhost, posts hash
                   9215: 
                   9216: =back
                   9217: 
                   9218: =head2 Data to String to Data
                   9219: 
                   9220: =over 4
1.191     harris41 9221: 
                   9222: =item *
                   9223: 
1.243     albertel 9224: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   9225: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 9226: 
                   9227: =item *
                   9228: 
1.243     albertel 9229: hashref2str($hashref) : convert a hashref into a string complete with
                   9230: escaping and '=' and '&' separators, supports elements that are
                   9231: arrayrefs and hashrefs
1.191     harris41 9232: 
                   9233: =item *
                   9234: 
1.243     albertel 9235: arrayref2str($arrayref) : convert an arrayref into a string complete
                   9236: with escaping and '&' separators, supports elements that are arrayrefs
                   9237: and hashrefs
1.191     harris41 9238: 
                   9239: =item *
                   9240: 
1.243     albertel 9241: str2hash($string) : convert string to hash using unescaping and
                   9242: splitting on '=' and '&', supports elements that are arrayrefs and
                   9243: hashrefs
1.191     harris41 9244: 
                   9245: =item *
                   9246: 
1.243     albertel 9247: str2array($string) : convert string to hash using unescaping and
                   9248: splitting on '&', supports elements that are arrayrefs and hashrefs
                   9249: 
                   9250: =back
                   9251: 
                   9252: =head2 Logging Routines
                   9253: 
                   9254: =over 4
                   9255: 
                   9256: These routines allow one to make log messages in the lonnet.log and
                   9257: lonnet.perm logfiles.
1.191     harris41 9258: 
                   9259: =item *
                   9260: 
1.243     albertel 9261: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 9262: 
                   9263: =item *
                   9264: 
1.243     albertel 9265: logthis() : append message to the normal lonnet.log file, it gets
                   9266: preiodically rolled over and deleted.
1.191     harris41 9267: 
                   9268: =item *
                   9269: 
1.243     albertel 9270: logperm() : append a permanent message to lonnet.perm.log, this log
                   9271: file never gets deleted by any automated portion of the system, only
                   9272: messages of critical importance should go in here.
                   9273: 
                   9274: =back
                   9275: 
                   9276: =head2 General File Helper Routines
                   9277: 
                   9278: =over 4
1.191     harris41 9279: 
                   9280: =item *
                   9281: 
1.481     raeburn  9282: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   9283: (a) files in /uploaded
                   9284:   (i) If a local copy of the file exists - 
                   9285:       compares modification date of local copy with last-modified date for 
                   9286:       definitive version stored on home server for course. If local copy is 
                   9287:       stale, requests a new version from the home server and stores it. 
                   9288:       If the original has been removed from the home server, then local copy 
                   9289:       is unlinked.
                   9290:   (ii) If local copy does not exist -
                   9291:       requests the file from the home server and stores it. 
                   9292:   
                   9293:   If $caller is 'uploadrep':  
                   9294:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   9295:     for request for files originally uploaded via DOCS. 
                   9296:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   9297:   
                   9298:   Otherwise:
                   9299:      This indicates a call from the content generation phase of the request.
                   9300:      -  returns the entire contents of the file or -1.
                   9301:      
                   9302: (b) files in /res
                   9303:    - returns the entire contents of a file or -1; 
                   9304:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 9305: 
1.712     albertel 9306: 
                   9307: =item *
                   9308: 
                   9309: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   9310:                   reference
                   9311: 
                   9312: returns either a stat() list of data about the file or an empty list
                   9313: if the file doesn't exist or couldn't find out about it (connection
                   9314: problems or user unknown)
                   9315: 
1.191     harris41 9316: =item *
                   9317: 
1.243     albertel 9318: filelocation($dir,$file) : returns file system location of a file
                   9319: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   9320: directory that relative $file lookups are to looked in ($dir of /a/dir
                   9321: and a file of ../bob will become /a/bob)
1.191     harris41 9322: 
                   9323: =item *
                   9324: 
                   9325: hreflocation($dir,$file) : returns file system location or a URL; same as
                   9326: filelocation except for hrefs
                   9327: 
                   9328: =item *
                   9329: 
                   9330: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   9331: 
1.243     albertel 9332: =back
                   9333: 
1.608     albertel 9334: =head2 Usererfile file routines (/uploaded*)
                   9335: 
                   9336: =over 4
                   9337: 
                   9338: =item *
                   9339: 
                   9340: userfileupload(): main rotine for putting a file in a user or course's
                   9341:                   filespace, arguments are,
                   9342: 
1.620     albertel 9343:  formname - required - this is the name of the element in $env where the
1.608     albertel 9344:            filename, and the contents of the file to create/modifed exist
1.620     albertel 9345:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   9346:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 9347:  coursedoc - if true, store the file in the course of the active role
                   9348:              of the current user
                   9349:  subdir - required - subdirectory to put the file in under ../userfiles/
                   9350:          if undefined, it will be placed in "unknown"
                   9351: 
                   9352:  (This routine calls clean_filename() to remove any dangerous
                   9353:  characters from the filename, and then calls finuserfileupload() to
                   9354:  complete the transaction)
                   9355: 
                   9356:  returns either the url of the uploaded file (/uploaded/....) if successful
                   9357:  and /adm/notfound.html if unsuccessful
                   9358: 
                   9359: =item *
                   9360: 
                   9361: clean_filename(): routine for cleaing a filename up for storage in
                   9362:                  userfile space, argument is:
                   9363: 
                   9364:  filename - proposed filename
                   9365: 
                   9366: returns: the new clean filename
                   9367: 
                   9368: =item *
                   9369: 
                   9370: finishuserfileupload(): routine that creaes and sends the file to
                   9371: userspace, probably shouldn't be called directly
                   9372: 
                   9373:   docuname: username or courseid of destination for the file
                   9374:   docudom: domain of user/course of destination for the file
                   9375:   formname: same as for userfileupload()
                   9376:   fname: filename (inculding subdirectories) for the file
                   9377: 
                   9378:  returns either the url of the uploaded file (/uploaded/....) if successful
                   9379:  and /adm/notfound.html if unsuccessful
                   9380: 
                   9381: =item *
                   9382: 
                   9383: renameuserfile(): renames an existing userfile to a new name
                   9384: 
                   9385:   Args:
                   9386:    docuname: username or courseid of destination for the file
                   9387:    docudom: domain of user/course of destination for the file
                   9388:    old: current file name (including any subdirs under userfiles)
                   9389:    new: desired file name (including any subdirs under userfiles)
                   9390: 
                   9391: =item *
                   9392: 
                   9393: mkdiruserfile(): creates a directory is a userfiles dir
                   9394: 
                   9395:   Args:
                   9396:    docuname: username or courseid of destination for the file
                   9397:    docudom: domain of user/course of destination for the file
                   9398:    dir: dir to create (including any subdirs under userfiles)
                   9399: 
                   9400: =item *
                   9401: 
                   9402: removeuserfile(): removes a file that exists in userfiles
                   9403: 
                   9404:   Args:
                   9405:    docuname: username or courseid of destination for the file
                   9406:    docudom: domain of user/course of destination for the file
                   9407:    fname: filname to delete (including any subdirs under userfiles)
                   9408: 
                   9409: =item *
                   9410: 
                   9411: removeuploadedurl(): convience function for removeuserfile()
                   9412: 
                   9413:   Args:
                   9414:    url:  a full /uploaded/... url to delete
                   9415: 
1.747     albertel 9416: =item * 
                   9417: 
                   9418: get_portfile_permissions():
                   9419:   Args:
                   9420:     domain: domain of user or course contain the portfolio files
                   9421:     user: name of user or num of course contain the portfolio files
                   9422:   Returns:
                   9423:     hashref of a dump of the proper file_permissions.db
                   9424:    
                   9425: 
                   9426: =item * 
                   9427: 
                   9428: get_access_controls():
                   9429: 
                   9430: Args:
                   9431:   current_permissions: the hash ref returned from get_portfile_permissions()
                   9432:   group: (optional) the group you want the files associated with
                   9433:   file: (optional) the file you want access info on
                   9434: 
                   9435: Returns:
1.749     raeburn  9436:     a hash (keys are file names) of hashes containing
                   9437:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   9438:         values are XML containing access control settings (see below) 
1.747     albertel 9439: 
                   9440: Internal notes:
                   9441: 
1.749     raeburn  9442:  access controls are stored in file_permissions.db as key=value pairs.
                   9443:     key -> path to file/file_name\0uniqueID:scope_end_start
                   9444:         where scope -> public,guest,course,group,domains or users.
                   9445:               end -> UNIX time for end of access (0 -> no end date)
                   9446:               start -> UNIX time for start of access
                   9447: 
                   9448:     value -> XML description of access control
                   9449:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   9450:             <start></start>
                   9451:             <end></end>
                   9452: 
                   9453:             <password></password>  for scope type = guest
                   9454: 
                   9455:             <domain></domain>     for scope type = course or group
                   9456:             <number></number>
                   9457:             <roles id="">
                   9458:              <role></role>
                   9459:              <access></access>
                   9460:              <section></section>
                   9461:              <group></group>
                   9462:             </roles>
                   9463: 
                   9464:             <dom></dom>         for scope type = domains
                   9465: 
                   9466:             <users>             for scope type = users
                   9467:              <user>
                   9468:               <uname></uname>
                   9469:               <udom></udom>
                   9470:              </user>
                   9471:             </users>
                   9472:            </scope> 
                   9473:               
                   9474:  Access data is also aggregated for each file in an additional key=value pair:
                   9475:  key -> path to file/file_name\0accesscontrol 
                   9476:  value -> reference to hash
                   9477:           hash contains key = value pairs
                   9478:           where key = uniqueID:scope_end_start
                   9479:                 value = UNIX time record was last updated
                   9480: 
                   9481:           Used to improve speed of look-ups of access controls for each file.  
                   9482:  
                   9483:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   9484: 
                   9485: modify_access_controls():
                   9486: 
                   9487: Modifies access controls for a portfolio file
                   9488: Args
                   9489: 1. file name
                   9490: 2. reference to hash of required changes,
                   9491: 3. domain
                   9492: 4. username
                   9493:   where domain,username are the domain of the portfolio owner 
                   9494:   (either a user or a course) 
                   9495: 
                   9496: Returns:
                   9497: 1. result of additions or updates ('ok' or 'error', with error message). 
                   9498: 2. result of deletions ('ok' or 'error', with error message).
                   9499: 3. reference to hash of any new or updated access controls.
                   9500: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   9501:    key = integer (inbound ID)
                   9502:    value = uniqueID  
1.747     albertel 9503: 
1.608     albertel 9504: =back
                   9505: 
1.243     albertel 9506: =head2 HTTP Helper Routines
                   9507: 
                   9508: =over 4
                   9509: 
1.191     harris41 9510: =item *
                   9511: 
                   9512: escape() : unpack non-word characters into CGI-compatible hex codes
                   9513: 
                   9514: =item *
                   9515: 
                   9516: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   9517: 
1.243     albertel 9518: =back
                   9519: 
                   9520: =head1 PRIVATE SUBROUTINES
                   9521: 
                   9522: =head2 Underlying communication routines (Shouldn't call)
                   9523: 
                   9524: =over 4
                   9525: 
                   9526: =item *
                   9527: 
                   9528: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   9529: 
                   9530: =item *
                   9531: 
                   9532: reply() : uses subreply to send a message to remote machine, logs all failures
                   9533: 
                   9534: =item *
                   9535: 
                   9536: critical() : passes a critical message to another server; if cannot
                   9537: get through then place message in connection buffer directory and
                   9538: returns con_delayed, if incapable of saving message, returns
                   9539: con_failed
                   9540: 
                   9541: =item *
                   9542: 
                   9543: reconlonc() : tries to reconnect lonc client processes.
                   9544: 
                   9545: =back
                   9546: 
                   9547: =head2 Resource Access Logging
                   9548: 
                   9549: =over 4
                   9550: 
                   9551: =item *
                   9552: 
                   9553: flushcourselogs() : flush (save) buffer logs and access logs
                   9554: 
                   9555: =item *
                   9556: 
                   9557: courselog($what) : save message for course in hash
                   9558: 
                   9559: =item *
                   9560: 
                   9561: courseacclog($what) : save message for course using &courselog().  Perform
                   9562: special processing for specific resource types (problems, exams, quizzes, etc).
                   9563: 
1.191     harris41 9564: =item *
                   9565: 
                   9566: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   9567: as a PerlChildExitHandler
1.243     albertel 9568: 
                   9569: =back
                   9570: 
                   9571: =head2 Other
                   9572: 
                   9573: =over 4
                   9574: 
                   9575: =item *
                   9576: 
                   9577: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 9578: 
                   9579: =back
                   9580: 
                   9581: =cut
1.877     foxr     9582: 

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