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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.946   ! raeburn     4: # $Id: lonnet.pm,v 1.945 2008/02/29 21:01:24 raeburn 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.917     albertel  323: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    324: 	if (!$opened) {
1.915     albertel  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.917     albertel  365:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    366: 	if (!$opened) {
1.915     albertel  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: 
1.917     albertel  411:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    412:     return undef if (!$opened);
1.916     albertel  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.917     albertel  462:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    463:     if ($opened
1.915     albertel  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.917     albertel  484:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    485:     if ($opened
1.915     albertel  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: sub userload {
                    517:     my $numusers=0;
                    518:     {
                    519: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    520: 	my $filename;
                    521: 	my $curtime=time;
                    522: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  523: 	    next if ($filename eq '.' || $filename eq '..');
                    524: 	    next if ($filename =~ /publicuser_\d+\.id/);
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 {
1.923     raeburn  1050:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  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')) {
1.923     raeburn  1058:                 my $response;
                   1059:                 if ($item eq 'username') {                
                   1060:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   1061:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  1062:                                               $homeserver));
1.923     raeburn  1063:                 } elsif ($item eq 'id') {
                   1064:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   1065:                                               ':'.&escape($id).':'.$rulestr,
                   1066:                                               $homeserver));
1.945     raeburn  1067:                 } elsif ($item eq 'selfcreate') {
                   1068:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  1069:                                                &escape($udom).':'.&escape($uname).
                   1070:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  1071:                 }
1.912     raeburn  1072:                 if ($response ne 'refused') {
                   1073:                     my @pairs=split(/\&/,$response);
                   1074:                     foreach my $item (@pairs) {
                   1075:                         my ($key,$value)=split(/=/,$item,2);
                   1076:                         $key = &unescape($key);
                   1077:                         next if ($key =~ /^error: 2 /);
                   1078:                         $returnhash{$key}=&thaw_unescape($value);
                   1079:                     }
                   1080:                 }
                   1081:             }
                   1082:         }
                   1083:     }
                   1084:     return %returnhash;
                   1085: }
                   1086: 
                   1087: sub inst_userrules {
1.923     raeburn  1088:     my ($udom,$check) = @_;
1.912     raeburn  1089:     my (%ruleshash,@ruleorder);
                   1090:     if ($udom ne '') {
                   1091:         my $homeserver=&domain($udom,'primary');
                   1092:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1093:             my $response;
                   1094:             if ($check eq 'id') {
                   1095:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  1096:                                  $homeserver);
1.943     raeburn  1097:             } elsif ($check eq 'email') {
                   1098:                 $response=&reply('instemailrules:'.&escape($udom),
                   1099:                                  $homeserver);
1.923     raeburn  1100:             } else {
                   1101:                 $response=&reply('instuserrules:'.&escape($udom),
                   1102:                                  $homeserver);
                   1103:             }
1.912     raeburn  1104:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  1105:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  1106:                 ($response ne 'no_such_host')) {
                   1107:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1108:                 my @pairs=split(/\&/,$hashitems);
                   1109:                 foreach my $item (@pairs) {
                   1110:                     my ($key,$value)=split(/=/,$item,2);
                   1111:                     $key = &unescape($key);
                   1112:                     next if ($key =~ /^error: 2 /);
                   1113:                     $ruleshash{$key}=&thaw_unescape($value);
                   1114:                 }
                   1115:                 my @esc_order = split(/\&/,$orderitems);
                   1116:                 foreach my $item (@esc_order) {
                   1117:                     push(@ruleorder,&unescape($item));
                   1118:                 }
                   1119:             }
                   1120:         }
                   1121:     }
                   1122:     return (\%ruleshash,\@ruleorder);
                   1123: }
                   1124: 
1.943     raeburn  1125: # ------------------------- Get Authentication and Language Defaults for Domain
                   1126: 
                   1127: sub get_domain_defaults {
                   1128:     my ($domain) = @_;
                   1129:     my $cachetime = 60*60*24;
                   1130:     my ($defauthtype,$defautharg,$deflang);
                   1131:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   1132:     if (defined($cached)) {
                   1133:         if (ref($result) eq 'HASH') {
                   1134:             return %{$result};
                   1135:         }
                   1136:     }
                   1137:     my %domdefaults;
                   1138:     my %domconfig =
                   1139:          &Apache::lonnet::get_dom('configuration',['defaults'],$domain);
                   1140:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   1141:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   1142:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   1143:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
                   1144:     } else {
                   1145:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   1146:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   1147:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   1148:     }
                   1149:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
                   1150:                                   $cachetime);
                   1151:     return %domdefaults;
                   1152: }
                   1153: 
1.344     www      1154: # --------------------------------------------------- Assign a key to a student
                   1155: 
                   1156: sub assign_access_key {
1.364     www      1157: #
                   1158: # a valid key looks like uname:udom#comments
                   1159: # comments are being appended
                   1160: #
1.498     www      1161:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   1162:     $kdom=
1.620     albertel 1163:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      1164:     $knum=
1.620     albertel 1165:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      1166:     $cdom=
1.620     albertel 1167:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1168:     $cnum=
1.620     albertel 1169:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1170:     $udom=$env{'user.name'} unless (defined($udom));
                   1171:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      1172:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      1173:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 1174:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      1175:                                                   # assigned to this person
                   1176:                                                   # - this should not happen,
1.345     www      1177:                                                   # unless something went wrong
                   1178:                                                   # the first time around
                   1179: # ready to assign
1.364     www      1180:         $logentry=$1.'; '.$logentry;
1.496     www      1181:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      1182:                                                  $kdom,$knum) eq 'ok') {
1.345     www      1183: # key now belongs to user
1.346     www      1184: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      1185:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
                   1186:                 &appenv('environment.'.$envkey => $ckey);
                   1187:                 return 'ok';
                   1188:             } else {
                   1189:                 return 
                   1190:   'error: Count not permanently assign key, will need to be re-entered later.';
                   1191: 	    }
                   1192:         } else {
                   1193:             return 'error: Could not assign key, try again later.';
                   1194:         }
1.364     www      1195:     } elsif (!$existing{$ckey}) {
1.345     www      1196: # the key does not exist
                   1197: 	return 'error: The key does not exist';
                   1198:     } else {
                   1199: # the key is somebody else's
                   1200: 	return 'error: The key is already in use';
                   1201:     }
1.344     www      1202: }
                   1203: 
1.364     www      1204: # ------------------------------------------ put an additional comment on a key
                   1205: 
                   1206: sub comment_access_key {
                   1207: #
                   1208: # a valid key looks like uname:udom#comments
                   1209: # comments are being appended
                   1210: #
                   1211:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   1212:     $cdom=
1.620     albertel 1213:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      1214:     $cnum=
1.620     albertel 1215:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      1216:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   1217:     if ($existing{$ckey}) {
                   1218:         $existing{$ckey}.='; '.$logentry;
                   1219: # ready to assign
1.367     www      1220:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      1221:                                                  $cdom,$cnum) eq 'ok') {
                   1222: 	    return 'ok';
                   1223:         } else {
                   1224: 	    return 'error: Count not store comment.';
                   1225:         }
                   1226:     } else {
                   1227: # the key does not exist
                   1228: 	return 'error: The key does not exist';
                   1229:     }
                   1230: }
                   1231: 
1.344     www      1232: # ------------------------------------------------------ Generate a set of keys
                   1233: 
                   1234: sub generate_access_keys {
1.364     www      1235:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      1236:     $cdom=
1.620     albertel 1237:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1238:     $cnum=
1.620     albertel 1239:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      1240:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      1241:     unless (($cdom) && ($cnum)) { return 0; }
                   1242:     if ($number>10000) { return 0; }
                   1243:     sleep(2); # make sure don't get same seed twice
                   1244:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   1245:     my $total=0;
                   1246:     for (my $i=1;$i<=$number;$i++) {
                   1247:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   1248:                   sprintf("%lx",int(100000*rand)).'-'.
                   1249:                   sprintf("%lx",int(100000*rand));
                   1250:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   1251:        $newkey=~s/0/h/g; # and also 0 and O
                   1252:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   1253:        if ($existing{$newkey}) {
                   1254:            $i--;
                   1255:        } else {
1.364     www      1256: 	  if (&put('accesskeys',
                   1257:               { $newkey => '# generated '.localtime().
1.620     albertel 1258:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      1259:                            '; '.$logentry },
                   1260: 		   $cdom,$cnum) eq 'ok') {
1.344     www      1261:               $total++;
                   1262: 	  }
                   1263:        }
                   1264:     }
1.620     albertel 1265:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      1266:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   1267:     return $total;
                   1268: }
                   1269: 
                   1270: # ------------------------------------------------------- Validate an accesskey
                   1271: 
                   1272: sub validate_access_key {
                   1273:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   1274:     $cdom=
1.620     albertel 1275:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1276:     $cnum=
1.620     albertel 1277:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1278:     $udom=$env{'user.domain'} unless (defined($udom));
                   1279:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      1280:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 1281:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      1282: }
                   1283: 
                   1284: # ------------------------------------- Find the section of student in a course
1.652     albertel 1285: sub devalidate_getsection_cache {
                   1286:     my ($udom,$unam,$courseid)=@_;
                   1287:     my $hashid="$udom:$unam:$courseid";
                   1288:     &devalidate_cache_new('getsection',$hashid);
                   1289: }
1.298     matthew  1290: 
1.815     albertel 1291: sub courseid_to_courseurl {
                   1292:     my ($courseid) = @_;
                   1293:     #already url style courseid
                   1294:     return $courseid if ($courseid =~ m{^/});
                   1295: 
                   1296:     if (exists($env{'course.'.$courseid.'.num'})) {
                   1297: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   1298: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   1299: 	return "/$cdom/$cnum";
                   1300:     }
                   1301: 
                   1302:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   1303:     if (exists($courseinfo{'num'})) {
                   1304: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   1305:     }
                   1306: 
                   1307:     return undef;
                   1308: }
                   1309: 
1.298     matthew  1310: sub getsection {
                   1311:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 1312:     my $cachetime=1800;
1.551     albertel 1313: 
                   1314:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 1315:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 1316:     if (defined($cached)) { return $result; }
                   1317: 
1.298     matthew  1318:     my %Pending; 
                   1319:     my %Expired;
                   1320:     #
                   1321:     # Each role can either have not started yet (pending), be active, 
                   1322:     #    or have expired.
                   1323:     #
                   1324:     # If there is an active role, we are done.
                   1325:     #
                   1326:     # If there is more than one role which has not started yet, 
                   1327:     #     choose the one which will start sooner
                   1328:     # If there is one role which has not started yet, return it.
                   1329:     #
                   1330:     # If there is more than one expired role, choose the one which ended last.
                   1331:     # If there is a role which has expired, return it.
                   1332:     #
1.815     albertel 1333:     $courseid = &courseid_to_courseurl($courseid);
1.817     raeburn  1334:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
                   1335:     foreach my $key (keys(%roleshash)) {
1.479     albertel 1336:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  1337:         my $section=$1;
                   1338:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  1339:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  1340:         my $now=time;
1.548     albertel 1341:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  1342:             $Expired{$end}=$section;
                   1343:             next;
                   1344:         }
1.548     albertel 1345:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  1346:             $Pending{$start}=$section;
                   1347:             next;
                   1348:         }
1.599     albertel 1349:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  1350:     }
                   1351:     #
                   1352:     # Presumedly there will be few matching roles from the above
                   1353:     # loop and the sorting time will be negligible.
                   1354:     if (scalar(keys(%Pending))) {
                   1355:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 1356:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  1357:     } 
                   1358:     if (scalar(keys(%Expired))) {
                   1359:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   1360:         my $time = pop(@sorted);
1.599     albertel 1361:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  1362:     }
1.599     albertel 1363:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  1364: }
1.70      www      1365: 
1.599     albertel 1366: sub save_cache {
                   1367:     &purge_remembered();
1.722     albertel 1368:     #&Apache::loncommon::validate_page();
1.620     albertel 1369:     undef(%env);
1.780     albertel 1370:     undef($env_loaded);
1.599     albertel 1371: }
1.452     albertel 1372: 
1.599     albertel 1373: my $to_remember=-1;
                   1374: my %remembered;
                   1375: my %accessed;
                   1376: my $kicks=0;
                   1377: my $hits=0;
1.849     albertel 1378: sub make_key {
                   1379:     my ($name,$id) = @_;
1.872     albertel 1380:     if (length($id) > 65 
                   1381: 	&& length(&escape($id)) > 200) {
                   1382: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   1383:     }
1.849     albertel 1384:     return &escape($name.':'.$id);
                   1385: }
                   1386: 
1.599     albertel 1387: sub devalidate_cache_new {
                   1388:     my ($name,$id,$debug) = @_;
                   1389:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 1390:     $id=&make_key($name,$id);
1.599     albertel 1391:     $memcache->delete($id);
                   1392:     delete($remembered{$id});
                   1393:     delete($accessed{$id});
                   1394: }
                   1395: 
                   1396: sub is_cached_new {
                   1397:     my ($name,$id,$debug) = @_;
1.849     albertel 1398:     $id=&make_key($name,$id);
1.599     albertel 1399:     if (exists($remembered{$id})) {
                   1400: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                   1401: 	$accessed{$id}=[&gettimeofday()];
                   1402: 	$hits++;
                   1403: 	return ($remembered{$id},1);
                   1404:     }
                   1405:     my $value = $memcache->get($id);
                   1406:     if (!(defined($value))) {
                   1407: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 1408: 	return (undef,undef);
1.416     albertel 1409:     }
1.599     albertel 1410:     if ($value eq '__undef__') {
                   1411: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   1412: 	$value=undef;
                   1413:     }
                   1414:     &make_room($id,$value,$debug);
                   1415:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   1416:     return ($value,1);
                   1417: }
                   1418: 
                   1419: sub do_cache_new {
                   1420:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 1421:     $id=&make_key($name,$id);
1.599     albertel 1422:     my $setvalue=$value;
                   1423:     if (!defined($setvalue)) {
                   1424: 	$setvalue='__undef__';
                   1425:     }
1.623     albertel 1426:     if (!defined($time) ) {
                   1427: 	$time=600;
                   1428:     }
1.599     albertel 1429:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 1430:     my $result = $memcache->set($id,$setvalue,$time);
                   1431:     if (! $result) {
1.872     albertel 1432: 	&logthis("caching of id -> $id  failed");
1.910     albertel 1433: 	$memcache->disconnect_all();
1.872     albertel 1434:     }
1.600     albertel 1435:     # need to make a copy of $value
1.919     albertel 1436:     &make_room($id,$value,$debug);
1.599     albertel 1437:     return $value;
                   1438: }
                   1439: 
                   1440: sub make_room {
                   1441:     my ($id,$value,$debug)=@_;
1.919     albertel 1442: 
                   1443:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   1444:                                     : $value;
1.599     albertel 1445:     if ($to_remember<0) { return; }
                   1446:     $accessed{$id}=[&gettimeofday()];
                   1447:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   1448:     my $to_kick;
                   1449:     my $max_time=0;
                   1450:     foreach my $other (keys(%accessed)) {
                   1451: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   1452: 	    $to_kick=$other;
                   1453: 	    $max_time=&tv_interval($accessed{$other});
                   1454: 	}
                   1455:     }
                   1456:     delete($remembered{$to_kick});
                   1457:     delete($accessed{$to_kick});
                   1458:     $kicks++;
                   1459:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 1460:     return;
                   1461: }
                   1462: 
1.599     albertel 1463: sub purge_remembered {
1.604     albertel 1464:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   1465:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 1466:     undef(%remembered);
                   1467:     undef(%accessed);
1.428     albertel 1468: }
1.70      www      1469: # ------------------------------------- Read an entry from a user's environment
                   1470: 
                   1471: sub userenvironment {
                   1472:     my ($udom,$unam,@what)=@_;
                   1473:     my %returnhash=();
                   1474:     my @answer=split(/\&/,
                   1475:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
                   1476:                       &homeserver($unam,$udom)));
                   1477:     my $i;
                   1478:     for ($i=0;$i<=$#what;$i++) {
                   1479: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                   1480:     }
                   1481:     return %returnhash;
1.1       albertel 1482: }
                   1483: 
1.617     albertel 1484: # ---------------------------------------------------------- Get a studentphoto
                   1485: sub studentphoto {
                   1486:     my ($udom,$unam,$ext) = @_;
                   1487:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1488:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1489:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1490:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1491:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1492:             } else {
                   1493:                 my ($result,$perm_reqd)=
1.707     albertel 1494: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1495:                 if ($result eq 'ok') {
                   1496:                     if (!($perm_reqd eq 'yes')) {
                   1497:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1498:                     }
                   1499:                 }
                   1500:             }
                   1501:         }
                   1502:     } else {
                   1503:         my ($result,$perm_reqd) = 
1.707     albertel 1504: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1505:         if ($result eq 'ok') {
                   1506:             if (!($perm_reqd eq 'yes')) {
                   1507:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1508:             }
                   1509:         }
                   1510:     }
                   1511:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1512: }
                   1513: 
                   1514: sub retrievestudentphoto {
                   1515:     my ($udom,$unam,$ext,$type) = @_;
                   1516:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1517:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1518:     if ($ret eq 'ok') {
                   1519:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1520:         if ($type eq 'thumbnail') {
                   1521:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1522:         }
                   1523:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1524:         return $tokenurl;
                   1525:     } else {
                   1526:         if ($type eq 'thumbnail') {
                   1527:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1528:         } else { 
                   1529:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1530:         }
1.617     albertel 1531:     }
                   1532: }
                   1533: 
1.263     www      1534: # -------------------------------------------------------------------- New chat
                   1535: 
                   1536: sub chatsend {
1.724     raeburn  1537:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1538:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1539:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1540:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1541:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1542: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1543: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1544: }
                   1545: 
                   1546: # ------------------------------------------ Find current version of a resource
                   1547: 
                   1548: sub getversion {
                   1549:     my $fname=&clutter(shift);
                   1550:     unless ($fname=~/^\/res\//) { return -1; }
                   1551:     return &currentversion(&filelocation('',$fname));
                   1552: }
                   1553: 
                   1554: sub currentversion {
                   1555:     my $fname=shift;
1.599     albertel 1556:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1557:     if (defined($cached)) { return $result; }
1.292     www      1558:     my $author=$fname;
                   1559:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1560:     my ($udom,$uname)=split(/\//,$author);
                   1561:     my $home=homeserver($uname,$udom);
                   1562:     if ($home eq 'no_host') { 
                   1563:         return -1; 
                   1564:     }
                   1565:     my $answer=reply("currentversion:$fname",$home);
                   1566:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1567: 	return -1;
                   1568:     }
1.599     albertel 1569:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1570: }
                   1571: 
1.1       albertel 1572: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1573: 
1.1       albertel 1574: sub subscribe {
                   1575:     my $fname=shift;
1.761     raeburn  1576:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1577:     $fname=~s/[\n\r]//g;
1.1       albertel 1578:     my $author=$fname;
                   1579:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1580:     my ($udom,$uname)=split(/\//,$author);
                   1581:     my $home=homeserver($uname,$udom);
1.335     albertel 1582:     if ($home eq 'no_host') {
                   1583:         return 'not_found';
1.1       albertel 1584:     }
                   1585:     my $answer=reply("sub:$fname",$home);
1.64      www      1586:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1587: 	$answer.=' by '.$home;
                   1588:     }
1.1       albertel 1589:     return $answer;
                   1590: }
                   1591:     
1.8       www      1592: # -------------------------------------------------------------- Replicate file
                   1593: 
                   1594: sub repcopy {
                   1595:     my $filename=shift;
1.23      www      1596:     $filename=~s/\/+/\//g;
1.607     raeburn  1597:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1598:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1599:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1600: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1601: 	return &repcopy_userfile($filename);
                   1602:     }
1.532     albertel 1603:     $filename=~s/[\n\r]//g;
1.8       www      1604:     my $transname="$filename.in.transfer";
1.828     www      1605: # FIXME: this should flock
1.607     raeburn  1606:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1607:     my $remoteurl=subscribe($filename);
1.64      www      1608:     if ($remoteurl =~ /^con_lost by/) {
                   1609: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1610:            return 'unavailable';
1.8       www      1611:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1612: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1613: 	   return 'not_found';
1.64      www      1614:     } elsif ($remoteurl =~ /^rejected by/) {
                   1615: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1616:            return 'forbidden';
1.20      www      1617:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1618:            return 'ok';
1.8       www      1619:     } else {
1.290     www      1620:         my $author=$filename;
                   1621:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1622:         my ($udom,$uname)=split(/\//,$author);
                   1623:         my $home=homeserver($uname,$udom);
                   1624:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1625:            my @parts=split(/\//,$filename);
                   1626:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1627:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1628:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1629: 	       return 'bad_request';
1.8       www      1630:            }
                   1631:            my $count;
                   1632:            for ($count=5;$count<$#parts;$count++) {
                   1633:                $path.="/$parts[$count]";
                   1634:                if ((-e $path)!=1) {
                   1635: 		   mkdir($path,0777);
                   1636:                }
                   1637:            }
                   1638:            my $ua=new LWP::UserAgent;
                   1639:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1640:            my $response=$ua->request($request,$transname);
                   1641:            if ($response->is_error()) {
                   1642: 	       unlink($transname);
                   1643:                my $message=$response->status_line;
1.672     albertel 1644:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      1645:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1646:                return 'unavailable';
1.8       www      1647:            } else {
1.16      www      1648: 	       if ($remoteurl!~/\.meta$/) {
                   1649:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1650:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1651:                   if ($mresponse->is_error()) {
                   1652: 		      unlink($filename.'.meta');
                   1653:                       &logthis(
1.672     albertel 1654:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      1655:                   }
                   1656: 	       }
1.8       www      1657:                rename($transname,$filename);
1.607     raeburn  1658:                return 'ok';
1.8       www      1659:            }
1.290     www      1660:        }
1.8       www      1661:     }
1.330     www      1662: }
                   1663: 
                   1664: # ------------------------------------------------ Get server side include body
                   1665: sub ssi_body {
1.381     albertel 1666:     my ($filelink,%form)=@_;
1.606     matthew  1667:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1668:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1669:     }
1.330     www      1670:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
1.381     albertel 1671:                                      &ssi($filelink,%form));
1.778     albertel 1672:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1673:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 1674:     $output=~s/\<\/body\s*\>.*?$//si;
1.330     www      1675:     return $output;
1.8       www      1676: }
                   1677: 
1.15      www      1678: # --------------------------------------------------------- Server Side Include
                   1679: 
1.782     albertel 1680: sub absolute_url {
                   1681:     my ($host_name) = @_;
                   1682:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   1683:     if ($host_name eq '') {
                   1684: 	$host_name = $ENV{'SERVER_NAME'};
                   1685:     }
                   1686:     return $protocol.$host_name;
                   1687: }
                   1688: 
1.942     foxr     1689: #
                   1690: #   Server side include.
                   1691: # Parameters:
                   1692: #  fn     Possibly encrypted resource name/id.
                   1693: #  form   Hash that describes how the rendering should be done
                   1694: #         and other things.
1.944     foxr     1695: # Returns:
                   1696: #   Scalar context: The content of the reply.
                   1697: #   Array context:  2 element list of the content and the full response variable.
1.942     foxr     1698: #     
                   1699: # Returns:
                   1700: #    The content of the response.
1.15      www      1701: sub ssi {
                   1702: 
1.944     foxr     1703:     my ($fn,%form)=@_;
                   1704:     my $count = scalar(@_);
                   1705:     
1.15      www      1706: 
                   1707:     my $ua=new LWP::UserAgent;
1.23      www      1708:     
                   1709:     my $request;
1.711     albertel 1710: 
                   1711:     $form{'no_update_last_known'}=1;
1.895     albertel 1712:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      1713:     if (%form) {
1.782     albertel 1714:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.201     albertel 1715:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www      1716:     } else {
1.782     albertel 1717:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      1718:     }
                   1719: 
1.15      www      1720:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1721:     my $response=$ua->request($request);
1.944     foxr     1722:     my $status = $response->code;
1.15      www      1723: 
1.944     foxr     1724:     if (wantarray) {
                   1725: 	return ($response->content, $response);
                   1726:     } else {
                   1727: 	return $response->content;
1.942     foxr     1728:     }
1.324     www      1729: }
                   1730: 
                   1731: sub externalssi {
                   1732:     my ($url)=@_;
                   1733:     my $ua=new LWP::UserAgent;
                   1734:     my $request=new HTTP::Request('GET',$url);
                   1735:     my $response=$ua->request($request);
1.15      www      1736:     return $response->content;
                   1737: }
1.254     www      1738: 
1.492     albertel 1739: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1740: 
                   1741: sub allowuploaded {
                   1742:     my ($srcurl,$url)=@_;
                   1743:     $url=&clutter(&declutter($url));
                   1744:     my $dir=$url;
                   1745:     $dir=~s/\/[^\/]+$//;
                   1746:     my %httpref=();
                   1747:     my $httpurl=&hreflocation('',$url);
                   1748:     $httpref{'httpref.'.$httpurl}=$srcurl;
                   1749:     &Apache::lonnet::appenv(%httpref);
1.254     www      1750: }
1.477     raeburn  1751: 
1.478     albertel 1752: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 1753: # input: action, courseID, current domain, intended
1.637     raeburn  1754: #        path to file, source of file, instruction to parse file for objects,
                   1755: #        ref to hash for embedded objects,
                   1756: #        ref to hash for codebase of java objects.
                   1757: #
1.485     raeburn  1758: # output: url to file (if action was uploaddoc), 
                   1759: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  1760: #
1.478     albertel 1761: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   1762: # course.
1.477     raeburn  1763: #
1.478     albertel 1764: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1765: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   1766: #          course's home server.
1.477     raeburn  1767: #
1.478     albertel 1768: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   1769: #          be copied from $source (current location) to 
                   1770: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1771: #         and will then be copied to
                   1772: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   1773: #         course's home server.
1.485     raeburn  1774: #
1.481     raeburn  1775: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 1776: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  1777: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1778: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   1779: #         in course's home server.
1.637     raeburn  1780: #
1.477     raeburn  1781: 
                   1782: sub process_coursefile {
1.638     albertel 1783:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  1784:     my $fetchresult;
1.638     albertel 1785:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  1786:     if ($action eq 'propagate') {
1.638     albertel 1787:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1788: 			     $home);
1.481     raeburn  1789:     } else {
1.477     raeburn  1790:         my $fpath = '';
                   1791:         my $fname = $file;
1.478     albertel 1792:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  1793:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  1794:         my $filepath = &build_filepath($fpath);
1.481     raeburn  1795:         if ($action eq 'copy') {
                   1796:             if ($source eq '') {
                   1797:                 $fetchresult = 'no source file';
                   1798:                 return $fetchresult;
                   1799:             } else {
                   1800:                 my $destination = $filepath.'/'.$fname;
                   1801:                 rename($source,$destination);
                   1802:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1803:                                  $home);
1.481     raeburn  1804:             }
                   1805:         } elsif ($action eq 'uploaddoc') {
                   1806:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 1807:             print $fh $env{'form.'.$source};
1.481     raeburn  1808:             close($fh);
1.637     raeburn  1809:             if ($parser eq 'parse') {
                   1810:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
                   1811:                 unless ($parse_result eq 'ok') {
                   1812:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   1813:                 }
                   1814:             }
1.477     raeburn  1815:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1816:                                  $home);
1.481     raeburn  1817:             if ($fetchresult eq 'ok') {
                   1818:                 return '/uploaded/'.$fpath.'/'.$fname;
                   1819:             } else {
                   1820:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1821:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  1822:                 return '/adm/notfound.html';
                   1823:             }
1.477     raeburn  1824:         }
                   1825:     }
1.485     raeburn  1826:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  1827:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1828:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  1829:     }
                   1830:     return $fetchresult;
                   1831: }
                   1832: 
1.637     raeburn  1833: sub build_filepath {
                   1834:     my ($fpath) = @_;
                   1835:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   1836:     unless ($fpath eq '') {
                   1837:         my @parts=split('/',$fpath);
                   1838:         foreach my $part (@parts) {
                   1839:             $filepath.= '/'.$part;
                   1840:             if ((-e $filepath)!=1) {
                   1841:                 mkdir($filepath,0777);
                   1842:             }
                   1843:         }
                   1844:     }
                   1845:     return $filepath;
                   1846: }
                   1847: 
                   1848: sub store_edited_file {
1.638     albertel 1849:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  1850:     my $file = $primary_url;
                   1851:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   1852:     my $fpath = '';
                   1853:     my $fname = $file;
                   1854:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   1855:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   1856:     my $filepath = &build_filepath($fpath);
                   1857:     open(my $fh,'>'.$filepath.'/'.$fname);
                   1858:     print $fh $content;
                   1859:     close($fh);
1.638     albertel 1860:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  1861:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1862: 			  $home);
1.637     raeburn  1863:     if ($$fetchresult eq 'ok') {
                   1864:         return '/uploaded/'.$fpath.'/'.$fname;
                   1865:     } else {
1.638     albertel 1866:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   1867: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  1868:         return '/adm/notfound.html';
                   1869:     }
                   1870: }
                   1871: 
1.531     albertel 1872: sub clean_filename {
1.831     albertel 1873:     my ($fname,$args)=@_;
1.315     www      1874: # Replace Windows backslashes by forward slashes
1.257     www      1875:     $fname=~s/\\/\//g;
1.831     albertel 1876:     if (!$args->{'keep_path'}) {
                   1877:         # Get rid of everything but the actual filename
                   1878: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   1879:     }
1.315     www      1880: # Replace spaces by underscores
                   1881:     $fname=~s/\s+/\_/g;
                   1882: # Replace all other weird characters by nothing
1.831     albertel 1883:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 1884: # Replace all .\d. sequences with _\d. so they no longer look like version
                   1885: # numbers
                   1886:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 1887:     return $fname;
                   1888: }
                   1889: 
1.608     albertel 1890: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 1891: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 1892: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 1893: #        $coursedoc - if true up to the current course
                   1894: #                     if false
                   1895: #        $subdir - directory in userfile to store the file into
1.858     raeburn  1896: #        $parser - instruction to parse file for objects ($parser = parse)    
                   1897: #        $allfiles - reference to hash for embedded objects
                   1898: #        $codebase - reference to hash for codebase of java objects
                   1899: #        $desuname - username for permanent storage of uploaded file
                   1900: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  1901: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   1902: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.858     raeburn  1903: # 
1.686     albertel 1904: # output: url of file in userspace, or error: <message> 
                   1905: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 1906: 
                   1907: 
1.531     albertel 1908: sub userfileupload {
1.860     raeburn  1909:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
                   1910:         $destudom,$thumbwidth,$thumbheight)=@_;
1.531     albertel 1911:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 1912:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 1913:     $fname=&clean_filename($fname);
1.315     www      1914: # See if there is anything left
1.257     www      1915:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 1916:     chop($env{'form.'.$formname});
1.523     raeburn  1917:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   1918:         my $now = time;
                   1919:         my $filepath = 'tmp/helprequests/'.$now;
                   1920:         my @parts=split(/\//,$filepath);
                   1921:         my $fullpath = $perlvar{'lonDaemons'};
                   1922:         for (my $i=0;$i<@parts;$i++) {
                   1923:             $fullpath .= '/'.$parts[$i];
                   1924:             if ((-e $fullpath)!=1) {
                   1925:                 mkdir($fullpath,0777);
                   1926:             }
                   1927:         }
                   1928:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 1929:         print $fh $env{'form.'.$formname};
1.523     raeburn  1930:         close($fh);
1.741     raeburn  1931:         return $fullpath.'/'.$fname;
                   1932:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   1933:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   1934:                        '_'.$env{'user.domain'}.'/pending';
                   1935:         my @parts=split(/\//,$filepath);
                   1936:         my $fullpath = $perlvar{'lonDaemons'};
                   1937:         for (my $i=0;$i<@parts;$i++) {
                   1938:             $fullpath .= '/'.$parts[$i];
                   1939:             if ((-e $fullpath)!=1) {
                   1940:                 mkdir($fullpath,0777);
                   1941:             }
                   1942:         }
                   1943:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   1944:         print $fh $env{'form.'.$formname};
                   1945:         close($fh);
                   1946:         return $fullpath.'/'.$fname;
1.523     raeburn  1947:     }
1.719     banghart 1948:     
1.258     www      1949: # Create the directory if not present
1.493     albertel 1950:     $fname="$subdir/$fname";
1.259     www      1951:     if ($coursedoc) {
1.638     albertel 1952: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1953: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  1954:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 1955:             return &finishuserfileupload($docuname,$docudom,
                   1956: 					 $formname,$fname,$parser,$allfiles,
1.860     raeburn  1957: 					 $codebase,$thumbwidth,$thumbheight);
1.481     raeburn  1958:         } else {
1.620     albertel 1959:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 1960:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   1961: 				       $fname,$formname,$parser,
                   1962: 				       $allfiles,$codebase);
1.481     raeburn  1963:         }
1.719     banghart 1964:     } elsif (defined($destuname)) {
                   1965:         my $docuname=$destuname;
                   1966:         my $docudom=$destudom;
1.860     raeburn  1967: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   1968: 				     $parser,$allfiles,$codebase,
                   1969:                                      $thumbwidth,$thumbheight);
1.719     banghart 1970:         
1.259     www      1971:     } else {
1.638     albertel 1972:         my $docuname=$env{'user.name'};
                   1973:         my $docudom=$env{'user.domain'};
1.714     raeburn  1974:         if (exists($env{'form.group'})) {
                   1975:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1976:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1977:         }
1.860     raeburn  1978: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   1979: 				     $parser,$allfiles,$codebase,
                   1980:                                      $thumbwidth,$thumbheight);
1.259     www      1981:     }
1.271     www      1982: }
                   1983: 
                   1984: sub finishuserfileupload {
1.860     raeburn  1985:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
                   1986:         $thumbwidth,$thumbheight) = @_;
1.477     raeburn  1987:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      1988:     my $filepath=$perlvar{'lonDocRoot'};
1.860     raeburn  1989:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 1990:     $file=$fname;
                   1991:     if ($fname=~m|/|) {
                   1992:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   1993: 	$path.=$fnamepath.'/';
                   1994:     }
1.259     www      1995:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      1996:     my $count;
                   1997:     for ($count=4;$count<=$#parts;$count++) {
                   1998:         $filepath.="/$parts[$count]";
                   1999:         if ((-e $filepath)!=1) {
                   2000: 	    mkdir($filepath,0777);
                   2001:         }
                   2002:     }
                   2003: # Save the file
                   2004:     {
1.701     albertel 2005: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   2006: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   2007: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   2008: 	    return '/adm/notfound.html';
                   2009: 	}
                   2010: 	if (!print FH ($env{'form.'.$formname})) {
                   2011: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   2012: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   2013: 	    return '/adm/notfound.html';
                   2014: 	}
1.570     albertel 2015: 	close(FH);
1.258     www      2016:     }
1.637     raeburn  2017:     if ($parser eq 'parse') {
1.638     albertel 2018:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
                   2019: 						   $codebase);
1.637     raeburn  2020:         unless ($parse_result eq 'ok') {
1.638     albertel 2021:             &logthis('Failed to parse '.$filepath.$file.
                   2022: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  2023:         }
                   2024:     }
1.860     raeburn  2025:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   2026:         my $input = $filepath.'/'.$file;
                   2027:         my $output = $filepath.'/'.'tn-'.$file;
                   2028:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   2029:         system("convert -sample $thumbsize $input $output");
                   2030:         if (-e $filepath.'/'.'tn-'.$file) {
                   2031:             $fetchthumb  = 1; 
                   2032:         }
                   2033:     }
1.858     raeburn  2034:  
1.259     www      2035: # Notify homeserver to grep it
                   2036: #
1.638     albertel 2037:     my $docuhome=&homeserver($docuname,$docudom);
1.494     albertel 2038:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      2039:     if ($fetchresult eq 'ok') {
1.860     raeburn  2040:         if ($fetchthumb) {
                   2041:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   2042:             if ($thumbresult ne 'ok') {
                   2043:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   2044:                          $docuhome.': '.$thumbresult);
                   2045:             }
                   2046:         }
1.259     www      2047: #
1.258     www      2048: # Return the URL to it
1.494     albertel 2049:         return '/uploaded/'.$path.$file;
1.263     www      2050:     } else {
1.494     albertel 2051:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   2052: 		 ': '.$fetchresult);
1.263     www      2053:         return '/adm/notfound.html';
1.858     raeburn  2054:     }
1.493     albertel 2055: }
                   2056: 
1.637     raeburn  2057: sub extract_embedded_items {
1.648     raeburn  2058:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
1.637     raeburn  2059:     my @state = ();
                   2060:     my %javafiles = (
                   2061:                       codebase => '',
                   2062:                       code => '',
                   2063:                       archive => ''
                   2064:                     );
                   2065:     my %mediafiles = (
                   2066:                       src => '',
                   2067:                       movie => '',
                   2068:                      );
1.648     raeburn  2069:     my $p;
                   2070:     if ($content) {
                   2071:         $p = HTML::LCParser->new($content);
                   2072:     } else {
                   2073:         $p = HTML::LCParser->new($filepath.'/'.$file);
                   2074:     }
1.641     albertel 2075:     while (my $t=$p->get_token()) {
1.640     albertel 2076: 	if ($t->[0] eq 'S') {
                   2077: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 2078: 	    push(@state, $tagname);
1.648     raeburn  2079:             if (lc($tagname) eq 'allow') {
                   2080:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   2081:             }
1.640     albertel 2082: 	    if (lc($tagname) eq 'img') {
                   2083: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   2084: 	    }
1.886     albertel 2085: 	    if (lc($tagname) eq 'a') {
                   2086: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   2087: 	    }
1.645     raeburn  2088:             if (lc($tagname) eq 'script') {
                   2089:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   2090:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   2091:                 } else {
                   2092:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   2093:                 }
                   2094:             }
                   2095:             if (lc($tagname) eq 'link') {
                   2096:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   2097:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   2098:                 }
                   2099:             }
1.640     albertel 2100: 	    if (lc($tagname) eq 'object' ||
                   2101: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   2102: 		foreach my $item (keys(%javafiles)) {
                   2103: 		    $javafiles{$item} = '';
                   2104: 		}
                   2105: 	    }
                   2106: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   2107: 		my $name = lc($attr->{'name'});
                   2108: 		foreach my $item (keys(%javafiles)) {
                   2109: 		    if ($name eq $item) {
                   2110: 			$javafiles{$item} = $attr->{'value'};
                   2111: 			last;
                   2112: 		    }
                   2113: 		}
                   2114: 		foreach my $item (keys(%mediafiles)) {
                   2115: 		    if ($name eq $item) {
                   2116: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   2117: 			last;
                   2118: 		    }
                   2119: 		}
                   2120: 	    }
                   2121: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   2122: 		foreach my $item (keys(%javafiles)) {
                   2123: 		    if ($attr->{$item}) {
                   2124: 			$javafiles{$item} = $attr->{$item};
                   2125: 			last;
                   2126: 		    }
                   2127: 		}
                   2128: 		foreach my $item (keys(%mediafiles)) {
                   2129: 		    if ($attr->{$item}) {
                   2130: 			&add_filetype($allfiles,$attr->{$item},$item);
                   2131: 			last;
                   2132: 		    }
                   2133: 		}
                   2134: 	    }
                   2135: 	} elsif ($t->[0] eq 'E') {
                   2136: 	    my ($tagname) = ($t->[1]);
                   2137: 	    if ($javafiles{'codebase'} ne '') {
                   2138: 		$javafiles{'codebase'} .= '/';
                   2139: 	    }  
                   2140: 	    if (lc($tagname) eq 'applet' ||
                   2141: 		lc($tagname) eq 'object' ||
                   2142: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   2143: 		) {
                   2144: 		foreach my $item (keys(%javafiles)) {
                   2145: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   2146: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   2147: 			&add_filetype($allfiles,$file,$item);
                   2148: 		    }
                   2149: 		}
                   2150: 	    } 
                   2151: 	    pop @state;
                   2152: 	}
                   2153:     }
1.637     raeburn  2154:     return 'ok';
                   2155: }
                   2156: 
1.639     albertel 2157: sub add_filetype {
                   2158:     my ($allfiles,$file,$type)=@_;
                   2159:     if (exists($allfiles->{$file})) {
                   2160: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   2161: 	    push(@{$allfiles->{$file}}, &escape($type));
                   2162: 	}
                   2163:     } else {
                   2164: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  2165:     }
                   2166: }
                   2167: 
1.493     albertel 2168: sub removeuploadedurl {
                   2169:     my ($url)=@_;
                   2170:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613     albertel 2171:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 2172: }
                   2173: 
                   2174: sub removeuserfile {
                   2175:     my ($docuname,$docudom,$fname)=@_;
                   2176:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2177:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
                   2178:     if ($result eq 'ok') {
                   2179:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   2180:             my $metafile = $fname.'.meta';
                   2181:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 2182: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
                   2183:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2184:             my $sqlresult = 
1.823     albertel 2185:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2186:                                         'portfolio_metadata',$group,
                   2187:                                         'delete');
1.798     raeburn  2188:         }
                   2189:     }
                   2190:     return $result;
1.257     www      2191: }
1.15      www      2192: 
1.530     albertel 2193: sub mkdiruserfile {
                   2194:     my ($docuname,$docudom,$dir)=@_;
                   2195:     my $home=&homeserver($docuname,$docudom);
                   2196:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   2197: }
                   2198: 
1.531     albertel 2199: sub renameuserfile {
                   2200:     my ($docuname,$docudom,$old,$new)=@_;
                   2201:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  2202:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   2203:                         &escape("$old").':'.&escape("$new"),$home);
                   2204:     if ($result eq 'ok') {
                   2205:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   2206:             my $oldmeta = $old.'.meta';
                   2207:             my $newmeta = $new.'.meta';
                   2208:             my $metaresult = 
                   2209:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 2210: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   2211:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  2212:             my $sqlresult = 
1.823     albertel 2213:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  2214:                                         'portfolio_metadata',$group,
                   2215:                                         'delete');
1.798     raeburn  2216:         }
                   2217:     }
                   2218:     return $result;
1.531     albertel 2219: }
                   2220: 
1.14      www      2221: # ------------------------------------------------------------------------- Log
                   2222: 
                   2223: sub log {
                   2224:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      2225:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      2226: }
                   2227: 
                   2228: # ------------------------------------------------------------------ Course Log
1.352     www      2229: #
                   2230: # This routine flushes several buffers of non-mission-critical nature
                   2231: #
1.157     www      2232: 
                   2233: sub flushcourselogs {
1.352     www      2234:     &logthis('Flushing log buffers');
                   2235: #
                   2236: # course logs
                   2237: # This is a log of all transactions in a course, which can be used
                   2238: # for data mining purposes
                   2239: #
                   2240: # It also collects the courseid database, which lists last transaction
                   2241: # times and course titles for all courseids
                   2242: #
                   2243:     my %courseidbuffer=();
1.921     raeburn  2244:     foreach my $crsid (keys(%courselogs)) {
1.352     www      2245:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      2246: 		          &escape($courselogs{$crsid}),
                   2247: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      2248: 	    delete $courselogs{$crsid};
                   2249:         } else {
                   2250:             &logthis('Failed to flush log buffer for '.$crsid);
                   2251:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 2252:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      2253:                         " exceeded maximum size, deleting.</font>");
                   2254:                delete $courselogs{$crsid};
                   2255:             }
1.352     www      2256:         }
1.920     raeburn  2257:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  2258:             'description' => $coursedescrbuf{$crsid},
                   2259:             'inst_code'    => $courseinstcodebuf{$crsid},
                   2260:             'type'        => $coursetypebuf{$crsid},
                   2261:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  2262:         };
1.191     harris41 2263:     }
1.352     www      2264: #
                   2265: # Write course id database (reverse lookup) to homeserver of courses 
                   2266: # Is used in pickcourse
                   2267: #
1.840     albertel 2268:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  2269:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  2270:                                     $courseidbuffer{$crs_home},
                   2271:                                     $crs_home,'timeonly');
1.352     www      2272:     }
                   2273: #
                   2274: # File accesses
                   2275: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   2276: #
1.449     matthew  2277:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  2278:         if ($entry =~ /___count$/) {
                   2279:             my ($dom,$name);
1.807     albertel 2280:             ($dom,$name,undef)=
1.811     albertel 2281: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  2282:             if (! defined($dom) || $dom eq '' || 
                   2283:                 ! defined($name) || $name eq '') {
1.620     albertel 2284:                 my $cid = $env{'request.course.id'};
                   2285:                 $dom  = $env{'request.'.$cid.'.domain'};
                   2286:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  2287:             }
1.450     matthew  2288:             my $value = $accesshash{$entry};
                   2289:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   2290:             my %temphash=($url => $value);
1.449     matthew  2291:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   2292:             if ($result eq 'ok') {
                   2293:                 delete $accesshash{$entry};
                   2294:             } elsif ($result eq 'unknown_cmd') {
                   2295:                 # Target server has old code running on it.
1.450     matthew  2296:                 my %temphash=($entry => $value);
1.449     matthew  2297:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2298:                     delete $accesshash{$entry};
                   2299:                 }
                   2300:             }
                   2301:         } else {
1.811     albertel 2302:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  2303:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  2304:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   2305:                 delete $accesshash{$entry};
                   2306:             }
1.185     www      2307:         }
1.191     harris41 2308:     }
1.352     www      2309: #
                   2310: # Roles
                   2311: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   2312: #
1.800     albertel 2313:     foreach my $entry (keys(%userrolehash)) {
1.351     www      2314:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      2315: 	    split(/\:/,$entry);
                   2316:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      2317:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      2318:                 $rudom,$runame) eq 'ok') {
                   2319: 	    delete $userrolehash{$entry};
                   2320:         }
                   2321:     }
1.662     raeburn  2322: #
                   2323: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   2324: #
                   2325:     my %domrolebuffer = ();
                   2326:     foreach my $entry (keys %domainrolehash) {
1.901     albertel 2327:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  2328:         if ($domrolebuffer{$rudom}) {
                   2329:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   2330:                       '='.&escape($domainrolehash{$entry});
                   2331:         } else {
                   2332:             $domrolebuffer{$rudom}.=&escape($entry).
                   2333:                       '='.&escape($domainrolehash{$entry});
                   2334:         }
                   2335:         delete $domainrolehash{$entry};
                   2336:     }
                   2337:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 2338: 	my %servers = &get_servers($dom,'library');
                   2339: 	foreach my $tryserver (keys(%servers)) {
                   2340: 	    unless (&reply('domroleput:'.$dom.':'.
                   2341: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   2342: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   2343: 	    }
1.662     raeburn  2344:         }
                   2345:     }
1.186     www      2346:     $dumpcount++;
1.157     www      2347: }
                   2348: 
                   2349: sub courselog {
                   2350:     my $what=shift;
1.158     www      2351:     $what=time.':'.$what;
1.620     albertel 2352:     unless ($env{'request.course.id'}) { return ''; }
                   2353:     $coursedombuf{$env{'request.course.id'}}=
                   2354:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2355:     $coursenumbuf{$env{'request.course.id'}}=
                   2356:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   2357:     $coursehombuf{$env{'request.course.id'}}=
                   2358:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   2359:     $coursedescrbuf{$env{'request.course.id'}}=
                   2360:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   2361:     $courseinstcodebuf{$env{'request.course.id'}}=
                   2362:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   2363:     $courseownerbuf{$env{'request.course.id'}}=
                   2364:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  2365:     $coursetypebuf{$env{'request.course.id'}}=
                   2366:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 2367:     if (defined $courselogs{$env{'request.course.id'}}) {
                   2368: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      2369:     } else {
1.620     albertel 2370: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      2371:     }
1.620     albertel 2372:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      2373: 	&flushcourselogs();
                   2374:     }
1.158     www      2375: }
                   2376: 
                   2377: sub courseacclog {
                   2378:     my $fnsymb=shift;
1.620     albertel 2379:     unless ($env{'request.course.id'}) { return ''; }
                   2380:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 2381:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      2382:         $what.=':POST';
1.583     matthew  2383:         # FIXME: Probably ought to escape things....
1.800     albertel 2384: 	foreach my $key (keys(%env)) {
                   2385:             if ($key=~/^form\.(.*)/) {
                   2386: 		$what.=':'.$1.'='.$env{$key};
1.158     www      2387:             }
1.191     harris41 2388:         }
1.583     matthew  2389:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   2390:         # FIXME: We should not be depending on a form parameter that someone
                   2391:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 2392:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  2393:             $what.= ':POST';
                   2394:             # FIXME: Probably ought to escape things....
                   2395:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   2396:                                  'crsdiscuss') {
1.620     albertel 2397:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  2398:             }
                   2399:         }
1.158     www      2400:     }
                   2401:     &courselog($what);
1.149     www      2402: }
                   2403: 
1.185     www      2404: sub countacc {
                   2405:     my $url=&declutter(shift);
1.458     matthew  2406:     return if (! defined($url) || $url eq '');
1.620     albertel 2407:     unless ($env{'request.course.id'}) { return ''; }
                   2408:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      2409:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  2410:     $accesshash{$key}++;
1.185     www      2411: }
1.349     www      2412: 
1.361     www      2413: sub linklog {
                   2414:     my ($from,$to)=@_;
                   2415:     $from=&declutter($from);
                   2416:     $to=&declutter($to);
                   2417:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   2418:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   2419: }
                   2420:   
1.349     www      2421: sub userrolelog {
                   2422:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  2423:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  2424:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  2425:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   2426:         ($trole=~/^ta/)) {
1.350     www      2427:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2428:        $userrolehash
                   2429:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      2430:                     =$tend.':'.$tstart;
1.662     raeburn  2431:     }
1.898     albertel 2432:     if (($env{'request.role'} =~ /dc\./) &&
                   2433: 	(($trole=~/^au/) || ($trole=~/^in/) ||
                   2434: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
                   2435: 	 ($trole=~/^cr/) || ($trole=~/^ta/))) {
                   2436:        $userrolehash
                   2437:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   2438:                     =$tend.':'.$tstart;
                   2439:     }
1.662     raeburn  2440:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   2441:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   2442:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   2443:         ($trole=~/^sc/)) {
                   2444:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2445:        $domainrolehash
                   2446:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   2447:                     = $tend.':'.$tstart;
                   2448:     }
1.351     www      2449: }
                   2450: 
                   2451: sub get_course_adv_roles {
                   2452:     my $cid=shift;
1.620     albertel 2453:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      2454:     my %coursehash=&coursedescription($cid);
1.470     www      2455:     my %nothide=();
1.800     albertel 2456:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  2457:         if ($user !~ /:/) {
                   2458: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   2459:         } else {
                   2460:             $nothide{$user}=1;
                   2461:         }
1.470     www      2462:     }
1.351     www      2463:     my %returnhash=();
                   2464:     my %dumphash=
                   2465:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   2466:     my $now=time;
1.800     albertel 2467:     foreach my $entry (keys %dumphash) {
                   2468: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      2469:         if (($tstart) && ($tstart<0)) { next; }
                   2470:         if (($tend) && ($tend<$now)) { next; }
                   2471:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 2472:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 2473: 	if ($username eq '' || $domain eq '') { next; }
1.470     www      2474: 	if ((&privileged($username,$domain)) && 
                   2475: 	    (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 2476: 	if ($role eq 'cr') { next; }
1.351     www      2477:         my $key=&plaintext($role);
                   2478:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
                   2479:         if ($returnhash{$key}) {
                   2480: 	    $returnhash{$key}.=','.$username.':'.$domain;
                   2481:         } else {
                   2482:             $returnhash{$key}=$username.':'.$domain;
                   2483:         }
1.400     www      2484:      }
                   2485:     return %returnhash;
                   2486: }
                   2487: 
                   2488: sub get_my_roles {
1.937     raeburn  2489:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 2490:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   2491:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  2492:     my (%dumphash,%nothide);
1.858     raeburn  2493:     if ($context eq 'userroles') { 
                   2494:         %dumphash = &dump('roles',$udom,$uname);
                   2495:     } else {
                   2496:         %dumphash=
1.400     www      2497:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  2498:         if ($hidepriv) {
                   2499:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   2500:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2501:                 if ($user !~ /:/) {
                   2502:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   2503:                 } else {
                   2504:                     $nothide{$user} = 1;
                   2505:                 }
                   2506:             }
                   2507:         }
1.858     raeburn  2508:     }
1.400     www      2509:     my %returnhash=();
                   2510:     my $now=time;
1.800     albertel 2511:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  2512:         my ($role,$tend,$tstart);
                   2513:         if ($context eq 'userroles') {
                   2514: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   2515:         } else {
                   2516:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   2517:         }
1.400     www      2518:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  2519:         my $status = 'active';
1.939     raeburn  2520:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  2521:             $status = 'previous';
                   2522:         } 
                   2523:         if (($tstart) && ($now<$tstart)) {
                   2524:             $status = 'future';
                   2525:         }
                   2526:         if (ref($types) eq 'ARRAY') {
                   2527:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   2528:                 next;
                   2529:             } 
                   2530:         } else {
                   2531:             if ($status ne 'active') {
                   2532:                 next;
                   2533:             }
                   2534:         }
1.867     raeburn  2535:         my ($rolecode,$username,$domain,$section,$area);
                   2536:         if ($context eq 'userroles') {
                   2537:             ($area,$rolecode) = split(/_/,$entry);
                   2538:             (undef,$domain,$username,$section) = split(/\//,$area);
                   2539:         } else {
                   2540:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   2541:         }
1.832     raeburn  2542:         if (ref($roledoms) eq 'ARRAY') {
                   2543:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   2544:                 next;
                   2545:             }
                   2546:         }
                   2547:         if (ref($roles) eq 'ARRAY') {
                   2548:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  2549:                 if ($role =~ /^cr\//) {
                   2550:                     if (!grep(/^cr$/,@{$roles})) {
                   2551:                         next;
                   2552:                     }
                   2553:                 } else {
                   2554:                     next;
                   2555:                 }
1.832     raeburn  2556:             }
1.867     raeburn  2557:         }
1.937     raeburn  2558:         if ($hidepriv) {
                   2559:             if ((&privileged($username,$domain)) &&
                   2560:                 (!$nothide{$username.':'.$domain})) { 
                   2561:                 next;
                   2562:             }
                   2563:         }
1.933     raeburn  2564:         if ($withsec) {
                   2565:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   2566:                 $tstart.':'.$tend;
                   2567:         } else {
                   2568:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   2569:         }
1.832     raeburn  2570:     }
1.373     www      2571:     return %returnhash;
1.399     www      2572: }
                   2573: 
                   2574: # ----------------------------------------------------- Frontpage Announcements
                   2575: #
                   2576: #
                   2577: 
                   2578: sub postannounce {
                   2579:     my ($server,$text)=@_;
1.844     albertel 2580:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      2581:     unless ($text=~/\w/) { $text=''; }
                   2582:     return &reply('setannounce:'.&escape($text),$server);
                   2583: }
                   2584: 
                   2585: sub getannounce {
1.448     albertel 2586: 
                   2587:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      2588: 	my $announcement='';
1.800     albertel 2589: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 2590: 	close($fh);
1.399     www      2591: 	if ($announcement=~/\w/) { 
                   2592: 	    return 
                   2593:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 2594:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      2595: 	} else {
                   2596: 	    return '';
                   2597: 	}
                   2598:     } else {
                   2599: 	return '';
                   2600:     }
1.351     www      2601: }
1.353     www      2602: 
                   2603: # ---------------------------------------------------------- Course ID routines
                   2604: # Deal with domain's nohist_courseid.db files
                   2605: #
                   2606: 
                   2607: sub courseidput {
1.921     raeburn  2608:     my ($domain,$storehash,$coursehome,$caller) = @_;
                   2609:     my $outcome;
                   2610:     if ($caller eq 'timeonly') {
                   2611:         my $cids = '';
                   2612:         foreach my $item (keys(%$storehash)) {
                   2613:             $cids.=&escape($item).'&';
                   2614:         }
                   2615:         $cids=~s/\&$//;
                   2616:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   2617:                           $coursehome);       
                   2618:     } else {
                   2619:         my $items = '';
                   2620:         foreach my $item (keys(%$storehash)) {
                   2621:             $items.= &escape($item).'='.
                   2622:                      &freeze_escape($$storehash{$item}).'&';
                   2623:         }
                   2624:         $items=~s/\&$//;
                   2625:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   2626:                           $coursehome);
1.918     raeburn  2627:     }
                   2628:     if ($outcome eq 'unknown_cmd') {
                   2629:         my $what;
                   2630:         foreach my $cid (keys(%$storehash)) {
                   2631:             $what .= &escape($cid).'=';
1.921     raeburn  2632:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  2633:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  2634:             }
                   2635:             $what =~ s/\:$/&/;
                   2636:         }
                   2637:         $what =~ s/\&$//;  
                   2638:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   2639:     } else {
                   2640:         return $outcome;
                   2641:     }
1.353     www      2642: }
                   2643: 
                   2644: sub courseiddump {
1.921     raeburn  2645:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
                   2646:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok)=@_;
1.918     raeburn  2647:     my $as_hash = 1;
                   2648:     my %returnhash;
                   2649:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 2650:     my %libserv = &all_library();
                   2651:     foreach my $tryserver (keys(%libserv)) {
                   2652:         if ( (  $hostidflag == 1 
                   2653: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   2654: 	     || (!defined($hostidflag)) ) {
                   2655: 
1.918     raeburn  2656: 	    if (($domfilter eq '') ||
                   2657: 		(&host_domain($tryserver) eq $domfilter)) {
                   2658:                 my $rep = 
                   2659:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
                   2660:                          $sincefilter.':'.&escape($descfilter).':'.
                   2661:                          &escape($instcodefilter).':'.&escape($ownerfilter).
                   2662:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
1.921     raeburn  2663:                          ':'.&escape($regexp_ok).':'.$as_hash,$tryserver);
1.918     raeburn  2664:                 my @pairs=split(/\&/,$rep);
                   2665:                 foreach my $item (@pairs) {
                   2666:                     my ($key,$value)=split(/\=/,$item,2);
                   2667:                     $key = &unescape($key);
                   2668:                     next if ($key =~ /^error: 2 /);
                   2669:                     my $result = &thaw_unescape($value);
                   2670:                     if (ref($result) eq 'HASH') {
                   2671:                         $returnhash{$key}=$result;
                   2672:                     } else {
1.921     raeburn  2673:                         my @responses = split(/:/,$value);
                   2674:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  2675:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  2676:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  2677:                         }
                   2678:                     } 
1.353     www      2679:                 }
                   2680:             }
                   2681:         }
                   2682:     }
                   2683:     return %returnhash;
                   2684: }
                   2685: 
1.658     raeburn  2686: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  2687: 
                   2688: sub dcmailput {
1.685     raeburn  2689:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  2690:     my $status = &Apache::lonnet::critical(
1.740     www      2691:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   2692:        &escape($message),$server);
1.662     raeburn  2693:     return $status;
                   2694: }
                   2695: 
1.658     raeburn  2696: sub dcmaildump {
                   2697:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  2698:     my %returnhash=();
1.846     albertel 2699: 
                   2700:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  2701:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   2702:                                                          &escape($enddate).':';
                   2703: 	my @esc_senders=map { &escape($_)} @$senders;
                   2704: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 2705: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 2706:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  2707:             if (($key) && ($value)) {
                   2708:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  2709:             }
                   2710:         }
                   2711:     }
                   2712:     return %returnhash;
                   2713: }
1.662     raeburn  2714: # ---------------------------------------------------------- Domain roles
                   2715: 
                   2716: sub get_domain_roles {
                   2717:     my ($dom,$roles,$startdate,$enddate)=@_;
                   2718:     if (undef($startdate) || $startdate eq '') {
                   2719:         $startdate = '.';
                   2720:     }
                   2721:     if (undef($enddate) || $enddate eq '') {
                   2722:         $enddate = '.';
                   2723:     }
1.922     raeburn  2724:     my $rolelist;
                   2725:     if (ref($roles) eq 'ARRAY') {
                   2726:         $rolelist = join(':',@{$roles});
                   2727:     }
1.662     raeburn  2728:     my %personnel = ();
1.841     albertel 2729: 
                   2730:     my %servers = &get_servers($dom,'library');
                   2731:     foreach my $tryserver (keys(%servers)) {
                   2732: 	%{$personnel{$tryserver}}=();
                   2733: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   2734: 					    &escape($startdate).':'.
                   2735: 					    &escape($enddate).':'.
                   2736: 					    &escape($rolelist), $tryserver))) {
                   2737: 	    my ($key,$value) = split(/\=/,$line,2);
                   2738: 	    if (($key) && ($value)) {
                   2739: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   2740: 	    }
                   2741: 	}
1.662     raeburn  2742:     }
                   2743:     return %personnel;
                   2744: }
1.658     raeburn  2745: 
1.149     www      2746: # ----------------------------------------------------------- Check out an item
                   2747: 
1.504     albertel 2748: sub get_first_access {
                   2749:     my ($type,$argsymb)=@_;
1.790     albertel 2750:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2751:     if ($argsymb) { $symb=$argsymb; }
                   2752:     my ($map,$id,$res)=&decode_symb($symb);
1.926     albertel 2753:     if ($type eq 'course') {
                   2754: 	$res='course';
                   2755:     } elsif ($type eq 'map') {
1.588     albertel 2756: 	$res=&symbread($map);
                   2757:     } else {
                   2758: 	$res=$symb;
                   2759:     }
                   2760:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   2761:     return $times{"$courseid\0$res"};
1.504     albertel 2762: }
                   2763: 
                   2764: sub set_first_access {
                   2765:     my ($type)=@_;
1.790     albertel 2766:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2767:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 2768:     if ($type eq 'course') {
                   2769: 	$res='course';
                   2770:     } elsif ($type eq 'map') {
1.588     albertel 2771: 	$res=&symbread($map);
                   2772:     } else {
                   2773: 	$res=$symb;
                   2774:     }
                   2775:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 2776:     if (!$firstaccess) {
1.588     albertel 2777: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 2778:     }
                   2779:     return 'already_set';
1.504     albertel 2780: }
                   2781: 
1.149     www      2782: sub checkout {
                   2783:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   2784:     my $now=time;
                   2785:     my $lonhost=$perlvar{'lonHostID'};
                   2786:     my $infostr=&escape(
1.234     www      2787:                  'CHECKOUTTOKEN&'.
1.149     www      2788:                  $tuname.'&'.
                   2789:                  $tudom.'&'.
                   2790:                  $tcrsid.'&'.
                   2791:                  $symb.'&'.
                   2792: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   2793:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      2794:     if ($token=~/^error\:/) { 
1.672     albertel 2795:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2796:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2797:                  "</font>");
                   2798:         return ''; 
                   2799:     }
                   2800: 
1.149     www      2801:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   2802:     $token=~tr/a-z/A-Z/;
                   2803: 
1.153     www      2804:     my %infohash=('resource.0.outtoken' => $token,
                   2805:                   'resource.0.checkouttime' => $now,
                   2806:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      2807: 
                   2808:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2809:        return '';
1.151     www      2810:     } else {
1.672     albertel 2811:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2812:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2813:                  "</font>");
1.149     www      2814:     }    
                   2815: 
                   2816:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2817:                          &escape('Checkout '.$infostr.' - '.
                   2818:                                                  $token)) ne 'ok') {
                   2819: 	return '';
1.151     www      2820:     } else {
1.672     albertel 2821:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2822:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2823:                  "</font>");
1.149     www      2824:     }
1.151     www      2825:     return $token;
1.149     www      2826: }
                   2827: 
                   2828: # ------------------------------------------------------------ Check in an item
                   2829: 
                   2830: sub checkin {
                   2831:     my $token=shift;
1.150     www      2832:     my $now=time;
                   2833:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   2834:     $lonhost=~tr/A-Z/a-z/;
1.838     albertel 2835:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150     www      2836:     $dtoken=~s/\W/\_/g;
1.234     www      2837:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      2838:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   2839: 
1.154     www      2840:     unless (($tuname) && ($tudom)) {
                   2841:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   2842:         return '';
                   2843:     }
                   2844:     
                   2845:     unless (&allowed('mgr',$tcrsid)) {
                   2846:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 2847:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      2848:         return '';
                   2849:     }
                   2850: 
1.153     www      2851:     my %infohash=('resource.0.intoken' => $token,
                   2852:                   'resource.0.checkintime' => $now,
                   2853:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      2854: 
                   2855:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2856:        return '';
                   2857:     }    
                   2858: 
                   2859:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2860:                          &escape('Checkin - '.$token)) ne 'ok') {
                   2861: 	return '';
                   2862:     }
                   2863: 
                   2864:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      2865: }
                   2866: 
                   2867: # --------------------------------------------- Set Expire Date for Spreadsheet
                   2868: 
                   2869: sub expirespread {
                   2870:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 2871:     my $cid=$env{'request.course.id'}; 
1.110     www      2872:     if ($cid) {
                   2873:        my $now=time;
                   2874:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 2875:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   2876:                             $env{'course.'.$cid.'.num'}.
1.110     www      2877: 	        	    ':nohist_expirationdates:'.
                   2878:                             &escape($key).'='.$now,
1.620     albertel 2879:                             $env{'course.'.$cid.'.home'})
1.110     www      2880:     }
                   2881:     return 'ok';
1.14      www      2882: }
                   2883: 
1.109     www      2884: # ----------------------------------------------------- Devalidate Spreadsheets
                   2885: 
                   2886: sub devalidate {
1.325     www      2887:     my ($symb,$uname,$udom)=@_;
1.620     albertel 2888:     my $cid=$env{'request.course.id'}; 
1.109     www      2889:     if ($cid) {
1.391     matthew  2890:         # delete the stored spreadsheets for
                   2891:         # - the student level sheet of this user in course's homespace
                   2892:         # - the assessment level sheet for this resource 
                   2893:         #   for this user in user's homespace
1.553     albertel 2894: 	# - current conditional state info
1.325     www      2895: 	my $key=$uname.':'.$udom.':';
1.109     www      2896:         my $status=
1.299     matthew  2897: 	    &del('nohist_calculatedsheets',
1.391     matthew  2898: 		 [$key.'studentcalc:'],
1.620     albertel 2899: 		 $env{'course.'.$cid.'.domain'},
                   2900: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 2901: 		.' '.
                   2902: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  2903: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      2904:         unless ($status eq 'ok ok') {
                   2905:            &logthis('Could not devalidate spreadsheet '.
1.325     www      2906:                     $uname.' at '.$udom.' for '.
1.109     www      2907: 		    $symb.': '.$status);
1.133     albertel 2908:         }
1.553     albertel 2909: 	&delenv('user.state.'.$cid);
1.109     www      2910:     }
                   2911: }
                   2912: 
1.265     albertel 2913: sub get_scalar {
                   2914:     my ($string,$end) = @_;
                   2915:     my $value;
                   2916:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   2917: 	$value = $1;
                   2918:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   2919: 	$value = $1;
                   2920:     }
                   2921:     return &unescape($value);
                   2922: }
                   2923: 
                   2924: sub array2str {
                   2925:   my (@array) = @_;
                   2926:   my $result=&arrayref2str(\@array);
                   2927:   $result=~s/^__ARRAY_REF__//;
                   2928:   $result=~s/__END_ARRAY_REF__$//;
                   2929:   return $result;
                   2930: }
                   2931: 
1.204     albertel 2932: sub arrayref2str {
                   2933:   my ($arrayref) = @_;
1.265     albertel 2934:   my $result='__ARRAY_REF__';
1.204     albertel 2935:   foreach my $elem (@$arrayref) {
1.265     albertel 2936:     if(ref($elem) eq 'ARRAY') {
                   2937:       $result.=&arrayref2str($elem).'&';
                   2938:     } elsif(ref($elem) eq 'HASH') {
                   2939:       $result.=&hashref2str($elem).'&';
                   2940:     } elsif(ref($elem)) {
                   2941:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 2942:     } else {
                   2943:       $result.=&escape($elem).'&';
                   2944:     }
                   2945:   }
                   2946:   $result=~s/\&$//;
1.265     albertel 2947:   $result .= '__END_ARRAY_REF__';
1.204     albertel 2948:   return $result;
                   2949: }
                   2950: 
1.168     albertel 2951: sub hash2str {
1.204     albertel 2952:   my (%hash) = @_;
                   2953:   my $result=&hashref2str(\%hash);
1.265     albertel 2954:   $result=~s/^__HASH_REF__//;
                   2955:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 2956:   return $result;
                   2957: }
                   2958: 
                   2959: sub hashref2str {
                   2960:   my ($hashref)=@_;
1.265     albertel 2961:   my $result='__HASH_REF__';
1.800     albertel 2962:   foreach my $key (sort(keys(%$hashref))) {
                   2963:     if (ref($key) eq 'ARRAY') {
                   2964:       $result.=&arrayref2str($key).'=';
                   2965:     } elsif (ref($key) eq 'HASH') {
                   2966:       $result.=&hashref2str($key).'=';
                   2967:     } elsif (ref($key)) {
1.265     albertel 2968:       $result.='=';
1.800     albertel 2969:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 2970:     } else {
1.800     albertel 2971: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 2972:     }
                   2973: 
1.800     albertel 2974:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   2975:       $result.=&arrayref2str($hashref->{$key}).'&';
                   2976:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   2977:       $result.=&hashref2str($hashref->{$key}).'&';
                   2978:     } elsif(ref($hashref->{$key})) {
1.265     albertel 2979:        $result.='&';
1.800     albertel 2980:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 2981:     } else {
1.800     albertel 2982:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 2983:     }
                   2984:   }
1.168     albertel 2985:   $result=~s/\&$//;
1.265     albertel 2986:   $result .= '__END_HASH_REF__';
1.168     albertel 2987:   return $result;
                   2988: }
                   2989: 
                   2990: sub str2hash {
1.265     albertel 2991:     my ($string)=@_;
                   2992:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   2993:     return %$hash;
                   2994: }
                   2995: 
                   2996: sub str2hashref {
1.168     albertel 2997:   my ($string) = @_;
1.265     albertel 2998: 
                   2999:   my %hash;
                   3000: 
                   3001:   if($string !~ /^__HASH_REF__/) {
                   3002:       if (! ($string eq '' || !defined($string))) {
                   3003: 	  $hash{'error'}='Not hash reference';
                   3004:       }
                   3005:       return (\%hash, $string);
                   3006:   }
                   3007: 
                   3008:   $string =~ s/^__HASH_REF__//;
                   3009: 
                   3010:   while($string !~ /^__END_HASH_REF__/) {
                   3011:       #key
                   3012:       my $key='';
                   3013:       if($string =~ /^__HASH_REF__/) {
                   3014:           ($key, $string)=&str2hashref($string);
                   3015:           if(defined($key->{'error'})) {
                   3016:               $hash{'error'}='Bad data';
                   3017:               return (\%hash, $string);
                   3018:           }
                   3019:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3020:           ($key, $string)=&str2arrayref($string);
                   3021:           if($key->[0] eq 'Array reference error') {
                   3022:               $hash{'error'}='Bad data';
                   3023:               return (\%hash, $string);
                   3024:           }
                   3025:       } else {
                   3026:           $string =~ s/^(.*?)=//;
1.267     albertel 3027: 	  $key=&unescape($1);
1.265     albertel 3028:       }
                   3029:       $string =~ s/^=//;
                   3030: 
                   3031:       #value
                   3032:       my $value='';
                   3033:       if($string =~ /^__HASH_REF__/) {
                   3034:           ($value, $string)=&str2hashref($string);
                   3035:           if(defined($value->{'error'})) {
                   3036:               $hash{'error'}='Bad data';
                   3037:               return (\%hash, $string);
                   3038:           }
                   3039:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3040:           ($value, $string)=&str2arrayref($string);
                   3041:           if($value->[0] eq 'Array reference error') {
                   3042:               $hash{'error'}='Bad data';
                   3043:               return (\%hash, $string);
                   3044:           }
                   3045:       } else {
                   3046: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   3047:       }
                   3048:       $string =~ s/^&//;
                   3049: 
                   3050:       $hash{$key}=$value;
1.204     albertel 3051:   }
1.265     albertel 3052: 
                   3053:   $string =~ s/^__END_HASH_REF__//;
                   3054: 
                   3055:   return (\%hash, $string);
1.204     albertel 3056: }
                   3057: 
                   3058: sub str2array {
1.265     albertel 3059:     my ($string)=@_;
                   3060:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   3061:     return @$array;
                   3062: }
                   3063: 
                   3064: sub str2arrayref {
1.204     albertel 3065:   my ($string) = @_;
1.265     albertel 3066:   my @array;
                   3067: 
                   3068:   if($string !~ /^__ARRAY_REF__/) {
                   3069:       if (! ($string eq '' || !defined($string))) {
                   3070: 	  $array[0]='Array reference error';
                   3071:       }
                   3072:       return (\@array, $string);
                   3073:   }
                   3074: 
                   3075:   $string =~ s/^__ARRAY_REF__//;
                   3076: 
                   3077:   while($string !~ /^__END_ARRAY_REF__/) {
                   3078:       my $value='';
                   3079:       if($string =~ /^__HASH_REF__/) {
                   3080:           ($value, $string)=&str2hashref($string);
                   3081:           if(defined($value->{'error'})) {
                   3082:               $array[0] ='Array reference error';
                   3083:               return (\@array, $string);
                   3084:           }
                   3085:       } elsif($string =~ /^__ARRAY_REF__/) {
                   3086:           ($value, $string)=&str2arrayref($string);
                   3087:           if($value->[0] eq 'Array reference error') {
                   3088:               $array[0] ='Array reference error';
                   3089:               return (\@array, $string);
                   3090:           }
                   3091:       } else {
                   3092: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   3093:       }
                   3094:       $string =~ s/^&//;
                   3095: 
                   3096:       push(@array, $value);
1.191     harris41 3097:   }
1.265     albertel 3098: 
                   3099:   $string =~ s/^__END_ARRAY_REF__//;
                   3100: 
                   3101:   return (\@array, $string);
1.168     albertel 3102: }
                   3103: 
1.167     albertel 3104: # -------------------------------------------------------------------Temp Store
                   3105: 
1.168     albertel 3106: sub tmpreset {
                   3107:   my ($symb,$namespace,$domain,$stuname) = @_;
                   3108:   if (!$symb) {
                   3109:     $symb=&symbread();
1.620     albertel 3110:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3111:   }
                   3112:   $symb=escape($symb);
                   3113: 
1.620     albertel 3114:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 3115:   $namespace=~s/\//\_/g;
                   3116:   $namespace=~s/\W//g;
                   3117: 
1.620     albertel 3118:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3119:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3120:   if ($domain eq 'public' && $stuname eq 'public') {
                   3121:       $stuname=$ENV{'REMOTE_ADDR'};
                   3122:   }
1.168     albertel 3123:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3124:   my %hash;
                   3125:   if (tie(%hash,'GDBM_File',
                   3126: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3127: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3128:     foreach my $key (keys %hash) {
1.180     albertel 3129:       if ($key=~ /:$symb/) {
1.168     albertel 3130: 	delete($hash{$key});
                   3131:       }
                   3132:     }
                   3133:   }
                   3134: }
                   3135: 
1.167     albertel 3136: sub tmpstore {
1.168     albertel 3137:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3138: 
                   3139:   if (!$symb) {
                   3140:     $symb=&symbread();
1.620     albertel 3141:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3142:   }
                   3143:   $symb=escape($symb);
                   3144: 
                   3145:   if (!$namespace) {
                   3146:     # I don't think we would ever want to store this for a course.
                   3147:     # it seems this will only be used if we don't have a course.
1.620     albertel 3148:     #$namespace=$env{'request.course.id'};
1.168     albertel 3149:     #if (!$namespace) {
1.620     albertel 3150:       $namespace=$env{'request.state'};
1.168     albertel 3151:     #}
                   3152:   }
                   3153:   $namespace=~s/\//\_/g;
                   3154:   $namespace=~s/\W//g;
1.620     albertel 3155:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3156:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3157:   if ($domain eq 'public' && $stuname eq 'public') {
                   3158:       $stuname=$ENV{'REMOTE_ADDR'};
                   3159:   }
1.168     albertel 3160:   my $now=time;
                   3161:   my %hash;
                   3162:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3163:   if (tie(%hash,'GDBM_File',
                   3164: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3165: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 3166:     $hash{"version:$symb"}++;
                   3167:     my $version=$hash{"version:$symb"};
                   3168:     my $allkeys=''; 
                   3169:     foreach my $key (keys(%$storehash)) {
                   3170:       $allkeys.=$key.':';
1.591     albertel 3171:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 3172:     }
                   3173:     $hash{"$version:$symb:timestamp"}=$now;
                   3174:     $allkeys.='timestamp';
                   3175:     $hash{"$version:keys:$symb"}=$allkeys;
                   3176:     if (untie(%hash)) {
                   3177:       return 'ok';
                   3178:     } else {
                   3179:       return "error:$!";
                   3180:     }
                   3181:   } else {
                   3182:     return "error:$!";
                   3183:   }
                   3184: }
1.167     albertel 3185: 
1.168     albertel 3186: # -----------------------------------------------------------------Temp Restore
1.167     albertel 3187: 
1.168     albertel 3188: sub tmprestore {
                   3189:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 3190: 
1.168     albertel 3191:   if (!$symb) {
                   3192:     $symb=&symbread();
1.620     albertel 3193:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 3194:   }
                   3195:   $symb=escape($symb);
                   3196: 
1.620     albertel 3197:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 3198: 
1.620     albertel 3199:   if (!$domain) { $domain=$env{'user.domain'}; }
                   3200:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 3201:   if ($domain eq 'public' && $stuname eq 'public') {
                   3202:       $stuname=$ENV{'REMOTE_ADDR'};
                   3203:   }
1.168     albertel 3204:   my %returnhash;
                   3205:   $namespace=~s/\//\_/g;
                   3206:   $namespace=~s/\W//g;
                   3207:   my %hash;
                   3208:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   3209:   if (tie(%hash,'GDBM_File',
                   3210: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 3211: 	  &GDBM_READER(),0640)) {
1.168     albertel 3212:     my $version=$hash{"version:$symb"};
                   3213:     $returnhash{'version'}=$version;
                   3214:     my $scope;
                   3215:     for ($scope=1;$scope<=$version;$scope++) {
                   3216:       my $vkeys=$hash{"$scope:keys:$symb"};
                   3217:       my @keys=split(/:/,$vkeys);
                   3218:       my $key;
                   3219:       $returnhash{"$scope:keys"}=$vkeys;
                   3220:       foreach $key (@keys) {
1.591     albertel 3221: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   3222: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 3223:       }
                   3224:     }
1.168     albertel 3225:     if (!(untie(%hash))) {
                   3226:       return "error:$!";
                   3227:     }
                   3228:   } else {
                   3229:     return "error:$!";
                   3230:   }
                   3231:   return %returnhash;
1.167     albertel 3232: }
                   3233: 
1.9       www      3234: # ----------------------------------------------------------------------- Store
                   3235: 
                   3236: sub store {
1.124     www      3237:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3238:     my $home='';
                   3239: 
1.168     albertel 3240:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3241: 
1.213     www      3242:     $symb=&symbclean($symb);
1.122     albertel 3243:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3244: 
1.620     albertel 3245:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3246:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3247: 
                   3248:     &devalidate($symb,$stuname,$domain);
1.109     www      3249: 
                   3250:     $symb=escape($symb);
1.187     www      3251:     if (!$namespace) { 
1.620     albertel 3252:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3253:           return ''; 
                   3254:        } 
                   3255:     }
1.620     albertel 3256:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3257: 
                   3258:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3259:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   3260: 
1.12      www      3261:     my $namevalue='';
1.800     albertel 3262:     foreach my $key (keys(%$storehash)) {
                   3263:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3264:     }
1.12      www      3265:     $namevalue=~s/\&$//;
1.187     www      3266:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      3267:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      3268: }
                   3269: 
1.47      www      3270: # -------------------------------------------------------------- Critical Store
                   3271: 
                   3272: sub cstore {
1.124     www      3273:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   3274:     my $home='';
                   3275: 
1.168     albertel 3276:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3277: 
1.213     www      3278:     $symb=&symbclean($symb);
1.122     albertel 3279:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      3280: 
1.620     albertel 3281:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3282:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      3283: 
                   3284:     &devalidate($symb,$stuname,$domain);
1.109     www      3285: 
                   3286:     $symb=escape($symb);
1.187     www      3287:     if (!$namespace) { 
1.620     albertel 3288:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      3289:           return ''; 
                   3290:        } 
                   3291:     }
1.620     albertel 3292:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      3293: 
                   3294:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   3295:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 3296: 
1.47      www      3297:     my $namevalue='';
1.800     albertel 3298:     foreach my $key (keys(%$storehash)) {
                   3299:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 3300:     }
1.47      www      3301:     $namevalue=~s/\&$//;
1.187     www      3302:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      3303:     return critical
                   3304:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      3305: }
                   3306: 
1.9       www      3307: # --------------------------------------------------------------------- Restore
                   3308: 
                   3309: sub restore {
1.124     www      3310:     my ($symb,$namespace,$domain,$stuname) = @_;
                   3311:     my $home='';
                   3312: 
1.168     albertel 3313:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      3314: 
1.122     albertel 3315:     if (!$symb) {
                   3316:       unless ($symb=escape(&symbread())) { return ''; }
                   3317:     } else {
1.213     www      3318:       $symb=&escape(&symbclean($symb));
1.122     albertel 3319:     }
1.188     www      3320:     if (!$namespace) { 
1.620     albertel 3321:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      3322:           return ''; 
                   3323:        } 
                   3324:     }
1.620     albertel 3325:     if (!$domain) { $domain=$env{'user.domain'}; }
                   3326:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   3327:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 3328:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   3329: 
1.12      www      3330:     my %returnhash=();
1.800     albertel 3331:     foreach my $line (split(/\&/,$answer)) {
                   3332: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 3333:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 3334:     }
1.75      www      3335:     my $version;
                   3336:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 3337:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   3338:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 3339:        }
1.75      www      3340:     }
1.13      www      3341:     return %returnhash;
1.34      www      3342: }
                   3343: 
                   3344: # ---------------------------------------------------------- Course Description
                   3345: 
                   3346: sub coursedescription {
1.731     albertel 3347:     my ($courseid,$args)=@_;
1.34      www      3348:     $courseid=~s/^\///;
1.49      www      3349:     $courseid=~s/\_/\//g;
1.34      www      3350:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 3351:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 3352:     my $normalid=$cdomain.'_'.$cnum;
                   3353:     # need to always cache even if we get errors otherwise we keep 
                   3354:     # trying and trying and trying to get the course description.
                   3355:     my %envhash=();
                   3356:     my %returnhash=();
1.731     albertel 3357:     
                   3358:     my $expiretime=600;
                   3359:     if ($env{'request.course.id'} eq $normalid) {
                   3360: 	$expiretime=120;
                   3361:     }
                   3362: 
                   3363:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   3364:     if (!$args->{'freshen_cache'}
                   3365: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   3366: 	foreach my $key (keys(%env)) {
                   3367: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   3368: 	    my ($setting) = $1;
                   3369: 	    $returnhash{$setting} = $env{$key};
                   3370: 	}
                   3371: 	return %returnhash;
                   3372:     }
                   3373: 
                   3374:     # get the data agin
                   3375:     if (!$args->{'one_time'}) {
                   3376: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   3377:     }
1.811     albertel 3378: 
1.34      www      3379:     if ($chome ne 'no_host') {
1.302     albertel 3380:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 3381:        if (!exists($returnhash{'con_lost'})) {
                   3382:            $returnhash{'home'}= $chome;
                   3383: 	   $returnhash{'domain'} = $cdomain;
                   3384: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  3385:            if (!defined($returnhash{'type'})) {
                   3386:                $returnhash{'type'} = 'Course';
                   3387:            }
1.130     albertel 3388:            while (my ($name,$value) = each %returnhash) {
1.53      www      3389:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 3390:            }
1.270     www      3391:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      3392:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 3393: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      3394:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   3395:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   3396:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      3397:        }
                   3398:     }
1.731     albertel 3399:     if (!$args->{'one_time'}) {
                   3400: 	&appenv(%envhash);
                   3401:     }
1.302     albertel 3402:     return %returnhash;
1.461     www      3403: }
                   3404: 
                   3405: # -------------------------------------------------See if a user is privileged
                   3406: 
                   3407: sub privileged {
                   3408:     my ($username,$domain)=@_;
                   3409:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   3410: 			&homeserver($username,$domain));
                   3411:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   3412:     my $now=time;
                   3413:     if ($rolesdump ne '') {
1.800     albertel 3414:         foreach my $entry (split(/&/,$rolesdump)) {
                   3415: 	    if ($entry!~/^rolesdef_/) {
                   3416: 		my ($area,$role)=split(/=/,$entry);
1.461     www      3417: 		$area=~s/\_\w\w$//;
                   3418: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   3419: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   3420: 		    my $active=1;
                   3421: 		    if ($tend) {
                   3422: 			if ($tend<$now) { $active=0; }
                   3423: 		    }
                   3424: 		    if ($tstart) {
                   3425: 			if ($tstart>$now) { $active=0; }
                   3426: 		    }
                   3427: 		    if ($active) { return 1; }
                   3428: 		}
                   3429: 	    }
                   3430: 	}
                   3431:     }
                   3432:     return 0;
1.9       www      3433: }
1.1       albertel 3434: 
1.103     harris41 3435: # -------------------------------------------------------- Get user privileges
1.11      www      3436: 
                   3437: sub rolesinit {
                   3438:     my ($domain,$username,$authhost)=@_;
                   3439:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12      www      3440:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11      www      3441:     my %allroles=();
1.678     raeburn  3442:     my %allgroups=();   
1.11      www      3443:     my $now=time;
1.743     albertel 3444:     my %userroles = ('user.login.time' => $now);
1.678     raeburn  3445:     my $group_privs;
1.11      www      3446: 
                   3447:     if ($rolesdump ne '') {
1.800     albertel 3448:         foreach my $entry (split(/&/,$rolesdump)) {
                   3449: 	  if ($entry!~/^rolesdef_/) {
                   3450:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 3451: 	    $area=~s/\_\w\w$//;
1.678     raeburn  3452:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 3453: 	    if ($role=~/^cr/) { 
1.807     albertel 3454: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   3455: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 3456: 		    ($tend,$tstart)=split('_',$trest);
                   3457: 		} else {
                   3458: 		    $trole=$role;
                   3459: 		}
1.678     raeburn  3460:             } elsif ($role =~ m|^gr/|) {
                   3461:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   3462:                 ($trole,$group_privs) = split(/\//,$trole);
                   3463:                 $group_privs = &unescape($group_privs);
1.587     albertel 3464: 	    } else {
                   3465: 		($trole,$tend,$tstart)=split(/_/,$role);
                   3466: 	    }
1.743     albertel 3467: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   3468: 					 $username);
                   3469: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  3470:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   3471:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      3472:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 3473: 		my $spec=$trole.'.'.$area;
                   3474: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   3475: 		if ($trole =~ /^cr\//) {
1.567     raeburn  3476:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  3477:                 } elsif ($trole eq 'gr') {
                   3478:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 3479: 		} else {
1.567     raeburn  3480:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 3481: 		}
1.12      www      3482:             }
1.662     raeburn  3483:           }
1.191     harris41 3484:         }
1.743     albertel 3485:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   3486:         $userroles{'user.adv'}    = $adv;
                   3487: 	$userroles{'user.author'} = $author;
1.620     albertel 3488:         $env{'user.adv'}=$adv;
1.11      www      3489:     }
1.743     albertel 3490:     return \%userroles;  
1.11      www      3491: }
                   3492: 
1.567     raeburn  3493: sub set_arearole {
                   3494:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   3495: # log the associated role with the area
                   3496:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 3497:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  3498: }
                   3499: 
                   3500: sub custom_roleprivs {
                   3501:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   3502:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   3503:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 3504:     if (&hostname($homsvr) ne '') {
1.567     raeburn  3505:         my ($rdummy,$roledef)=
                   3506:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   3507:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   3508:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   3509:             if (defined($syspriv)) {
                   3510:                 $$allroles{'cm./'}.=':'.$syspriv;
                   3511:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   3512:             }
                   3513:             if ($tdomain ne '') {
                   3514:                 if (defined($dompriv)) {
                   3515:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   3516:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   3517:                 }
                   3518:                 if (($trest ne '') && (defined($coursepriv))) {
                   3519:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   3520:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   3521:                 }
                   3522:             }
                   3523:         }
                   3524:     }
                   3525: }
                   3526: 
1.678     raeburn  3527: sub group_roleprivs {
                   3528:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   3529:     my $access = 1;
                   3530:     my $now = time;
                   3531:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   3532:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   3533:     if ($access) {
1.811     albertel 3534:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  3535:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   3536:     }
                   3537: }
1.567     raeburn  3538: 
                   3539: sub standard_roleprivs {
                   3540:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   3541:     if (defined($pr{$trole.':s'})) {
                   3542:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   3543:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   3544:     }
                   3545:     if ($tdomain ne '') {
                   3546:         if (defined($pr{$trole.':d'})) {
                   3547:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3548:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3549:         }
                   3550:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   3551:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   3552:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   3553:         }
                   3554:     }
                   3555: }
                   3556: 
                   3557: sub set_userprivs {
1.678     raeburn  3558:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  3559:     my $author=0;
                   3560:     my $adv=0;
1.678     raeburn  3561:     my %grouproles = ();
                   3562:     if (keys(%{$allgroups}) > 0) {
                   3563:         foreach my $role (keys %{$allroles}) {
1.681     raeburn  3564:             my ($trole,$area,$sec,$extendedarea);
1.881     raeburn  3565:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
1.678     raeburn  3566:                 $trole = $1;
                   3567:                 $area = $2;
1.681     raeburn  3568:                 $sec = $3;
                   3569:                 $extendedarea = $area.$sec;
                   3570:                 if (exists($$allgroups{$area})) {
                   3571:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   3572:                         my $spec = $trole.'.'.$extendedarea;
                   3573:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   3574:                                                 $$allgroups{$area}{$group};
1.678     raeburn  3575:                     }
                   3576:                 }
                   3577:             }
                   3578:         }
                   3579:     }
1.800     albertel 3580:     foreach my $group (keys(%grouproles)) {
                   3581:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  3582:     }
1.800     albertel 3583:     foreach my $role (keys(%{$allroles})) {
                   3584:         my %thesepriv;
1.941     raeburn  3585:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 3586:         foreach my $item (split(/:/,$$allroles{$role})) {
                   3587:             if ($item ne '') {
                   3588:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  3589:                 if ($restrictions eq '') {
                   3590:                     $thesepriv{$privilege}='F';
                   3591:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   3592:                     $thesepriv{$privilege}.=$restrictions;
                   3593:                 }
                   3594:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   3595:             }
                   3596:         }
                   3597:         my $thesestr='';
1.800     albertel 3598:         foreach my $priv (keys(%thesepriv)) {
                   3599: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   3600: 	}
                   3601:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  3602:     }
                   3603:     return ($author,$adv);
                   3604: }
                   3605: 
1.12      www      3606: # --------------------------------------------------------------- get interface
                   3607: 
                   3608: sub get {
1.131     albertel 3609:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3610:    my $items='';
1.800     albertel 3611:    foreach my $item (@$storearr) {
                   3612:        $items.=&escape($item).'&';
1.191     harris41 3613:    }
1.12      www      3614:    $items=~s/\&$//;
1.620     albertel 3615:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3616:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 3617:    my $uhome=&homeserver($uname,$udomain);
                   3618: 
1.133     albertel 3619:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3620:    my @pairs=split(/\&/,$rep);
1.273     albertel 3621:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   3622:      return @pairs;
                   3623:    }
1.15      www      3624:    my %returnhash=();
1.42      www      3625:    my $i=0;
1.800     albertel 3626:    foreach my $item (@$storearr) {
                   3627:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3628:       $i++;
1.191     harris41 3629:    }
1.15      www      3630:    return %returnhash;
1.27      www      3631: }
                   3632: 
                   3633: # --------------------------------------------------------------- del interface
                   3634: 
                   3635: sub del {
1.133     albertel 3636:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      3637:    my $items='';
1.800     albertel 3638:    foreach my $item (@$storearr) {
                   3639:        $items.=&escape($item).'&';
1.191     harris41 3640:    }
1.27      www      3641:    $items=~s/\&$//;
1.620     albertel 3642:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3643:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3644:    my $uhome=&homeserver($uname,$udomain);
                   3645: 
                   3646:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3647: }
                   3648: 
                   3649: # -------------------------------------------------------------- dump interface
                   3650: 
                   3651: sub dump {
1.755     albertel 3652:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   3653:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3654:     if (!$uname) { $uname=$env{'user.name'}; }
                   3655:     my $uhome=&homeserver($uname,$udomain);
                   3656:     if ($regexp) {
                   3657: 	$regexp=&escape($regexp);
                   3658:     } else {
                   3659: 	$regexp='.';
                   3660:     }
                   3661:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3662:     my @pairs=split(/\&/,$rep);
                   3663:     my %returnhash=();
                   3664:     foreach my $item (@pairs) {
                   3665: 	my ($key,$value)=split(/=/,$item,2);
                   3666: 	$key = &unescape($key);
                   3667: 	next if ($key =~ /^error: 2 /);
                   3668: 	$returnhash{$key}=&thaw_unescape($value);
                   3669:     }
                   3670:     return %returnhash;
1.407     www      3671: }
                   3672: 
1.717     albertel 3673: # --------------------------------------------------------- dumpstore interface
                   3674: 
                   3675: sub dumpstore {
                   3676:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 3677:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3678:    if (!$uname) { $uname=$env{'user.name'}; }
                   3679:    my $uhome=&homeserver($uname,$udomain);
                   3680:    if ($regexp) {
                   3681:        $regexp=&escape($regexp);
                   3682:    } else {
                   3683:        $regexp='.';
                   3684:    }
                   3685:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3686:    my @pairs=split(/\&/,$rep);
                   3687:    my %returnhash=();
                   3688:    foreach my $item (@pairs) {
                   3689:        my ($key,$value)=split(/=/,$item,2);
                   3690:        next if ($key =~ /^error: 2 /);
                   3691:        $returnhash{$key}=&thaw_unescape($value);
                   3692:    }
                   3693:    return %returnhash;
1.717     albertel 3694: }
                   3695: 
1.407     www      3696: # -------------------------------------------------------------- keys interface
                   3697: 
                   3698: sub getkeys {
                   3699:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 3700:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3701:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      3702:    my $uhome=&homeserver($uname,$udomain);
                   3703:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   3704:    my @keyarray=();
1.800     albertel 3705:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  3706:       next if ($key =~ /^error: 2 /);
1.800     albertel 3707:       push(@keyarray,&unescape($key));
1.407     www      3708:    }
                   3709:    return @keyarray;
1.318     matthew  3710: }
                   3711: 
1.319     matthew  3712: # --------------------------------------------------------------- currentdump
                   3713: sub currentdump {
1.328     matthew  3714:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 3715:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   3716:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   3717:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  3718:    my $uhome = &homeserver($sname,$sdom);
                   3719:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  3720:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  3721:    #
1.318     matthew  3722:    my %returnhash=();
1.319     matthew  3723:    #
                   3724:    if ($rep eq "unknown_cmd") { 
                   3725:        # an old lond will not know currentdump
                   3726:        # Do a dump and make it look like a currentdump
1.822     albertel 3727:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  3728:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   3729:        my %hash = @tmp;
                   3730:        @tmp=();
1.424     matthew  3731:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  3732:    } else {
                   3733:        my @pairs=split(/\&/,$rep);
1.800     albertel 3734:        foreach my $pair (@pairs) {
                   3735:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  3736:            my ($symb,$param) = split(/:/,$key);
                   3737:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 3738:                                                         &thaw_unescape($value);
1.319     matthew  3739:        }
1.191     harris41 3740:    }
1.12      www      3741:    return %returnhash;
1.424     matthew  3742: }
                   3743: 
                   3744: sub convert_dump_to_currentdump{
                   3745:     my %hash = %{shift()};
                   3746:     my %returnhash;
                   3747:     # Code ripped from lond, essentially.  The only difference
                   3748:     # here is the unescaping done by lonnet::dump().  Conceivably
                   3749:     # we might run in to problems with parameter names =~ /^v\./
                   3750:     while (my ($key,$value) = each(%hash)) {
                   3751:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 3752: 	$symb  = &unescape($symb);
                   3753: 	$param = &unescape($param);
1.424     matthew  3754:         next if ($v eq 'version' || $symb eq 'keys');
                   3755:         next if (exists($returnhash{$symb}) &&
                   3756:                  exists($returnhash{$symb}->{$param}) &&
                   3757:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   3758:         $returnhash{$symb}->{$param}=$value;
                   3759:         $returnhash{$symb}->{'v.'.$param}=$v;
                   3760:     }
                   3761:     #
                   3762:     # Remove all of the keys in the hashes which keep track of
                   3763:     # the version of the parameter.
                   3764:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   3765:         # use a foreach because we are going to delete from the hash.
                   3766:         foreach my $key (keys(%$param_hash)) {
                   3767:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   3768:         }
                   3769:     }
                   3770:     return \%returnhash;
1.12      www      3771: }
                   3772: 
1.627     albertel 3773: # ------------------------------------------------------ critical inc interface
                   3774: 
                   3775: sub cinc {
                   3776:     return &inc(@_,'critical');
                   3777: }
                   3778: 
1.449     matthew  3779: # --------------------------------------------------------------- inc interface
                   3780: 
                   3781: sub inc {
1.627     albertel 3782:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 3783:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3784:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  3785:     my $uhome=&homeserver($uname,$udomain);
                   3786:     my $items='';
                   3787:     if (! ref($store)) {
                   3788:         # got a single value, so use that instead
                   3789:         $items = &escape($store).'=&';
                   3790:     } elsif (ref($store) eq 'SCALAR') {
                   3791:         $items = &escape($$store).'=&';        
                   3792:     } elsif (ref($store) eq 'ARRAY') {
                   3793:         $items = join('=&',map {&escape($_);} @{$store});
                   3794:     } elsif (ref($store) eq 'HASH') {
                   3795:         while (my($key,$value) = each(%{$store})) {
                   3796:             $items.= &escape($key).'='.&escape($value).'&';
                   3797:         }
                   3798:     }
                   3799:     $items=~s/\&$//;
1.627     albertel 3800:     if ($critical) {
                   3801: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3802:     } else {
                   3803: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3804:     }
1.449     matthew  3805: }
                   3806: 
1.12      www      3807: # --------------------------------------------------------------- put interface
                   3808: 
                   3809: sub put {
1.134     albertel 3810:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3811:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3812:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3813:    my $uhome=&homeserver($uname,$udomain);
1.12      www      3814:    my $items='';
1.800     albertel 3815:    foreach my $item (keys(%$storehash)) {
                   3816:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3817:    }
1.12      www      3818:    $items=~s/\&$//;
1.134     albertel 3819:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      3820: }
                   3821: 
1.631     albertel 3822: # ------------------------------------------------------------ newput interface
                   3823: 
                   3824: sub newput {
                   3825:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   3826:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3827:    if (!$uname) { $uname=$env{'user.name'}; }
                   3828:    my $uhome=&homeserver($uname,$udomain);
                   3829:    my $items='';
                   3830:    foreach my $key (keys(%$storehash)) {
                   3831:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   3832:    }
                   3833:    $items=~s/\&$//;
                   3834:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   3835: }
                   3836: 
                   3837: # ---------------------------------------------------------  putstore interface
                   3838: 
1.524     raeburn  3839: sub putstore {
1.715     albertel 3840:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 3841:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3842:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  3843:    my $uhome=&homeserver($uname,$udomain);
                   3844:    my $items='';
1.715     albertel 3845:    foreach my $key (keys(%$storehash)) {
                   3846:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  3847:    }
1.715     albertel 3848:    $items=~s/\&$//;
1.716     albertel 3849:    my $esc_symb=&escape($symb);
                   3850:    my $esc_v=&escape($version);
1.715     albertel 3851:    my $reply =
1.716     albertel 3852:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 3853: 	      $uhome);
                   3854:    if ($reply eq 'unknown_cmd') {
1.716     albertel 3855:        # gfall back to way things use to be done
1.715     albertel 3856:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   3857: 			    $uname);
1.524     raeburn  3858:    }
1.715     albertel 3859:    return $reply;
                   3860: }
                   3861: 
                   3862: sub old_putstore {
1.716     albertel 3863:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   3864:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3865:     if (!$uname) { $uname=$env{'user.name'}; }
                   3866:     my $uhome=&homeserver($uname,$udomain);
                   3867:     my %newstorehash;
1.800     albertel 3868:     foreach my $item (keys(%$storehash)) {
                   3869: 	my $key = $version.':'.&escape($symb).':'.$item;
                   3870: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 3871:     }
                   3872:     my $items='';
                   3873:     my %allitems = ();
1.800     albertel 3874:     foreach my $item (keys(%newstorehash)) {
                   3875: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 3876: 	    my $key = $1.':keys:'.$2;
                   3877: 	    $allitems{$key} .= $3.':';
                   3878: 	}
1.800     albertel 3879: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 3880:     }
1.800     albertel 3881:     foreach my $item (keys(%allitems)) {
                   3882: 	$allitems{$item} =~ s/\:$//;
                   3883: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 3884:     }
                   3885:     $items=~s/\&$//;
                   3886:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  3887: }
                   3888: 
1.47      www      3889: # ------------------------------------------------------ critical put interface
                   3890: 
                   3891: sub cput {
1.134     albertel 3892:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3893:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3894:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3895:    my $uhome=&homeserver($uname,$udomain);
1.47      www      3896:    my $items='';
1.800     albertel 3897:    foreach my $item (keys(%$storehash)) {
                   3898:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3899:    }
1.47      www      3900:    $items=~s/\&$//;
1.134     albertel 3901:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3902: }
                   3903: 
                   3904: # -------------------------------------------------------------- eget interface
                   3905: 
                   3906: sub eget {
1.133     albertel 3907:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3908:    my $items='';
1.800     albertel 3909:    foreach my $item (@$storearr) {
                   3910:        $items.=&escape($item).'&';
1.191     harris41 3911:    }
1.12      www      3912:    $items=~s/\&$//;
1.620     albertel 3913:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3914:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3915:    my $uhome=&homeserver($uname,$udomain);
                   3916:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3917:    my @pairs=split(/\&/,$rep);
                   3918:    my %returnhash=();
1.42      www      3919:    my $i=0;
1.800     albertel 3920:    foreach my $item (@$storearr) {
                   3921:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3922:       $i++;
1.191     harris41 3923:    }
1.12      www      3924:    return %returnhash;
                   3925: }
                   3926: 
1.667     albertel 3927: # ------------------------------------------------------------ tmpput interface
                   3928: sub tmpput {
1.802     raeburn  3929:     my ($storehash,$server,$context)=@_;
1.667     albertel 3930:     my $items='';
1.800     albertel 3931:     foreach my $item (keys(%$storehash)) {
                   3932: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 3933:     }
                   3934:     $items=~s/\&$//;
1.802     raeburn  3935:     if (defined($context)) {
                   3936:         $items .= ':'.&escape($context);
                   3937:     }
1.667     albertel 3938:     return &reply("tmpput:$items",$server);
                   3939: }
                   3940: 
                   3941: # ------------------------------------------------------------ tmpget interface
                   3942: sub tmpget {
1.688     albertel 3943:     my ($token,$server)=@_;
                   3944:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3945:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 3946:     my %returnhash;
                   3947:     foreach my $item (split(/\&/,$rep)) {
                   3948: 	my ($key,$value)=split(/=/,$item);
                   3949: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   3950:     }
                   3951:     return %returnhash;
                   3952: }
                   3953: 
1.688     albertel 3954: # ------------------------------------------------------------ tmpget interface
                   3955: sub tmpdel {
                   3956:     my ($token,$server)=@_;
                   3957:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3958:     return &reply("tmpdel:$token",$server);
                   3959: }
                   3960: 
1.765     albertel 3961: # -------------------------------------------------- portfolio access checking
                   3962: 
                   3963: sub portfolio_access {
1.766     albertel 3964:     my ($requrl) = @_;
1.765     albertel 3965:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   3966:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  3967:     if ($result) {
                   3968:         my %setters;
                   3969:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3970:             my ($startblock,$endblock) =
                   3971:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   3972:             if ($startblock && $endblock) {
                   3973:                 return 'B';
                   3974:             }
                   3975:         } else {
                   3976:             my ($startblock,$endblock) =
                   3977:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   3978:             if ($startblock && $endblock) {
                   3979:                 return 'B';
                   3980:             }
                   3981:         }
                   3982:     }
1.765     albertel 3983:     if ($result eq 'ok') {
1.766     albertel 3984:        return 'F';
1.765     albertel 3985:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 3986:        return 'A';
1.765     albertel 3987:     }
1.766     albertel 3988:     return '';
1.765     albertel 3989: }
                   3990: 
                   3991: sub get_portfolio_access {
1.767     albertel 3992:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   3993: 
                   3994:     if (!ref($access_hash)) {
                   3995: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   3996: 	my %access_controls = &get_access_controls($current_perms,$group,
                   3997: 						   $file_name);
                   3998: 	$access_hash = $access_controls{$file_name};
                   3999:     }
                   4000: 
1.765     albertel 4001:     my ($public,$guest,@domains,@users,@courses,@groups);
                   4002:     my $now = time;
                   4003:     if (ref($access_hash) eq 'HASH') {
                   4004:         foreach my $key (keys(%{$access_hash})) {
                   4005:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   4006:             if ($start > $now) {
                   4007:                 next;
                   4008:             }
                   4009:             if ($end && $end<$now) {
                   4010:                 next;
                   4011:             }
                   4012:             if ($scope eq 'public') {
                   4013:                 $public = $key;
                   4014:                 last;
                   4015:             } elsif ($scope eq 'guest') {
                   4016:                 $guest = $key;
                   4017:             } elsif ($scope eq 'domains') {
                   4018:                 push(@domains,$key);
                   4019:             } elsif ($scope eq 'users') {
                   4020:                 push(@users,$key);
                   4021:             } elsif ($scope eq 'course') {
                   4022:                 push(@courses,$key);
                   4023:             } elsif ($scope eq 'group') {
                   4024:                 push(@groups,$key);
                   4025:             }
                   4026:         }
                   4027:         if ($public) {
                   4028:             return 'ok';
                   4029:         }
                   4030:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   4031:             if ($guest) {
                   4032:                 return $guest;
                   4033:             }
                   4034:         } else {
                   4035:             if (@domains > 0) {
                   4036:                 foreach my $domkey (@domains) {
                   4037:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   4038:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   4039:                             return 'ok';
                   4040:                         }
                   4041:                     }
                   4042:                 }
                   4043:             }
                   4044:             if (@users > 0) {
                   4045:                 foreach my $userkey (@users) {
1.865     raeburn  4046:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   4047:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   4048:                             if (ref($item) eq 'HASH') {
                   4049:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   4050:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   4051:                                     return 'ok';
                   4052:                                 }
                   4053:                             }
                   4054:                         }
                   4055:                     } 
1.765     albertel 4056:                 }
                   4057:             }
                   4058:             my %roleshash;
                   4059:             my @courses_and_groups = @courses;
                   4060:             push(@courses_and_groups,@groups); 
                   4061:             if (@courses_and_groups > 0) {
                   4062:                 my (%allgroups,%allroles); 
                   4063:                 my ($start,$end,$role,$sec,$group);
                   4064:                 foreach my $envkey (%env) {
1.811     albertel 4065:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4066:                         my $cid = $2.'_'.$3; 
                   4067:                         if ($1 eq 'gr') {
                   4068:                             $group = $4;
                   4069:                             $allgroups{$cid}{$group} = $env{$envkey};
                   4070:                         } else {
                   4071:                             if ($4 eq '') {
                   4072:                                 $sec = 'none';
                   4073:                             } else {
                   4074:                                 $sec = $4;
                   4075:                             }
                   4076:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4077:                         }
1.811     albertel 4078:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 4079:                         my $cid = $2.'_'.$3;
                   4080:                         if ($4 eq '') {
                   4081:                             $sec = 'none';
                   4082:                         } else {
                   4083:                             $sec = $4;
                   4084:                         }
                   4085:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   4086:                     }
                   4087:                 }
                   4088:                 if (keys(%allroles) == 0) {
                   4089:                     return;
                   4090:                 }
                   4091:                 foreach my $key (@courses_and_groups) {
                   4092:                     my %content = %{$$access_hash{$key}};
                   4093:                     my $cnum = $content{'number'};
                   4094:                     my $cdom = $content{'domain'};
                   4095:                     my $cid = $cdom.'_'.$cnum;
                   4096:                     if (!exists($allroles{$cid})) {
                   4097:                         next;
                   4098:                     }    
                   4099:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   4100:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   4101:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   4102:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   4103:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   4104:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   4105:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   4106:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   4107:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   4108:                                         if (grep/^all$/,@sections) {
                   4109:                                             return 'ok';
                   4110:                                         } else {
                   4111:                                             if (grep/^$sec$/,@sections) {
                   4112:                                                 return 'ok';
                   4113:                                             }
                   4114:                                         }
                   4115:                                     }
                   4116:                                 }
                   4117:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   4118:                                     if (grep/^none$/,@groups) {
                   4119:                                         return 'ok';
                   4120:                                     }
                   4121:                                 } else {
                   4122:                                     if (grep/^all$/,@groups) {
                   4123:                                         return 'ok';
                   4124:                                     } 
                   4125:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   4126:                                         if (grep/^$group$/,@groups) {
                   4127:                                             return 'ok';
                   4128:                                         }
                   4129:                                     }
                   4130:                                 } 
                   4131:                             }
                   4132:                         }
                   4133:                     }
                   4134:                 }
                   4135:             }
                   4136:             if ($guest) {
                   4137:                 return $guest;
                   4138:             }
                   4139:         }
                   4140:     }
                   4141:     return;
                   4142: }
                   4143: 
                   4144: sub course_group_datechecker {
                   4145:     my ($dates,$now,$status) = @_;
                   4146:     my ($start,$end) = split(/\./,$dates);
                   4147:     if (!$start && !$end) {
                   4148:         return 'ok';
                   4149:     }
                   4150:     if (grep/^active$/,@{$status}) {
                   4151:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   4152:             return 'ok';
                   4153:         }
                   4154:     }
                   4155:     if (grep/^previous$/,@{$status}) {
                   4156:         if ($end > $now ) {
                   4157:             return 'ok';
                   4158:         }
                   4159:     }
                   4160:     if (grep/^future$/,@{$status}) {
                   4161:         if ($start > $now) {
                   4162:             return 'ok';
                   4163:         }
                   4164:     }
                   4165:     return; 
                   4166: }
                   4167: 
                   4168: sub parse_portfolio_url {
                   4169:     my ($url) = @_;
                   4170: 
                   4171:     my ($type,$udom,$unum,$group,$file_name);
                   4172:     
1.823     albertel 4173:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 4174: 	$type = 1;
                   4175:         $udom = $1;
                   4176:         $unum = $2;
                   4177:         $file_name = $3;
1.823     albertel 4178:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 4179: 	$type = 2;
                   4180:         $udom = $1;
                   4181:         $unum = $2;
                   4182:         $group = $3;
                   4183:         $file_name = $3.'/'.$4;
                   4184:     }
                   4185:     if (wantarray) {
                   4186: 	return ($type,$udom,$unum,$file_name,$group);
                   4187:     }
                   4188:     return $type;
                   4189: }
                   4190: 
                   4191: sub is_portfolio_url {
                   4192:     my ($url) = @_;
                   4193:     return scalar(&parse_portfolio_url($url));
                   4194: }
                   4195: 
1.798     raeburn  4196: sub is_portfolio_file {
                   4197:     my ($file) = @_;
1.820     raeburn  4198:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  4199:         return 1;
                   4200:     }
                   4201:     return;
                   4202: }
                   4203: 
                   4204: 
1.341     www      4205: # ---------------------------------------------- Custom access rule evaluation
                   4206: 
                   4207: sub customaccess {
                   4208:     my ($priv,$uri)=@_;
1.807     albertel 4209:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      4210:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 4211:     $udom = &LONCAPA::clean_domain($udom);
                   4212:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      4213:     my $access=0;
1.800     albertel 4214:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 4215: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   4216: 	if ($type eq 'user') {
                   4217: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 4218: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 4219: 		if ($tdom) {
                   4220: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   4221: 		}
1.896     albertel 4222: 		if ($tuname) {
                   4223: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 4224: 		}
                   4225: 		$access=($effect eq 'allow');
                   4226: 		last;
                   4227: 	    }
                   4228: 	} else {
                   4229: 	    if ($role) {
                   4230: 		if ($role ne $urole) { next; }
                   4231: 	    }
                   4232: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   4233: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   4234: 		if ($tdom) {
                   4235: 		    if ($tdom ne $udom) { next; }
                   4236: 		}
                   4237: 		if ($tcrs) {
                   4238: 		    if ($tcrs ne $ucrs) { next; }
                   4239: 		}
                   4240: 		if ($tsec) {
                   4241: 		    if ($tsec ne $usec) { next; }
                   4242: 		}
                   4243: 		$access=($effect eq 'allow');
                   4244: 		last;
                   4245: 	    }
                   4246: 	    if ($realm eq '' && $role eq '') {
                   4247: 		$access=($effect eq 'allow');
                   4248: 	    }
1.402     bowersj2 4249: 	}
1.341     www      4250:     }
                   4251:     return $access;
                   4252: }
                   4253: 
1.103     harris41 4254: # ------------------------------------------------- Check for a user privilege
1.12      www      4255: 
                   4256: sub allowed {
1.810     raeburn  4257:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 4258:     my $ver_orguri=$uri;
1.439     www      4259:     $uri=&deversion($uri);
1.152     www      4260:     my $orguri=$uri;
1.52      www      4261:     $uri=&declutter($uri);
1.809     raeburn  4262: 
1.810     raeburn  4263:     if ($priv eq 'evb') {
                   4264: # Evade communication block restrictions for specified role in a course
                   4265:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   4266:             return $1;
                   4267:         } else {
                   4268:             return;
                   4269:         }
                   4270:     }
                   4271: 
1.620     albertel 4272:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      4273: # Free bre access to adm and meta resources
1.775     albertel 4274:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 4275: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   4276: 	&& ($priv eq 'bre')) {
1.14      www      4277: 	return 'F';
1.159     www      4278:     }
                   4279: 
1.545     banghart 4280: # Free bre access to user's own portfolio contents
1.714     raeburn  4281:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  4282:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  4283: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  4284:         my %setters;
                   4285:         my ($startblock,$endblock) = 
                   4286:             &Apache::loncommon::blockcheck(\%setters,'port');
                   4287:         if ($startblock && $endblock) {
                   4288:             return 'B';
                   4289:         } else {
                   4290:             return 'F';
                   4291:         }
1.545     banghart 4292:     }
                   4293: 
1.762     raeburn  4294: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  4295:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   4296:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   4297:         if (exists($env{'request.course.id'})) {
                   4298:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4299:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4300:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   4301:                 my $courseprivid=$env{'request.course.id'};
                   4302:                 $courseprivid=~s/\_/\//;
                   4303:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   4304:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   4305:                     return $1; 
1.762     raeburn  4306:                 } else {
                   4307:                     if ($env{'request.course.sec'}) {
                   4308:                         $courseprivid.='/'.$env{'request.course.sec'};
                   4309:                     }
                   4310:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   4311:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   4312:                         return $2;
                   4313:                     }
1.714     raeburn  4314:                 }
                   4315:             }
                   4316:         }
                   4317:     }
                   4318: 
1.159     www      4319: # Free bre to public access
                   4320: 
                   4321:     if ($priv eq 'bre') {
1.238     www      4322:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 4323: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      4324:            return 'F'; 
                   4325:         }
1.238     www      4326:         if ($copyright eq 'priv') {
                   4327:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4328: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      4329: 		return '';
                   4330:             }
                   4331:         }
                   4332:         if ($copyright eq 'domain') {
                   4333:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 4334: 	    unless (($env{'user.domain'} eq $1) ||
                   4335:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      4336: 		return '';
                   4337:             }
1.262     matthew  4338:         }
1.620     albertel 4339:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  4340:             # Library role, so allow browsing of resources in this domain.
                   4341:             return 'F';
1.238     www      4342:         }
1.341     www      4343:         if ($copyright eq 'custom') {
                   4344: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   4345:         }
1.14      www      4346:     }
1.264     matthew  4347:     # Domain coordinator is trying to create a course
1.620     albertel 4348:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  4349:         # uri is the requested domain in this case.
                   4350:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  4351:         # a role of dc for the domain in question.
1.620     albertel 4352:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  4353:     }
1.29      www      4354: 
1.52      www      4355:     my $thisallowed='';
                   4356:     my $statecond=0;
                   4357:     my $courseprivid='';
                   4358: 
                   4359: # Course
                   4360: 
1.620     albertel 4361:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4362:        $thisallowed.=$1;
                   4363:     }
1.29      www      4364: 
1.52      www      4365: # Domain
                   4366: 
1.620     albertel 4367:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 4368:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4369:        $thisallowed.=$1;
                   4370:     }
1.52      www      4371: 
                   4372: # Course: uri itself is a course
1.66      www      4373:     my $courseuri=$uri;
                   4374:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      4375:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      4376: 
1.620     albertel 4377:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 4378:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      4379:        $thisallowed.=$1;
                   4380:     }
1.29      www      4381: 
1.665     albertel 4382: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 4383: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 4384:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 4385: 	$thisallowed='';
1.671     raeburn  4386:         my ($match)=&is_on_map($uri);
                   4387:         if ($match) {
                   4388:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   4389:                   =~/\Q$priv\E\&([^\:]*)/) {
                   4390:                 $thisallowed.=$1;
                   4391:             }
                   4392:         } else {
1.705     albertel 4393:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  4394:             if ($refuri) {
                   4395:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  4396:                     $thisallowed='F';
1.671     raeburn  4397:                 } else {
                   4398:                     $refuri=&declutter($refuri);
                   4399:                     my ($match) = &is_on_map($refuri);
                   4400:                     if ($match) {
                   4401:                         $thisallowed='F';
                   4402:                     }
1.669     raeburn  4403:                 }
1.671     raeburn  4404:             }
                   4405:         }
1.314     www      4406:     }
1.492     albertel 4407: 
1.766     albertel 4408:     if ($priv eq 'bre'
                   4409: 	&& $thisallowed ne 'F' 
                   4410: 	&& $thisallowed ne '2'
                   4411: 	&& &is_portfolio_url($uri)) {
                   4412: 	$thisallowed = &portfolio_access($uri);
                   4413:     }
                   4414:     
1.52      www      4415: # Full access at system, domain or course-wide level? Exit.
1.29      www      4416: 
                   4417:     if ($thisallowed=~/F/) {
                   4418: 	return 'F';
                   4419:     }
                   4420: 
1.52      www      4421: # If this is generating or modifying users, exit with special codes
1.29      www      4422: 
1.643     www      4423:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   4424: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 4425: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      4426: # no author name given, so this just checks on the general right to make a co-author in this domain
                   4427: 	    unless ($auname) { return $thisallowed; }
                   4428: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 4429: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   4430: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   4431: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   4432: 	}
1.52      www      4433: 	return $thisallowed;
                   4434:     }
                   4435: #
1.103     harris41 4436: # Gathered so far: system, domain and course wide privileges
1.52      www      4437: #
                   4438: # Course: See if uri or referer is an individual resource that is part of 
                   4439: # the course
                   4440: 
1.620     albertel 4441:     if ($env{'request.course.id'}) {
1.232     www      4442: 
1.620     albertel 4443:        $courseprivid=$env{'request.course.id'};
                   4444:        if ($env{'request.course.sec'}) {
                   4445:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      4446:        }
                   4447:        $courseprivid=~s/\_/\//;
                   4448:        my $checkreferer=1;
1.232     www      4449:        my ($match,$cond)=&is_on_map($uri);
                   4450:        if ($match) {
                   4451:            $statecond=$cond;
1.620     albertel 4452:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4453:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4454:                $thisallowed.=$1;
                   4455:                $checkreferer=0;
                   4456:            }
1.29      www      4457:        }
1.83      www      4458:        
1.148     www      4459:        if ($checkreferer) {
1.620     albertel 4460: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      4461:             unless ($refuri) {
1.800     albertel 4462:                 foreach my $key (keys(%env)) {
                   4463: 		    if ($key=~/^httpref\..*\*/) {
                   4464: 			my $pattern=$key;
1.156     www      4465:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      4466:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   4467:                         $pattern=~s/\//\\\//g;
1.152     www      4468:                         if ($orguri=~/$pattern/) {
1.800     albertel 4469: 			    $refuri=$env{$key};
1.148     www      4470:                         }
                   4471:                     }
1.191     harris41 4472:                 }
1.148     www      4473:             }
1.232     www      4474: 
1.148     www      4475:          if ($refuri) { 
1.152     www      4476: 	  $refuri=&declutter($refuri);
1.232     www      4477:           my ($match,$cond)=&is_on_map($refuri);
                   4478:             if ($match) {
                   4479:               my $refstatecond=$cond;
1.620     albertel 4480:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 4481:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      4482:                   $thisallowed.=$1;
1.53      www      4483:                   $uri=$refuri;
                   4484:                   $statecond=$refstatecond;
1.52      www      4485:               }
                   4486:           }
1.148     www      4487:         }
1.29      www      4488:        }
1.52      www      4489:    }
1.29      www      4490: 
1.52      www      4491: #
1.103     harris41 4492: # Gathered now: all privileges that could apply, and condition number
1.52      www      4493: # 
                   4494: #
                   4495: # Full or no access?
                   4496: #
1.29      www      4497: 
1.52      www      4498:     if ($thisallowed=~/F/) {
                   4499: 	return 'F';
                   4500:     }
1.29      www      4501: 
1.52      www      4502:     unless ($thisallowed) {
                   4503:         return '';
                   4504:     }
1.29      www      4505: 
1.52      www      4506: # Restrictions exist, deal with them
                   4507: #
                   4508: #   C:according to course preferences
                   4509: #   R:according to resource settings
                   4510: #   L:unless locked
                   4511: #   X:according to user session state
                   4512: #
                   4513: 
                   4514: # Possibly locked functionality, check all courses
1.54      www      4515: # Locks might take effect only after 10 minutes cache expiration for other
                   4516: # courses, and 2 minutes for current course
1.52      www      4517: 
                   4518:     my $envkey;
                   4519:     if ($thisallowed=~/L/) {
1.620     albertel 4520:         foreach $envkey (keys %env) {
1.54      www      4521:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   4522:                my $courseid=$2;
                   4523:                my $roleid=$1.'.'.$2;
1.92      www      4524:                $courseid=~s/^\///;
1.54      www      4525:                my $expiretime=600;
1.620     albertel 4526:                if ($env{'request.role'} eq $roleid) {
1.54      www      4527: 		  $expiretime=120;
                   4528:                }
                   4529: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   4530:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 4531:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 4532: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      4533:                }
1.620     albertel 4534:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4535:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   4536: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   4537:                        &log($env{'user.domain'},$env{'user.name'},
                   4538:                             $env{'user.home'},
1.57      www      4539:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      4540:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4541:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4542: 		       return '';
                   4543:                    }
                   4544:                }
1.620     albertel 4545:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   4546:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   4547: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   4548:                        &log($env{'user.domain'},$env{'user.name'},
                   4549:                             $env{'user.home'},
1.57      www      4550:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      4551:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4552:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4553: 		       return '';
                   4554:                    }
                   4555:                }
                   4556: 	   }
1.29      www      4557:        }
1.52      www      4558:     }
                   4559:    
                   4560: #
                   4561: # Rest of the restrictions depend on selected course
                   4562: #
                   4563: 
1.620     albertel 4564:     unless ($env{'request.course.id'}) {
1.766     albertel 4565: 	if ($thisallowed eq 'A') {
                   4566: 	    return 'A';
1.814     raeburn  4567:         } elsif ($thisallowed eq 'B') {
                   4568:             return 'B';
1.766     albertel 4569: 	} else {
                   4570: 	    return '1';
                   4571: 	}
1.52      www      4572:     }
1.29      www      4573: 
1.52      www      4574: #
                   4575: # Now user is definitely in a course
                   4576: #
1.53      www      4577: 
                   4578: 
                   4579: # Course preferences
                   4580: 
                   4581:    if ($thisallowed=~/C/) {
1.620     albertel 4582:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   4583:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   4584:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 4585: 	   =~/\Q$rolecode\E/) {
1.689     albertel 4586: 	   if ($priv ne 'pch') { 
                   4587: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4588: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   4589: 			$env{'request.course.id'});
                   4590: 	   }
1.237     www      4591:            return '';
                   4592:        }
                   4593: 
1.620     albertel 4594:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 4595: 	   =~/\Q$unamedom\E/) {
1.689     albertel 4596: 	   if ($priv ne 'pch') { 
                   4597: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   4598: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   4599: 			$env{'request.course.id'});
                   4600: 	   }
1.54      www      4601:            return '';
                   4602:        }
1.53      www      4603:    }
                   4604: 
                   4605: # Resource preferences
                   4606: 
                   4607:    if ($thisallowed=~/R/) {
1.620     albertel 4608:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 4609:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 4610: 	   if ($priv ne 'pch') { 
                   4611: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4612: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   4613: 	   }
                   4614: 	   return '';
1.54      www      4615:        }
1.53      www      4616:    }
1.30      www      4617: 
1.246     www      4618: # Restricted by state or randomout?
1.30      www      4619: 
1.52      www      4620:    if ($thisallowed=~/X/) {
1.620     albertel 4621:       if ($env{'acc.randomout'}) {
1.579     albertel 4622: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 4623:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      4624:             return ''; 
                   4625:          }
1.247     www      4626:       }
                   4627:       if (&condval($statecond)) {
1.52      www      4628: 	 return '2';
                   4629:       } else {
                   4630:          return '';
                   4631:       }
                   4632:    }
1.30      www      4633: 
1.766     albertel 4634:     if ($thisallowed eq 'A') {
                   4635: 	return 'A';
1.814     raeburn  4636:     } elsif ($thisallowed eq 'B') {
                   4637:         return 'B';
1.766     albertel 4638:     }
1.52      www      4639:    return 'F';
1.232     www      4640: }
                   4641: 
1.710     albertel 4642: sub split_uri_for_cond {
                   4643:     my $uri=&deversion(&declutter(shift));
                   4644:     my @uriparts=split(/\//,$uri);
                   4645:     my $filename=pop(@uriparts);
                   4646:     my $pathname=join('/',@uriparts);
                   4647:     return ($pathname,$filename);
                   4648: }
1.232     www      4649: # --------------------------------------------------- Is a resource on the map?
                   4650: 
                   4651: sub is_on_map {
1.710     albertel 4652:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 4653:     #Trying to find the conditional for the file
1.620     albertel 4654:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 4655: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      4656:     if ($match) {
1.289     bowersj2 4657: 	return (1,$1);
                   4658:     } else {
1.434     www      4659: 	return (0,0);
1.289     bowersj2 4660:     }
1.12      www      4661: }
                   4662: 
1.427     www      4663: # --------------------------------------------------------- Get symb from alias
                   4664: 
                   4665: sub get_symb_from_alias {
                   4666:     my $symb=shift;
                   4667:     my ($map,$resid,$url)=&decode_symb($symb);
                   4668: # Already is a symb
                   4669:     if ($url) { return $symb; }
                   4670: # Must be an alias
                   4671:     my $aliassymb='';
                   4672:     my %bighash;
1.620     albertel 4673:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      4674:                             &GDBM_READER(),0640)) {
                   4675:         my $rid=$bighash{'mapalias_'.$symb};
                   4676: 	if ($rid) {
                   4677: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 4678: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   4679: 				    $resid,$bighash{'src_'.$rid});
1.427     www      4680: 	}
                   4681:         untie %bighash;
                   4682:     }
                   4683:     return $aliassymb;
                   4684: }
                   4685: 
1.12      www      4686: # ----------------------------------------------------------------- Define Role
                   4687: 
                   4688: sub definerole {
                   4689:   if (allowed('mcr','/')) {
                   4690:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 4691:     foreach my $role (split(':',$sysrole)) {
                   4692: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4693:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   4694:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   4695: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4696:                return "refused:s:$crole&$cqual"; 
                   4697:             }
                   4698:         }
1.191     harris41 4699:     }
1.800     albertel 4700:     foreach my $role (split(':',$domrole)) {
                   4701: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4702:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   4703:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   4704: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      4705:                return "refused:d:$crole&$cqual"; 
                   4706:             }
                   4707:         }
1.191     harris41 4708:     }
1.800     albertel 4709:     foreach my $role (split(':',$courole)) {
                   4710: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4711:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   4712:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   4713: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4714:                return "refused:c:$crole&$cqual"; 
                   4715:             }
                   4716:         }
1.191     harris41 4717:     }
1.620     albertel 4718:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   4719:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4720: 	        "rolesdef_$rolename=".
                   4721:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 4722:     return reply($command,$env{'user.home'});
1.12      www      4723:   } else {
                   4724:     return 'refused';
                   4725:   }
1.105     harris41 4726: }
                   4727: 
                   4728: # ---------------- Make a metadata query against the network of library servers
                   4729: 
                   4730: sub metadata_query {
1.244     matthew  4731:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 4732:     my %rhash;
1.845     albertel 4733:     my %libserv = &all_library();
1.244     matthew  4734:     my @server_list = (defined($server_array) ? @$server_array
                   4735:                                               : keys(%libserv) );
                   4736:     for my $server (@server_list) {
1.118     harris41 4737: 	unless ($custom or $customshow) {
                   4738: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   4739: 	    $rhash{$server}=$reply;
                   4740: 	}
                   4741: 	else {
                   4742: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   4743: 			     &escape($custom).':'.&escape($customshow),
                   4744: 			     $server);
                   4745: 	    $rhash{$server}=$reply;
                   4746: 	}
1.112     harris41 4747:     }
1.118     harris41 4748:     return \%rhash;
1.240     www      4749: }
                   4750: 
                   4751: # ----------------------------------------- Send log queries and wait for reply
                   4752: 
                   4753: sub log_query {
                   4754:     my ($uname,$udom,$query,%filters)=@_;
                   4755:     my $uhome=&homeserver($uname,$udom);
                   4756:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 4757:     my $uhost=&hostname($uhome);
1.800     albertel 4758:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      4759:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   4760:                        $uhome);
1.479     albertel 4761:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      4762:     return get_query_reply($queryid);
                   4763: }
                   4764: 
1.818     raeburn  4765: # -------------------------- Update MySQL table for portfolio file
                   4766: 
                   4767: sub update_portfolio_table {
1.821     raeburn  4768:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.818     raeburn  4769:     my $homeserver = &homeserver($uname,$udom);
                   4770:     my $queryid=
1.821     raeburn  4771:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   4772:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  4773:     my $reply = &get_query_reply($queryid);
                   4774:     return $reply;
                   4775: }
                   4776: 
1.899     raeburn  4777: # -------------------------- Update MySQL allusers table
                   4778: 
                   4779: sub update_allusers_table {
                   4780:     my ($uname,$udom,$names) = @_;
                   4781:     my $homeserver = &homeserver($uname,$udom);
                   4782:     my $queryid=
                   4783:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   4784:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   4785:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   4786:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   4787:                'generation='.&escape($names->{'generation'}).'%%'.
                   4788:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   4789:                'id='.&escape($names->{'id'}),$homeserver);
                   4790:     my $reply = &get_query_reply($queryid);
                   4791:     return $reply;
                   4792: }
                   4793: 
1.508     raeburn  4794: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  4795: 
                   4796: sub fetch_enrollment_query {
1.511     raeburn  4797:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  4798:     my $homeserver;
1.547     raeburn  4799:     my $maxtries = 1;
1.508     raeburn  4800:     if ($context eq 'automated') {
                   4801:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  4802:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  4803:     } else {
                   4804:         $homeserver = &homeserver($cnum,$dom);
                   4805:     }
1.838     albertel 4806:     my $host=&hostname($homeserver);
1.506     raeburn  4807:     my $cmd = '';
1.800     albertel 4808:     foreach my $affiliate (keys %{$affiliatesref}) {
                   4809:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  4810:     }
                   4811:     $cmd =~ s/%%$//;
                   4812:     $cmd = &escape($cmd);
                   4813:     my $query = 'fetchenrollment';
1.620     albertel 4814:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  4815:     unless ($queryid=~/^\Q$host\E\_/) { 
                   4816:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   4817:         return 'error: '.$queryid;
                   4818:     }
1.506     raeburn  4819:     my $reply = &get_query_reply($queryid);
1.547     raeburn  4820:     my $tries = 1;
                   4821:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4822:         $reply = &get_query_reply($queryid);
                   4823:         $tries ++;
                   4824:     }
1.526     raeburn  4825:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 4826:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  4827:     } else {
1.901     albertel 4828:         my @responses = split(/:/,$reply);
1.515     raeburn  4829:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 4830:             foreach my $line (@responses) {
                   4831:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  4832:                 $$replyref{$key} = $value;
                   4833:             }
                   4834:         } else {
1.506     raeburn  4835:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 4836:             foreach my $line (@responses) {
                   4837:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  4838:                 $$replyref{$key} = $value;
                   4839:                 if ($value > 0) {
1.800     albertel 4840:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   4841:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  4842:                         my $destname = $pathname.'/'.$filename;
                   4843:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  4844:                         if ($xml_classlist =~ /^error/) {
                   4845:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   4846:                         } else {
1.506     raeburn  4847:                             if ( open(FILE,">$destname") ) {
                   4848:                                 print FILE &unescape($xml_classlist);
                   4849:                                 close(FILE);
1.526     raeburn  4850:                             } else {
                   4851:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  4852:                             }
                   4853:                         }
                   4854:                     }
                   4855:                 }
                   4856:             }
                   4857:         }
                   4858:         return 'ok';
                   4859:     }
                   4860:     return 'error';
                   4861: }
                   4862: 
1.242     www      4863: sub get_query_reply {
                   4864:     my $queryid=shift;
1.240     www      4865:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   4866:     my $reply='';
                   4867:     for (1..100) {
                   4868: 	sleep 2;
                   4869:         if (-e $replyfile.'.end') {
1.448     albertel 4870: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 4871: 		$reply = join('',<$fh>);
                   4872: 		close($fh);
1.240     www      4873: 	   } else { return 'error: reply_file_error'; }
1.242     www      4874:            return &unescape($reply);
                   4875: 	}
1.240     www      4876:     }
1.242     www      4877:     return 'timeout:'.$queryid;
1.240     www      4878: }
                   4879: 
                   4880: sub courselog_query {
1.241     www      4881: #
                   4882: # possible filters:
                   4883: # url: url or symb
                   4884: # username
                   4885: # domain
                   4886: # action: view, submit, grade
                   4887: # start: timestamp
                   4888: # end: timestamp
                   4889: #
1.240     www      4890:     my (%filters)=@_;
1.620     albertel 4891:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      4892:     if ($filters{'url'}) {
                   4893: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   4894:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   4895:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   4896:     }
1.620     albertel 4897:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4898:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      4899:     return &log_query($cname,$cdom,'courselog',%filters);
                   4900: }
                   4901: 
                   4902: sub userlog_query {
1.858     raeburn  4903: #
                   4904: # possible filters:
                   4905: # action: log check role
                   4906: # start: timestamp
                   4907: # end: timestamp
                   4908: #
1.240     www      4909:     my ($uname,$udom,%filters)=@_;
                   4910:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      4911: }
                   4912: 
1.506     raeburn  4913: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   4914: 
                   4915: sub auto_run {
1.508     raeburn  4916:     my ($cnum,$cdom) = @_;
1.876     raeburn  4917:     my $response = 0;
                   4918:     my $settings;
                   4919:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   4920:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   4921:         $settings = $domconfig{'autoenroll'};
                   4922:         if ($settings->{'run'} eq '1') {
                   4923:             $response = 1;
                   4924:         }
                   4925:     } else {
1.934     raeburn  4926:         my $homeserver;
                   4927:         if (&is_course($cdom,$cnum)) {
                   4928:             $homeserver = &homeserver($cnum,$cdom);
                   4929:         } else {
                   4930:             $homeserver = &domain($cdom,'primary');
                   4931:         }
                   4932:         if ($homeserver ne 'no_host') {
                   4933:             $response = &reply('autorun:'.$cdom,$homeserver);
                   4934:         }
1.876     raeburn  4935:     }
1.506     raeburn  4936:     return $response;
                   4937: }
1.776     albertel 4938: 
1.506     raeburn  4939: sub auto_get_sections {
1.508     raeburn  4940:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   4941:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  4942:     my @secs = ();
1.511     raeburn  4943:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  4944:     unless ($response eq 'refused') {
1.901     albertel 4945:         @secs = split(/:/,$response);
1.506     raeburn  4946:     }
                   4947:     return @secs;
                   4948: }
1.776     albertel 4949: 
1.506     raeburn  4950: sub auto_new_course {
1.508     raeburn  4951:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   4952:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  4953:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  4954:     return $response;
                   4955: }
1.776     albertel 4956: 
1.506     raeburn  4957: sub auto_validate_courseID {
1.508     raeburn  4958:     my ($cnum,$cdom,$inst_course_id) = @_;
                   4959:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4960:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  4961:     return $response;
                   4962: }
1.776     albertel 4963: 
1.506     raeburn  4964: sub auto_create_password {
1.873     raeburn  4965:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   4966:     my ($homeserver,$response);
1.506     raeburn  4967:     my $create_passwd = 0;
                   4968:     my $authchk = '';
1.873     raeburn  4969:     if ($udom =~ /^$match_domain$/) {
                   4970:         $homeserver = &domain($udom,'primary');
                   4971:     }
                   4972:     if ($homeserver eq '') {
                   4973:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   4974:             $homeserver = &homeserver($cnum,$cdom);
                   4975:         }
                   4976:     }
                   4977:     if ($homeserver eq '') {
                   4978:         $authchk = 'nodomain';
1.506     raeburn  4979:     } else {
1.873     raeburn  4980:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   4981:         if ($response eq 'refused') {
                   4982:             $authchk = 'refused';
                   4983:         } else {
1.901     albertel 4984:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  4985:         }
1.506     raeburn  4986:     }
                   4987:     return ($authparam,$create_passwd,$authchk);
                   4988: }
                   4989: 
1.706     raeburn  4990: sub auto_photo_permission {
                   4991:     my ($cnum,$cdom,$students) = @_;
                   4992:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 4993:     my ($outcome,$perm_reqd,$conditions) = 
                   4994: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 4995:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4996: 	return (undef,undef);
                   4997:     }
1.706     raeburn  4998:     return ($outcome,$perm_reqd,$conditions);
                   4999: }
                   5000: 
                   5001: sub auto_checkphotos {
                   5002:     my ($uname,$udom,$pid) = @_;
                   5003:     my $homeserver = &homeserver($uname,$udom);
                   5004:     my ($result,$resulttype);
                   5005:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 5006: 				   &escape($uname).':'.&escape($pid),
                   5007: 				   $homeserver));
1.709     albertel 5008:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5009: 	return (undef,undef);
                   5010:     }
1.706     raeburn  5011:     if ($outcome) {
                   5012:         ($result,$resulttype) = split(/:/,$outcome);
                   5013:     } 
                   5014:     return ($result,$resulttype);
                   5015: }
                   5016: 
                   5017: sub auto_photochoice {
                   5018:     my ($cnum,$cdom) = @_;
                   5019:     my $homeserver = &homeserver($cnum,$cdom);
                   5020:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 5021: 						       &escape($cdom),
                   5022: 						       $homeserver)));
1.709     albertel 5023:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   5024: 	return (undef,undef);
                   5025:     }
1.706     raeburn  5026:     return ($update,$comment);
                   5027: }
                   5028: 
                   5029: sub auto_photoupdate {
                   5030:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   5031:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 5032:     my $host=&hostname($homeserver);
1.706     raeburn  5033:     my $cmd = '';
                   5034:     my $maxtries = 1;
1.800     albertel 5035:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   5036:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  5037:     }
                   5038:     $cmd =~ s/%%$//;
                   5039:     $cmd = &escape($cmd);
                   5040:     my $query = 'institutionalphotos';
                   5041:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   5042:     unless ($queryid=~/^\Q$host\E\_/) {
                   5043:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   5044:         return 'error: '.$queryid;
                   5045:     }
                   5046:     my $reply = &get_query_reply($queryid);
                   5047:     my $tries = 1;
                   5048:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   5049:         $reply = &get_query_reply($queryid);
                   5050:         $tries ++;
                   5051:     }
                   5052:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   5053:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   5054:     } else {
                   5055:         my @responses = split(/:/,$reply);
                   5056:         my $outcome = shift(@responses); 
                   5057:         foreach my $item (@responses) {
                   5058:             my ($key,$value) = split(/=/,$item);
                   5059:             $$photo{$key} = $value;
                   5060:         }
                   5061:         return $outcome;
                   5062:     }
                   5063:     return 'error';
                   5064: }
                   5065: 
1.521     raeburn  5066: sub auto_instcode_format {
1.793     albertel 5067:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   5068: 	$cat_order) = @_;
1.521     raeburn  5069:     my $courses = '';
1.772     raeburn  5070:     my @homeservers;
1.521     raeburn  5071:     if ($caller eq 'global') {
1.841     albertel 5072: 	my %servers = &get_servers($codedom,'library');
                   5073: 	foreach my $tryserver (keys(%servers)) {
                   5074: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   5075: 		push(@homeservers,$tryserver);
                   5076: 	    }
1.584     raeburn  5077:         }
1.521     raeburn  5078:     } else {
1.772     raeburn  5079:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  5080:     }
1.793     albertel 5081:     foreach my $code (keys(%{$instcodes})) {
                   5082:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  5083:     }
                   5084:     chop($courses);
1.772     raeburn  5085:     my $ok_response = 0;
                   5086:     my $response;
                   5087:     while (@homeservers > 0 && $ok_response == 0) {
                   5088:         my $server = shift(@homeservers); 
                   5089:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   5090:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   5091:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 5092: 		split(/:/,$response);
1.772     raeburn  5093:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   5094:             push(@{$codetitles},&str2array($codetitles_str));
                   5095:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   5096:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   5097:             $ok_response = 1;
                   5098:         }
                   5099:     }
                   5100:     if ($ok_response) {
1.521     raeburn  5101:         return 'ok';
1.772     raeburn  5102:     } else {
                   5103:         return $response;
1.521     raeburn  5104:     }
                   5105: }
                   5106: 
1.792     raeburn  5107: sub auto_instcode_defaults {
                   5108:     my ($domain,$returnhash,$code_order) = @_;
                   5109:     my @homeservers;
1.841     albertel 5110: 
                   5111:     my %servers = &get_servers($domain,'library');
                   5112:     foreach my $tryserver (keys(%servers)) {
                   5113: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   5114: 	    push(@homeservers,$tryserver);
                   5115: 	}
1.792     raeburn  5116:     }
1.841     albertel 5117: 
1.792     raeburn  5118:     my $response;
1.841     albertel 5119:     foreach my $server (@homeservers) {
1.792     raeburn  5120:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 5121:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   5122: 	
                   5123: 	foreach my $pair (split(/\&/,$response)) {
                   5124: 	    my ($name,$value)=split(/\=/,$pair);
                   5125: 	    if ($name eq 'code_order') {
                   5126: 		@{$code_order} = split(/\&/,&unescape($value));
                   5127: 	    } else {
                   5128: 		$returnhash->{&unescape($name)}=&unescape($value);
                   5129: 	    }
                   5130: 	}
                   5131: 	return 'ok';
1.792     raeburn  5132:     }
1.841     albertel 5133: 
                   5134:     return $response;
1.792     raeburn  5135: } 
                   5136: 
1.777     albertel 5137: sub auto_validate_class_sec {
1.918     raeburn  5138:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  5139:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  5140:     my $ownerlist;
                   5141:     if (ref($owners) eq 'ARRAY') {
                   5142:         $ownerlist = join(',',@{$owners});
                   5143:     } else {
                   5144:         $ownerlist = $owners;
                   5145:     }
1.773     raeburn  5146:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  5147:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  5148:     return $response;
                   5149: }
                   5150: 
1.679     raeburn  5151: # ------------------------------------------------------- Course Group routines
                   5152: 
                   5153: sub get_coursegroups {
1.809     raeburn  5154:     my ($cdom,$cnum,$group,$namespace) = @_;
                   5155:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  5156: }
                   5157: 
1.679     raeburn  5158: sub modify_coursegroup {
                   5159:     my ($cdom,$cnum,$groupsettings) = @_;
                   5160:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   5161: }
                   5162: 
1.809     raeburn  5163: sub toggle_coursegroup_status {
                   5164:     my ($cdom,$cnum,$group,$action) = @_;
                   5165:     my ($from_namespace,$to_namespace);
                   5166:     if ($action eq 'delete') {
                   5167:         $from_namespace = 'coursegroups';
                   5168:         $to_namespace = 'deleted_groups';
                   5169:     } else {
                   5170:         $from_namespace = 'deleted_groups';
                   5171:         $to_namespace = 'coursegroups';
                   5172:     }
                   5173:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  5174:     if (my $tmp = &error(%curr_group)) {
                   5175:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   5176:         return ('read error',$tmp);
                   5177:     } else {
                   5178:         my %savedsettings = %curr_group; 
1.809     raeburn  5179:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  5180:         my $deloutcome;
                   5181:         if ($result eq 'ok') {
1.809     raeburn  5182:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  5183:         } else {
                   5184:             return ('write error',$result);
                   5185:         }
                   5186:         if ($deloutcome eq 'ok') {
                   5187:             return 'ok';
                   5188:         } else {
                   5189:             return ('delete error',$deloutcome);
                   5190:         }
                   5191:     }
                   5192: }
                   5193: 
1.679     raeburn  5194: sub modify_group_roles {
                   5195:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
                   5196:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   5197:     my $role = 'gr/'.&escape($userprivs);
                   5198:     my ($uname,$udom) = split(/:/,$user);
                   5199:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
1.684     raeburn  5200:     if ($result eq 'ok') {
                   5201:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   5202:     }
1.679     raeburn  5203:     return $result;
                   5204: }
                   5205: 
                   5206: sub modify_coursegroup_membership {
                   5207:     my ($cdom,$cnum,$membership) = @_;
                   5208:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   5209:     return $result;
                   5210: }
                   5211: 
1.682     raeburn  5212: sub get_active_groups {
                   5213:     my ($udom,$uname,$cdom,$cnum) = @_;
                   5214:     my $now = time;
                   5215:     my %groups = ();
                   5216:     foreach my $key (keys(%env)) {
1.811     albertel 5217:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  5218:             my ($start,$end) = split(/\./,$env{$key});
                   5219:             if (($end!=0) && ($end<$now)) { next; }
                   5220:             if (($start!=0) && ($start>$now)) { next; }
                   5221:             if ($1 eq $cdom && $2 eq $cnum) {
                   5222:                 $groups{$3} = $env{$key} ;
                   5223:             }
                   5224:         }
                   5225:     }
                   5226:     return %groups;
                   5227: }
                   5228: 
1.683     raeburn  5229: sub get_group_membership {
                   5230:     my ($cdom,$cnum,$group) = @_;
                   5231:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   5232: }
                   5233: 
                   5234: sub get_users_groups {
                   5235:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  5236:     my @usersgroups;
1.683     raeburn  5237:     my $cachetime=1800;
                   5238: 
                   5239:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  5240:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   5241:     if (defined($cached)) {
1.734     albertel 5242:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  5243:     } else {  
                   5244:         $grouplist = '';
1.816     raeburn  5245:         my $courseurl = &courseid_to_courseurl($courseid);
                   5246:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  5247:         my $access_end = $env{'course.'.$courseid.
                   5248:                               '.default_enrollment_end_date'};
                   5249:         my $now = time;
                   5250:         foreach my $key (keys(%roleshash)) {
                   5251:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   5252:                 my $group = $1;
                   5253:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   5254:                     my $start = $2;
                   5255:                     my $end = $1;
                   5256:                     if ($start == -1) { next; } # deleted from group
                   5257:                     if (($start!=0) && ($start>$now)) { next; }
                   5258:                     if (($end!=0) && ($end<$now)) {
                   5259:                         if ($access_end && $access_end < $now) {
                   5260:                             if ($access_end - $end < 86400) {
                   5261:                                 push(@usersgroups,$group);
1.733     raeburn  5262:                             }
                   5263:                         }
1.817     raeburn  5264:                         next;
1.733     raeburn  5265:                     }
1.817     raeburn  5266:                     push(@usersgroups,$group);
1.683     raeburn  5267:                 }
                   5268:             }
                   5269:         }
1.817     raeburn  5270:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   5271:         $grouplist = join(':',@usersgroups);
                   5272:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  5273:     }
1.733     raeburn  5274:     return @usersgroups;
1.683     raeburn  5275: }
                   5276: 
                   5277: sub devalidate_getgroups_cache {
                   5278:     my ($udom,$uname,$cdom,$cnum)=@_;
                   5279:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 5280: 
1.683     raeburn  5281:     my $hashid="$udom:$uname:$courseid";
                   5282:     &devalidate_cache_new('getgroups',$hashid);
                   5283: }
                   5284: 
1.12      www      5285: # ------------------------------------------------------------------ Plain Text
                   5286: 
                   5287: sub plaintext {
1.742     raeburn  5288:     my ($short,$type,$cid) = @_;
1.758     albertel 5289:     if ($short =~ /^cr/) {
                   5290: 	return (split('/',$short))[-1];
                   5291:     }
1.742     raeburn  5292:     if (!defined($cid)) {
                   5293:         $cid = $env{'request.course.id'};
                   5294:     }
                   5295:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
                   5296:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
                   5297:                                           '.plaintext'});
                   5298:     }
                   5299:     my %rolenames = (
                   5300:                       Course => 'std',
                   5301:                       Group => 'alt1',
                   5302:                     );
                   5303:     if (defined($type) && 
                   5304:          defined($rolenames{$type}) && 
                   5305:          defined($prp{$short}{$rolenames{$type}})) {
                   5306:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   5307:     } else {
                   5308:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   5309:     }
1.12      www      5310: }
                   5311: 
                   5312: # ----------------------------------------------------------------- Assign Role
                   5313: 
                   5314: sub assignrole {
1.357     www      5315:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
1.21      www      5316:     my $mrole;
                   5317:     if ($role =~ /^cr\//) {
1.393     www      5318:         my $cwosec=$url;
1.811     albertel 5319:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      5320: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      5321:            &logthis('Refused custom assignrole: '.
                   5322:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 5323: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      5324:            return 'refused'; 
                   5325:         }
1.21      www      5326:         $mrole='cr';
1.678     raeburn  5327:     } elsif ($role =~ /^gr\//) {
                   5328:         my $cwogrp=$url;
1.811     albertel 5329:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  5330:         unless (&allowed('mdg',$cwogrp)) {
                   5331:             &logthis('Refused group assignrole: '.
                   5332:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   5333:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   5334:             return 'refused';
                   5335:         }
                   5336:         $mrole='gr';
1.21      www      5337:     } else {
1.82      www      5338:         my $cwosec=$url;
1.811     albertel 5339:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  5340:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   5341:             my $refused;
                   5342:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   5343:                 if (!(&allowed('c'.$role,$url))) {
                   5344:                     $refused = 1;
                   5345:                 }
                   5346:             } else {
                   5347:                 $refused = 1;
                   5348:             }
                   5349:             if ($refused) { 
                   5350:                 &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   5351:                          ' '.$role.' '.$end.' '.$start.' by '.
                   5352: 	  	         $env{'user.name'}.' at '.$env{'user.domain'});
                   5353:                 return 'refused';
                   5354:             }
1.104     www      5355:         }
1.21      www      5356:         $mrole=$role;
                   5357:     }
1.620     albertel 5358:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      5359:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      5360:     if ($end) { $command.='_'.$end; }
1.21      www      5361:     if ($start) {
                   5362: 	if ($end) { 
1.81      www      5363:            $command.='_'.$start; 
1.21      www      5364:         } else {
1.81      www      5365:            $command.='_0_'.$start;
1.21      www      5366:         }
                   5367:     }
1.739     raeburn  5368:     my $origstart = $start;
                   5369:     my $origend = $end;
1.357     www      5370: # actually delete
                   5371:     if ($deleteflag) {
1.373     www      5372: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      5373: # modify command to delete the role
1.620     albertel 5374:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      5375:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 5376: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      5377: # set start and finish to negative values for userrolelog
                   5378:            $start=-1;
                   5379:            $end=-1;
                   5380:         }
                   5381:     }
                   5382: # send command
1.349     www      5383:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      5384: # log new user role if status is ok
1.349     www      5385:     if ($answer eq 'ok') {
1.663     raeburn  5386: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  5387: # for course roles, perform group memberships changes triggered by role change.
                   5388:         unless ($role =~ /^gr/) {
                   5389:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   5390:                                              $origstart);
                   5391:         }
1.349     www      5392:     }
                   5393:     return $answer;
1.169     harris41 5394: }
                   5395: 
                   5396: # -------------------------------------------------- Modify user authentication
1.197     www      5397: # Overrides without validation
                   5398: 
1.169     harris41 5399: sub modifyuserauth {
                   5400:     my ($udom,$uname,$umode,$upass)=@_;
                   5401:     my $uhome=&homeserver($uname,$udom);
1.197     www      5402:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   5403:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 5404:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   5405:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 5406:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   5407: 		     &escape($upass),$uhome);
1.620     albertel 5408:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      5409:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   5410:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   5411:     &log($udom,,$uname,$uhome,
1.620     albertel 5412:         'Authentication changed by '.$env{'user.domain'}.', '.
                   5413:                                      $env{'user.name'}.', '.$umode.
1.197     www      5414:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 5415:     unless ($reply eq 'ok') {
1.197     www      5416:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 5417: 	return 'error: '.$reply;
                   5418:     }   
1.170     harris41 5419:     return 'ok';
1.80      www      5420: }
                   5421: 
1.81      www      5422: # --------------------------------------------------------------- Modify a user
1.80      www      5423: 
1.81      www      5424: sub modifyuser {
1.206     matthew  5425:     my ($udom,    $uname, $uid,
                   5426:         $umode,   $upass, $first,
                   5427:         $middle,  $last,  $gene,
1.387     www      5428:         $forceid, $desiredhome, $email)=@_;
1.807     albertel 5429:     $udom= &LONCAPA::clean_domain($udom);
                   5430:     $uname=&LONCAPA::clean_username($uname);
1.81      www      5431:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      5432:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  5433: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   5434:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   5435:                                      ' desiredhome not specified'). 
1.620     albertel 5436:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   5437:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 5438:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      5439: # ----------------------------------------------------------------- Create User
1.406     albertel 5440:     if (($uhome eq 'no_host') && 
                   5441: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      5442:         my $unhome='';
1.844     albertel 5443:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  5444:             $unhome = $desiredhome;
1.620     albertel 5445: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   5446: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  5447:         } else { # load balancing routine for determining $unhome
1.81      www      5448:             my $loadm=10000000;
1.841     albertel 5449: 	    my %servers = &get_servers($udom,'library');
                   5450: 	    foreach my $tryserver (keys(%servers)) {
                   5451: 		my $answer=reply('load',$tryserver);
                   5452: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   5453: 		    $loadm=$answer;
                   5454: 		    $unhome=$tryserver;
                   5455: 		}
1.80      www      5456: 	    }
                   5457:         }
                   5458:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  5459: 	    return 'error: unable to find a home server for '.$uname.
                   5460:                    ' in domain '.$udom;
1.80      www      5461:         }
                   5462:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   5463:                          &escape($upass),$unhome);
                   5464: 	unless ($reply eq 'ok') {
                   5465:             return 'error: '.$reply;
                   5466:         }   
1.230     stredwic 5467:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      5468:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  5469: 	    return 'error: unable verify users home machine.';
1.80      www      5470:         }
1.209     matthew  5471:     }   # End of creation of new user
1.80      www      5472: # ---------------------------------------------------------------------- Add ID
                   5473:     if ($uid) {
                   5474:        $uid=~tr/A-Z/a-z/;
                   5475:        my %uidhash=&idrget($udom,$uname);
1.196     www      5476:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   5477:          && (!$forceid)) {
1.80      www      5478: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  5479: 	      return 'error: user id "'.$uid.'" does not match '.
                   5480:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      5481:           }
                   5482:        } else {
                   5483: 	  &idput($udom,($uname => $uid));
                   5484:        }
                   5485:     }
                   5486: # -------------------------------------------------------------- Add names, etc
1.313     matthew  5487:     my @tmp=&get('environment',
1.899     raeburn  5488: 		   ['firstname','middlename','lastname','generation','id',
                   5489:                     'permanentemail'],
1.134     albertel 5490: 		   $udom,$uname);
1.313     matthew  5491:     my %names;
                   5492:     if ($tmp[0] =~ m/^error:.*/) { 
                   5493:         %names=(); 
                   5494:     } else {
                   5495:         %names = @tmp;
                   5496:     }
1.388     www      5497: #
                   5498: # Make sure to not trash student environment if instructor does not bother
                   5499: # to supply name and email information
                   5500: #
                   5501:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  5502:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      5503:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  5504:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      5505:     if ($email) {
                   5506:        $email=~s/[^\w\@\.\-\,]//gs;
                   5507:        if ($email=~/\@/) { $names{'notification'} = $email;
                   5508: 			   $names{'critnotification'} = $email;
                   5509: 			   $names{'permanentemail'} = $email; }
                   5510:     }
1.899     raeburn  5511:     if ($uid) { $names{'id'}  = $uid; }
1.134     albertel 5512:     my $reply = &put('environment', \%names, $udom,$uname);
                   5513:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.899     raeburn  5514:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
1.680     www      5515:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.81      www      5516:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      5517:              $umode.', '.$first.', '.$middle.', '.
                   5518: 	     $last.', '.$gene.' by '.
1.620     albertel 5519:              $env{'user.name'}.' at '.$env{'user.domain'});
1.134     albertel 5520:     return 'ok';
1.80      www      5521: }
                   5522: 
1.81      www      5523: # -------------------------------------------------------------- Modify student
1.80      www      5524: 
1.81      www      5525: sub modifystudent {
                   5526:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.515     raeburn  5527:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
1.455     albertel 5528:     if (!$cid) {
1.620     albertel 5529: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5530: 	    return 'not_in_class';
                   5531: 	}
1.80      www      5532:     }
                   5533: # --------------------------------------------------------------- Make the user
1.81      www      5534:     my $reply=&modifyuser
1.209     matthew  5535: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      5536:          $desiredhome,$email);
1.80      www      5537:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  5538:     # This will cause &modify_student_enrollment to get the uid from the
                   5539:     # students environment
                   5540:     $uid = undef if (!$forceid);
1.455     albertel 5541:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.515     raeburn  5542: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
1.297     matthew  5543:     return $reply;
                   5544: }
                   5545: 
                   5546: sub modify_student_enrollment {
1.515     raeburn  5547:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
1.455     albertel 5548:     my ($cdom,$cnum,$chome);
                   5549:     if (!$cid) {
1.620     albertel 5550: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 5551: 	    return 'not_in_class';
                   5552: 	}
1.620     albertel 5553: 	$cdom=$env{'course.'.$cid.'.domain'};
                   5554: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 5555:     } else {
                   5556: 	($cdom,$cnum)=split(/_/,$cid);
                   5557:     }
1.620     albertel 5558:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 5559:     if (!$chome) {
1.457     raeburn  5560: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  5561:     }
1.455     albertel 5562:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  5563:     # Make sure the user exists
1.81      www      5564:     my $uhome=&homeserver($uname,$udom);
                   5565:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5566: 	return 'error: no such user';
                   5567:     }
1.297     matthew  5568:     # Get student data if we were not given enough information
                   5569:     if (!defined($first)  || $first  eq '' || 
                   5570:         !defined($last)   || $last   eq '' || 
                   5571:         !defined($uid)    || $uid    eq '' || 
                   5572:         !defined($middle) || $middle eq '' || 
                   5573:         !defined($gene)   || $gene   eq '') {
1.294     matthew  5574:         # They did not supply us with enough data to enroll the student, so
                   5575:         # we need to pick up more information.
1.297     matthew  5576:         my %tmp = &get('environment',
1.294     matthew  5577:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  5578:                        ,$udom,$uname);
                   5579: 
1.800     albertel 5580:         #foreach my $key (keys(%tmp)) {
                   5581:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 5582:         #}
1.294     matthew  5583:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   5584:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   5585:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  5586:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  5587:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   5588:     }
1.556     albertel 5589:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 5590:     my $reply=cput('classlist',
                   5591: 		   {"$uname:$udom" => 
1.515     raeburn  5592: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 5593: 		   $cdom,$cnum);
1.81      www      5594:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   5595: 	return 'error: '.$reply;
1.652     albertel 5596:     } else {
                   5597: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      5598:     }
1.297     matthew  5599:     # Add student role to user
1.83      www      5600:     my $uurl='/'.$cid;
1.81      www      5601:     $uurl=~s/\_/\//g;
                   5602:     if ($usec) {
                   5603: 	$uurl.='/'.$usec;
                   5604:     }
                   5605:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21      www      5606: }
                   5607: 
1.556     albertel 5608: sub format_name {
                   5609:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   5610:     my $name;
                   5611:     if ($first ne 'lastname') {
                   5612: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   5613:     } else {
                   5614: 	if ($lastname=~/\S/) {
                   5615: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   5616: 	    $name=~s/\s+,/,/;
                   5617: 	} else {
                   5618: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   5619: 	}
                   5620:     }
                   5621:     $name=~s/^\s+//;
                   5622:     $name=~s/\s+$//;
                   5623:     $name=~s/\s+/ /g;
                   5624:     return $name;
                   5625: }
                   5626: 
1.84      www      5627: # ------------------------------------------------- Write to course preferences
                   5628: 
                   5629: sub writecoursepref {
                   5630:     my ($courseid,%prefs)=@_;
                   5631:     $courseid=~s/^\///;
                   5632:     $courseid=~s/\_/\//g;
                   5633:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   5634:     my $chome=homeserver($cnum,$cdomain);
                   5635:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   5636: 	return 'error: no such course';
                   5637:     }
                   5638:     my $cstring='';
1.800     albertel 5639:     foreach my $pref (keys(%prefs)) {
                   5640: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 5641:     }
1.84      www      5642:     $cstring=~s/\&$//;
                   5643:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   5644: }
                   5645: 
                   5646: # ---------------------------------------------------------- Make/modify course
                   5647: 
                   5648: sub createcourse {
1.741     raeburn  5649:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
                   5650:         $course_owner,$crstype)=@_;
1.84      www      5651:     $url=&declutter($url);
                   5652:     my $cid='';
1.264     matthew  5653:     unless (&allowed('ccc',$udom)) {
1.84      www      5654:         return 'refused';
                   5655:     }
                   5656: # ------------------------------------------------------------------- Create ID
1.674     www      5657:    my $uname=int(1+rand(9)).
                   5658:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   5659:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      5660:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   5661: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 5662:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      5663:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5664:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   5665:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 5666:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      5667:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5668:            return 'error: unable to generate unique course-ID';
                   5669:        } 
                   5670:    }
1.264     matthew  5671: # ------------------------------------------------ Check supplied server name
1.620     albertel 5672:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.845     albertel 5673:     if (! &is_library($course_server)) {
1.264     matthew  5674:         return 'error:bad server name '.$course_server;
                   5675:     }
1.84      www      5676: # ------------------------------------------------------------- Make the course
                   5677:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  5678:                       $course_server);
1.84      www      5679:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 5680:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      5681:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5682: 	return 'error: no such course';
                   5683:     }
1.271     www      5684: # ----------------------------------------------------------------- Course made
1.516     raeburn  5685: # log existence
1.918     raeburn  5686:     my $newcourse = {
                   5687:                     $udom.'_'.$uname => {
1.921     raeburn  5688:                                      description => $description,
                   5689:                                      inst_code   => $inst_code,
                   5690:                                      owner       => $course_owner,
                   5691:                                      type        => $crstype,
1.918     raeburn  5692:                                                 },
                   5693:                     };
1.921     raeburn  5694:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      5695: # set toplevel url
1.271     www      5696:     my $topurl=$url;
                   5697:     unless ($nonstandard) {
                   5698: # ------------------------------------------ For standard courses, make top url
                   5699:         my $mapurl=&clutter($url);
1.278     www      5700:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 5701:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      5702: <map>
                   5703: <resource id="1" type="start"></resource>
                   5704: <resource id="2" src="$mapurl"></resource>
                   5705: <resource id="3" type="finish"></resource>
                   5706: <link index="1" from="1" to="2"></link>
                   5707: <link index="2" from="2" to="3"></link>
                   5708: </map>
                   5709: ENDINITMAP
                   5710:         $topurl=&declutter(
1.638     albertel 5711:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      5712:                           );
                   5713:     }
                   5714: # ----------------------------------------------------------- Write preferences
1.84      www      5715:     &writecoursepref($udom.'_'.$uname,
                   5716:                      ('description' => $description,
1.271     www      5717:                       'url'         => $topurl));
1.84      www      5718:     return '/'.$udom.'/'.$uname;
                   5719: }
                   5720: 
1.813     albertel 5721: sub is_course {
                   5722:     my ($cdom,$cnum) = @_;
                   5723:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946   ! raeburn  5724: 				undef,'.');
1.813     albertel 5725:     if (exists($courses{$cdom.'_'.$cnum})) {
                   5726:         return 1;
                   5727:     }
                   5728:     return 0;
                   5729: }
                   5730: 
1.21      www      5731: # ---------------------------------------------------------- Assign Custom Role
                   5732: 
                   5733: sub assigncustomrole {
1.357     www      5734:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21      www      5735:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357     www      5736:                        $end,$start,$deleteflag);
1.21      www      5737: }
                   5738: 
                   5739: # ----------------------------------------------------------------- Revoke Role
                   5740: 
                   5741: sub revokerole {
1.357     www      5742:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21      www      5743:     my $now=time;
1.357     www      5744:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21      www      5745: }
                   5746: 
                   5747: # ---------------------------------------------------------- Revoke Custom Role
                   5748: 
                   5749: sub revokecustomrole {
1.357     www      5750:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21      www      5751:     my $now=time;
1.357     www      5752:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
                   5753:            $deleteflag);
1.17      www      5754: }
                   5755: 
1.533     banghart 5756: # ------------------------------------------------------------ Disk usage
1.535     albertel 5757: sub diskusage {
1.533     banghart 5758:     my ($udom,$uname,$directoryRoot)=@_;
                   5759:     $directoryRoot =~ s/\/$//;
1.535     albertel 5760:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
1.514     albertel 5761:     return $listing;
1.512     banghart 5762: }
                   5763: 
1.566     banghart 5764: sub is_locked {
                   5765:     my ($file_name, $domain, $user) = @_;
                   5766:     my @check;
                   5767:     my $is_locked;
                   5768:     push @check, $file_name;
1.613     albertel 5769:     my %locked = &get('file_permissions',\@check,
1.620     albertel 5770: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 5771:     my ($tmp)=keys(%locked);
                   5772:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  5773:     
1.566     banghart 5774:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  5775:         $is_locked = 'false';
                   5776:         foreach my $entry (@{$locked{$file_name}}) {
                   5777:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  5778:                $is_locked = 'true';
                   5779:                last;
1.745     raeburn  5780:            }
                   5781:        }
1.566     banghart 5782:     } else {
                   5783:         $is_locked = 'false';
                   5784:     }
                   5785: }
                   5786: 
1.759     albertel 5787: sub declutter_portfile {
                   5788:     my ($file) = @_;
1.833     albertel 5789:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 5790:     return $file;
                   5791: }
                   5792: 
1.559     banghart 5793: # ------------------------------------------------------------- Mark as Read Only
                   5794: 
                   5795: sub mark_as_readonly {
                   5796:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 5797:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5798:     my ($tmp)=keys(%current_permissions);
                   5799:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 5800:     foreach my $file (@{$files}) {
1.759     albertel 5801: 	$file = &declutter_portfile($file);
1.561     banghart 5802:         push(@{$current_permissions{$file}},$what);
1.559     banghart 5803:     }
1.613     albertel 5804:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5805:     return;
                   5806: }
                   5807: 
1.572     banghart 5808: # ------------------------------------------------------------Save Selected Files
                   5809: 
                   5810: sub save_selected_files {
                   5811:     my ($user, $path, @files) = @_;
                   5812:     my $filename = $user."savedfiles";
1.573     banghart 5813:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 5814:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 5815:     foreach my $file (@files) {
1.620     albertel 5816:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 5817:     }
                   5818:     foreach my $file (@other_files) {
1.574     banghart 5819:         print (OUT $file."\n");
1.572     banghart 5820:     }
1.574     banghart 5821:     close (OUT);
1.572     banghart 5822:     return 'ok';
                   5823: }
                   5824: 
1.574     banghart 5825: sub clear_selected_files {
                   5826:     my ($user) = @_;
                   5827:     my $filename = $user."savedfiles";
                   5828:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5829:     print (OUT undef);
                   5830:     close (OUT);
                   5831:     return ("ok");    
                   5832: }
                   5833: 
1.572     banghart 5834: sub files_in_path {
                   5835:     my ($user, $path) = @_;
                   5836:     my $filename = $user."savedfiles";
                   5837:     my %return_files;
1.574     banghart 5838:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 5839:     while (my $line_in = <IN>) {
1.574     banghart 5840:         chomp ($line_in);
                   5841:         my @paths_and_file = split (m!/!, $line_in);
                   5842:         my $file_part = pop (@paths_and_file);
                   5843:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 5844:         $path_part.='/';
                   5845:         my $path_and_file = $path_part.$file_part;
                   5846:         if ($path_part eq $path) {
                   5847:             $return_files{$file_part}= 'selected';
                   5848:         }
                   5849:     }
1.574     banghart 5850:     close (IN);
                   5851:     return (\%return_files);
1.572     banghart 5852: }
                   5853: 
                   5854: # called in portfolio select mode, to show files selected NOT in current directory
                   5855: sub files_not_in_path {
                   5856:     my ($user, $path) = @_;
                   5857:     my $filename = $user."savedfiles";
                   5858:     my @return_files;
                   5859:     my $path_part;
1.800     albertel 5860:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5861:     while (my $line = <IN>) {
1.572     banghart 5862:         #ok, I know it's clunky, but I want it to work
1.800     albertel 5863:         my @paths_and_file = split(m|/|, $line);
                   5864:         my $file_part = pop(@paths_and_file);
                   5865:         chomp($file_part);
                   5866:         my $path_part = join('/', @paths_and_file);
1.572     banghart 5867:         $path_part .= '/';
                   5868:         my $path_and_file = $path_part.$file_part;
                   5869:         if ($path_part ne $path) {
1.800     albertel 5870:             push(@return_files, ($path_and_file));
1.572     banghart 5871:         }
                   5872:     }
1.800     albertel 5873:     close(OUT);
1.574     banghart 5874:     return (@return_files);
1.572     banghart 5875: }
                   5876: 
1.745     raeburn  5877: #----------------------------------------------Get portfolio file permissions
1.629     banghart 5878: 
1.745     raeburn  5879: sub get_portfile_permissions {
                   5880:     my ($domain,$user) = @_;
1.613     albertel 5881:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5882:     my ($tmp)=keys(%current_permissions);
                   5883:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5884:     return \%current_permissions;
                   5885: }
                   5886: 
                   5887: #---------------------------------------------Get portfolio file access controls
                   5888: 
1.749     raeburn  5889: sub get_access_controls {
1.745     raeburn  5890:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 5891:     my %access;
                   5892:     my $real_file = $file;
                   5893:     $file =~ s/\.meta$//;
1.745     raeburn  5894:     if (defined($file)) {
1.749     raeburn  5895:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   5896:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 5897:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  5898:             }
                   5899:         }
1.745     raeburn  5900:     } else {
1.749     raeburn  5901:         foreach my $key (keys(%{$current_permissions})) {
                   5902:             if ($key =~ /\0accesscontrol$/) {
                   5903:                 if (defined($group)) {
                   5904:                     if ($key !~ m-^\Q$group\E/-) {
                   5905:                         next;
                   5906:                     }
                   5907:                 }
                   5908:                 my ($fullpath) = split(/\0/,$key);
                   5909:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   5910:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   5911:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   5912:                     }
                   5913:                 }
                   5914:             }
                   5915:         }
                   5916:     }
                   5917:     return %access;
                   5918: }
                   5919: 
                   5920: sub modify_access_controls {
                   5921:     my ($file_name,$changes,$domain,$user)=@_;
                   5922:     my ($outcome,$deloutcome);
                   5923:     my %store_permissions;
                   5924:     my %new_values;
                   5925:     my %new_control;
                   5926:     my %translation;
                   5927:     my @deletions = ();
                   5928:     my $now = time;
                   5929:     if (exists($$changes{'activate'})) {
                   5930:         if (ref($$changes{'activate'}) eq 'HASH') {
                   5931:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   5932:             my $numnew = scalar(@newitems);
                   5933:             for (my $i=0; $i<$numnew; $i++) {
                   5934:                 my $newkey = $newitems[$i];
                   5935:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  5936:                 if ($newkey =~ /^\d+:/) { 
                   5937:                     $newkey =~ s/^(\d+)/$newid/;
                   5938:                     $translation{$1} = $newid;
                   5939:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   5940:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   5941:                     $translation{$1} = $newid;
                   5942:                 }
1.749     raeburn  5943:                 $new_values{$file_name."\0".$newkey} = 
                   5944:                                           $$changes{'activate'}{$newitems[$i]};
                   5945:                 $new_control{$newkey} = $now;
                   5946:             }
                   5947:         }
                   5948:     }
                   5949:     my %todelete;
                   5950:     my %changed_items;
                   5951:     foreach my $action ('delete','update') {
                   5952:         if (exists($$changes{$action})) {
                   5953:             if (ref($$changes{$action}) eq 'HASH') {
                   5954:                 foreach my $key (keys(%{$$changes{$action}})) {
                   5955:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   5956:                     if ($action eq 'delete') { 
                   5957:                         $todelete{$itemnum} = 1;
                   5958:                     } else {
                   5959:                         $changed_items{$itemnum} = $key;
                   5960:                     }
                   5961:                 }
1.745     raeburn  5962:             }
                   5963:         }
1.749     raeburn  5964:     }
                   5965:     # get lock on access controls for file.
                   5966:     my $lockhash = {
                   5967:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   5968:                                                        ':'.$env{'user.domain'},
                   5969:                    }; 
                   5970:     my $tries = 0;
                   5971:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5972:    
                   5973:     while (($gotlock ne 'ok') && $tries <3) {
                   5974:         $tries ++;
                   5975:         sleep 1;
                   5976:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5977:     }
                   5978:     if ($gotlock eq 'ok') {
                   5979:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   5980:         my ($tmp)=keys(%curr_permissions);
                   5981:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   5982:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   5983:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   5984:             if (ref($curr_controls) eq 'HASH') {
                   5985:                 foreach my $control_item (keys(%{$curr_controls})) {
                   5986:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   5987:                     if (defined($todelete{$itemnum})) {
                   5988:                         push(@deletions,$file_name."\0".$control_item);
                   5989:                     } else {
                   5990:                         if (defined($changed_items{$itemnum})) {
                   5991:                             $new_control{$changed_items{$itemnum}} = $now;
                   5992:                             push(@deletions,$file_name."\0".$control_item);
                   5993:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   5994:                         } else {
                   5995:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   5996:                         }
                   5997:                     }
1.745     raeburn  5998:                 }
                   5999:             }
                   6000:         }
1.749     raeburn  6001:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   6002:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   6003:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   6004:         #  remove lock
                   6005:         my @del_lock = ($file_name."\0".'locked_access_records');
                   6006:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  6007:         my ($file,$group);
                   6008:         if (&is_course($domain,$user)) {
                   6009:             ($group,$file) = split(/\//,$file_name,2);
                   6010:         } else {
                   6011:             $file = $file_name;
                   6012:         }
                   6013:         my $sqlresult =
                   6014:             &update_portfolio_table($user,$domain,$file,'portfolio_access',
                   6015:                                     $group);
1.749     raeburn  6016:     } else {
                   6017:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  6018:     }
1.749     raeburn  6019:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  6020: }
                   6021: 
1.827     raeburn  6022: sub make_public_indefinitely {
                   6023:     my ($requrl) = @_;
                   6024:     my $now = time;
                   6025:     my $action = 'activate';
                   6026:     my $aclnum = 0;
                   6027:     if (&is_portfolio_url($requrl)) {
                   6028:         my (undef,$udom,$unum,$file_name,$group) =
                   6029:             &parse_portfolio_url($requrl);
                   6030:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   6031:         my %access_controls = &get_access_controls($current_perms,
                   6032:                                                    $group,$file_name);
                   6033:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   6034:             my ($num,$scope,$end,$start) = 
                   6035:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6036:             if ($scope eq 'public') {
                   6037:                 if ($start <= $now && $end == 0) {
                   6038:                     $action = 'none';
                   6039:                 } else {
                   6040:                     $action = 'update';
                   6041:                     $aclnum = $num;
                   6042:                 }
                   6043:                 last;
                   6044:             }
                   6045:         }
                   6046:         if ($action eq 'none') {
                   6047:              return 'ok';
                   6048:         } else {
                   6049:             my %changes;
                   6050:             my $newend = 0;
                   6051:             my $newstart = $now;
                   6052:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   6053:             $changes{$action}{$newkey} = {
                   6054:                 type => 'public',
                   6055:                 time => {
                   6056:                     start => $newstart,
                   6057:                     end   => $newend,
                   6058:                 },
                   6059:             };
                   6060:             my ($outcome,$deloutcome,$new_values,$translation) =
                   6061:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   6062:             return $outcome;
                   6063:         }
                   6064:     } else {
                   6065:         return 'invalid';
                   6066:     }
                   6067: }
                   6068: 
1.745     raeburn  6069: #------------------------------------------------------Get Marked as Read Only
                   6070: 
                   6071: sub get_marked_as_readonly {
                   6072:     my ($domain,$user,$what,$group) = @_;
                   6073:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 6074:     my @readonly_files;
1.629     banghart 6075:     my $cmp1=$what;
                   6076:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  6077:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   6078:         if (defined($group)) {
                   6079:             if ($file_name !~ m-^\Q$group\E/-) {
                   6080:                 next;
                   6081:             }
                   6082:         }
1.561     banghart 6083:         if (ref($value) eq "ARRAY"){
                   6084:             foreach my $stored_what (@{$value}) {
1.629     banghart 6085:                 my $cmp2=$stored_what;
1.759     albertel 6086:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  6087:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  6088:                 }
1.629     banghart 6089:                 if ($cmp1 eq $cmp2) {
1.561     banghart 6090:                     push(@readonly_files, $file_name);
1.745     raeburn  6091:                     last;
1.563     banghart 6092:                 } elsif (!defined($what)) {
                   6093:                     push(@readonly_files, $file_name);
1.745     raeburn  6094:                     last;
1.561     banghart 6095:                 }
                   6096:             }
1.745     raeburn  6097:         }
1.561     banghart 6098:     }
                   6099:     return @readonly_files;
                   6100: }
1.577     banghart 6101: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 6102: 
1.577     banghart 6103: sub get_marked_as_readonly_hash {
1.745     raeburn  6104:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 6105:     my %readonly_files;
1.745     raeburn  6106:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   6107:         if (defined($group)) {
                   6108:             if ($file_name !~ m-^\Q$group\E/-) {
                   6109:                 next;
                   6110:             }
                   6111:         }
1.577     banghart 6112:         if (ref($value) eq "ARRAY"){
                   6113:             foreach my $stored_what (@{$value}) {
1.745     raeburn  6114:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 6115:                     foreach my $lock_descriptor(@{$stored_what}) {
                   6116:                         if ($lock_descriptor eq 'graded') {
                   6117:                             $readonly_files{$file_name} = 'graded';
                   6118:                         } elsif ($lock_descriptor eq 'handback') {
                   6119:                             $readonly_files{$file_name} = 'handback';
                   6120:                         } else {
                   6121:                             if (!exists($readonly_files{$file_name})) {
                   6122:                                 $readonly_files{$file_name} = 'locked';
                   6123:                             }
                   6124:                         }
1.745     raeburn  6125:                     }
1.750     banghart 6126:                 } 
1.577     banghart 6127:             }
                   6128:         } 
                   6129:     }
                   6130:     return %readonly_files;
                   6131: }
1.559     banghart 6132: # ------------------------------------------------------------ Unmark as Read Only
                   6133: 
                   6134: sub unmark_as_readonly {
1.629     banghart 6135:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   6136:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  6137:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 6138:     $file_name = &declutter_portfile($file_name);
1.634     albertel 6139:     my $symb_crs = $what;
                   6140:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  6141:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 6142:     my ($tmp)=keys(%current_permissions);
                   6143:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  6144:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 6145:     foreach my $file (@readonly_files) {
1.759     albertel 6146: 	my $clean_file = &declutter_portfile($file);
                   6147: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 6148: 	my $current_locks = $current_permissions{$file};
1.563     banghart 6149:         my @new_locks;
                   6150:         my @del_keys;
                   6151:         if (ref($current_locks) eq "ARRAY"){
                   6152:             foreach my $locker (@{$current_locks}) {
1.632     albertel 6153:                 my $compare=$locker;
1.749     raeburn  6154:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  6155:                     $compare=join('',@{$locker});
1.746     raeburn  6156:                     if ($compare ne $symb_crs) {
                   6157:                         push(@new_locks, $locker);
                   6158:                     }
1.563     banghart 6159:                 }
                   6160:             }
1.650     albertel 6161:             if (scalar(@new_locks) > 0) {
1.563     banghart 6162:                 $current_permissions{$file} = \@new_locks;
                   6163:             } else {
                   6164:                 push(@del_keys, $file);
1.613     albertel 6165:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 6166:                 delete($current_permissions{$file});
1.563     banghart 6167:             }
                   6168:         }
1.561     banghart 6169:     }
1.613     albertel 6170:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 6171:     return;
                   6172: }
1.512     banghart 6173: 
1.17      www      6174: # ------------------------------------------------------------ Directory lister
                   6175: 
                   6176: sub dirlist {
1.253     stredwic 6177:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
                   6178: 
1.18      www      6179:     $uri=~s/^\///;
                   6180:     $uri=~s/\/$//;
1.253     stredwic 6181:     my ($udom, $uname);
                   6182:     (undef,$udom,$uname)=split(/\//,$uri);
                   6183:     if(defined($userdomain)) {
                   6184:         $udom = $userdomain;
                   6185:     }
                   6186:     if(defined($username)) {
                   6187:         $uname = $username;
                   6188:     }
                   6189: 
                   6190:     my $dirRoot = $perlvar{'lonDocRoot'};
                   6191:     if(defined($alternateDirectoryRoot)) {
                   6192:         $dirRoot = $alternateDirectoryRoot;
                   6193:         $dirRoot =~ s/\/$//;
1.751     banghart 6194:     }
1.253     stredwic 6195: 
                   6196:     if($udom) {
                   6197:         if($uname) {
1.800     albertel 6198:             my $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   6199: 				 &homeserver($uname,$udom));
1.605     matthew  6200:             my @listing_results;
                   6201:             if ($listing eq 'unknown_cmd') {
1.800     albertel 6202:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   6203: 				  &homeserver($uname,$udom));
1.605     matthew  6204:                 @listing_results = split(/:/,$listing);
                   6205:             } else {
                   6206:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   6207:             }
                   6208:             return @listing_results;
1.253     stredwic 6209:         } elsif(!defined($alternateDirectoryRoot)) {
1.800     albertel 6210:             my %allusers;
1.841     albertel 6211: 	    my %servers = &get_servers($udom,'library');
                   6212: 	    foreach my $tryserver (keys(%servers)) {
                   6213: 		my $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   6214: 				     $udom, $tryserver);
                   6215: 		my @listing_results;
                   6216: 		if ($listing eq 'unknown_cmd') {
                   6217: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   6218: 				      $udom, $tryserver);
                   6219: 		    @listing_results = split(/:/,$listing);
                   6220: 		} else {
                   6221: 		    @listing_results =
                   6222: 			map { &unescape($_); } split(/:/,$listing);
                   6223: 		}
                   6224: 		if ($listing_results[0] ne 'no_such_dir' && 
                   6225: 		    $listing_results[0] ne 'empty'       &&
                   6226: 		    $listing_results[0] ne 'con_lost') {
                   6227: 		    foreach my $line (@listing_results) {
                   6228: 			my ($entry) = split(/&/,$line,2);
                   6229: 			$allusers{$entry} = 1;
                   6230: 		    }
                   6231: 		}
1.253     stredwic 6232:             }
                   6233:             my $alluserstr='';
1.800     albertel 6234:             foreach my $user (sort(keys(%allusers))) {
                   6235:                 $alluserstr.=$user.'&user:';
1.253     stredwic 6236:             }
                   6237:             $alluserstr=~s/:$//;
                   6238:             return split(/:/,$alluserstr);
                   6239:         } else {
1.800     albertel 6240:             return ('missing user name');
1.253     stredwic 6241:         }
                   6242:     } elsif(!defined($alternateDirectoryRoot)) {
1.841     albertel 6243:         my @all_domains = sort(&all_domains());
                   6244:          foreach my $domain (@all_domains) {
                   6245:              $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   6246:          }
                   6247:          return @all_domains;
                   6248:      } else {
1.800     albertel 6249:         return ('missing domain');
1.275     stredwic 6250:     }
                   6251: }
                   6252: 
                   6253: # --------------------------------------------- GetFileTimestamp
                   6254: # This function utilizes dirlist and returns the date stamp for
                   6255: # when it was last modified.  It will also return an error of -1
                   6256: # if an error occurs
                   6257: 
1.410     matthew  6258: ##
                   6259: ## FIXME: This subroutine assumes its caller knows something about the
                   6260: ## directory structure of the home server for the student ($root).
                   6261: ## Not a good assumption to make.  Since this is for looking up files
                   6262: ## in user directories, the full path should be constructed by lond, not
                   6263: ## whatever machine we request data from.
                   6264: ##
1.275     stredwic 6265: sub GetFileTimestamp {
                   6266:     my ($studentDomain,$studentName,$filename,$root)=@_;
1.807     albertel 6267:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   6268:     $studentName   = &LONCAPA::clean_username($studentName);
1.275     stredwic 6269:     my $subdir=$studentName.'__';
                   6270:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   6271:     my $proname="$studentDomain/$subdir/$studentName";
                   6272:     $proname .= '/'.$filename;
1.375     matthew  6273:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
                   6274:                                               $studentName, $root);
1.275     stredwic 6275:     my @stats = split('&', $fileStat);
                   6276:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  6277:         # @stats contains first the filename, then the stat output
                   6278:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 6279:     } else {
                   6280:         return -1;
1.253     stredwic 6281:     }
1.26      www      6282: }
                   6283: 
1.712     albertel 6284: sub stat_file {
                   6285:     my ($uri) = @_;
1.787     albertel 6286:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 6287: 
1.712     albertel 6288:     my ($udom,$uname,$file,$dir);
                   6289:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   6290: 	($udom,$uname,$file) =
1.811     albertel 6291: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 6292: 	$file = 'userfiles/'.$file;
1.740     www      6293: 	$dir = &propath($udom,$uname);
1.712     albertel 6294:     }
                   6295:     if ($uri =~ m-^/res/-) {
                   6296: 	($udom,$uname) = 
1.807     albertel 6297: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 6298: 	$file = $uri;
                   6299:     }
                   6300: 
                   6301:     if (!$udom || !$uname || !$file) {
                   6302: 	# unable to handle the uri
                   6303: 	return ();
                   6304:     }
                   6305: 
                   6306:     my ($result) = &dirlist($file,$udom,$uname,$dir);
                   6307:     my @stats = split('&', $result);
1.721     banghart 6308:     
1.712     albertel 6309:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   6310: 	shift(@stats); #filename is first
                   6311: 	return @stats;
                   6312:     }
                   6313:     return ();
                   6314: }
                   6315: 
1.26      www      6316: # -------------------------------------------------------- Value of a Condition
                   6317: 
1.713     albertel 6318: # gets the value of a specific preevaluated condition
                   6319: #    stored in the string  $env{user.state.<cid>}
                   6320: # or looks up a condition reference in the bighash and if if hasn't
                   6321: # already been evaluated recurses into docondval to get the value of
                   6322: # the condition, then memoizing it to 
                   6323: #   $env{user.state.<cid>.<condition>}
1.40      www      6324: sub directcondval {
                   6325:     my $number=shift;
1.620     albertel 6326:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 6327: 	&Apache::lonuserstate::evalstate();
                   6328:     }
1.713     albertel 6329:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   6330: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   6331:     } elsif ($number =~ /^_/) {
                   6332: 	my $sub_condition;
                   6333: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   6334: 		&GDBM_READER(),0640)) {
                   6335: 	    $sub_condition=$bighash{'conditions'.$number};
                   6336: 	    untie(%bighash);
                   6337: 	}
                   6338: 	my $value = &docondval($sub_condition);
                   6339: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
                   6340: 	return $value;
                   6341:     }
1.620     albertel 6342:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   6343:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      6344:     } else {
                   6345:        return 2;
                   6346:     }
                   6347: }
                   6348: 
1.713     albertel 6349: # get the collection of conditions for this resource
1.26      www      6350: sub condval {
                   6351:     my $condidx=shift;
1.54      www      6352:     my $allpathcond='';
1.713     albertel 6353:     foreach my $cond (split(/\|/,$condidx)) {
                   6354: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   6355: 	    $allpathcond.=
                   6356: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   6357: 	}
1.191     harris41 6358:     }
1.54      www      6359:     $allpathcond=~s/\|$//;
1.713     albertel 6360:     return &docondval($allpathcond);
                   6361: }
                   6362: 
                   6363: #evaluates an expression of conditions
                   6364: sub docondval {
                   6365:     my ($allpathcond) = @_;
                   6366:     my $result=0;
                   6367:     if ($env{'request.course.id'}
                   6368: 	&& defined($allpathcond)) {
                   6369: 	my $operand='|';
                   6370: 	my @stack;
                   6371: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   6372: 	    if ($chunk eq '(') {
                   6373: 		push @stack,($operand,$result);
                   6374: 	    } elsif ($chunk eq ')') {
                   6375: 		my $before=pop @stack;
                   6376: 		if (pop @stack eq '&') {
                   6377: 		    $result=$result>$before?$before:$result;
                   6378: 		} else {
                   6379: 		    $result=$result>$before?$result:$before;
                   6380: 		}
                   6381: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   6382: 		$operand=$chunk;
                   6383: 	    } else {
                   6384: 		my $new=directcondval($chunk);
                   6385: 		if ($operand eq '&') {
                   6386: 		    $result=$result>$new?$new:$result;
                   6387: 		} else {
                   6388: 		    $result=$result>$new?$result:$new;
                   6389: 		}
                   6390: 	    }
                   6391: 	}
1.26      www      6392:     }
                   6393:     return $result;
1.421     albertel 6394: }
                   6395: 
                   6396: # ---------------------------------------------------- Devalidate courseresdata
                   6397: 
                   6398: sub devalidatecourseresdata {
                   6399:     my ($coursenum,$coursedomain)=@_;
                   6400:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 6401:     &devalidate_cache_new('courseres',$hashid);
1.28      www      6402: }
                   6403: 
1.763     www      6404: 
1.200     www      6405: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     6406: #
                   6407: #  Parameters:
                   6408: #      $coursenum    - Number of the course.
                   6409: #      $coursedomain - Domain at which the course was created.
                   6410: #  Returns:
                   6411: #     A hash of the course parameters along (I think) with timestamps
                   6412: #     and version info.
1.877     foxr     6413: 
1.624     albertel 6414: sub get_courseresdata {
                   6415:     my ($coursenum,$coursedomain)=@_;
1.200     www      6416:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   6417:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 6418:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 6419:     my %dumpreply;
1.417     albertel 6420:     unless (defined($cached)) {
1.624     albertel 6421: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 6422: 	$result=\%dumpreply;
1.251     albertel 6423: 	my ($tmp) = keys(%dumpreply);
                   6424: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 6425: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 6426: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   6427: 	    return $tmp;
1.416     albertel 6428: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 6429: 	    $result=undef;
1.599     albertel 6430: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 6431: 	}
                   6432:     }
1.624     albertel 6433:     return $result;
                   6434: }
                   6435: 
1.633     albertel 6436: sub devalidateuserresdata {
                   6437:     my ($uname,$udom)=@_;
                   6438:     my $hashid="$udom:$uname";
                   6439:     &devalidate_cache_new('userres',$hashid);
                   6440: }
                   6441: 
1.624     albertel 6442: sub get_userresdata {
                   6443:     my ($uname,$udom)=@_;
                   6444:     #most student don\'t have any data set, check if there is some data
                   6445:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   6446: 
                   6447:     my $hashid="$udom:$uname";
                   6448:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   6449:     if (!defined($cached)) {
                   6450: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   6451: 	$result=\%resourcedata;
                   6452: 	&do_cache_new('userres',$hashid,$result,600);
                   6453:     }
                   6454:     my ($tmp)=keys(%$result);
                   6455:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   6456: 	return $result;
                   6457:     }
                   6458:     #error 2 occurs when the .db doesn't exist
                   6459:     if ($tmp!~/error: 2 /) {
1.672     albertel 6460: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 6461: 		 " Trying to get resource data for ".
                   6462: 		 $uname." at ".$udom.": ".
                   6463: 		 $tmp."</font>");
                   6464:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 6465: 	#&EXT_cache_set($udom,$uname);
                   6466: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 6467: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 6468:     }
                   6469:     return $tmp;
                   6470: }
1.879     foxr     6471: #----------------------------------------------- resdata - return resource data
                   6472: #  Purpose:
                   6473: #    Return resource data for either users or for a course.
                   6474: #  Parameters:
                   6475: #     $name      - Course/user name.
                   6476: #     $domain    - Name of the domain the user/course is registered on.
                   6477: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   6478: #     @which     - Array of names of resources desired.
                   6479: #  Returns:
                   6480: #     The value of the first reasource in @which that is found in the
                   6481: #     resource hash.
                   6482: #  Exceptional Conditions:
                   6483: #     If the $type passed in is not valid (not the string 'course' or 
                   6484: #     'user', an undefined  reference is returned.
                   6485: #     If none of the resources are found, an undef is returned
1.624     albertel 6486: sub resdata {
                   6487:     my ($name,$domain,$type,@which)=@_;
                   6488:     my $result;
                   6489:     if ($type eq 'course') {
                   6490: 	$result=&get_courseresdata($name,$domain);
                   6491:     } elsif ($type eq 'user') {
                   6492: 	$result=&get_userresdata($name,$domain);
                   6493:     }
                   6494:     if (!ref($result)) { return $result; }    
1.251     albertel 6495:     foreach my $item (@which) {
1.927     albertel 6496: 	if (defined($result->{$item->[0]})) {
                   6497: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 6498: 	}
1.250     albertel 6499:     }
1.291     albertel 6500:     return undef;
1.200     www      6501: }
                   6502: 
1.379     matthew  6503: #
                   6504: # EXT resource caching routines
                   6505: #
                   6506: 
                   6507: sub clear_EXT_cache_status {
1.383     albertel 6508:     &delenv('cache.EXT.');
1.379     matthew  6509: }
                   6510: 
                   6511: sub EXT_cache_status {
                   6512:     my ($target_domain,$target_user) = @_;
1.383     albertel 6513:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 6514:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  6515:         # We know already the user has no data
                   6516:         return 1;
                   6517:     } else {
                   6518:         return 0;
                   6519:     }
                   6520: }
                   6521: 
                   6522: sub EXT_cache_set {
                   6523:     my ($target_domain,$target_user) = @_;
1.383     albertel 6524:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.633     albertel 6525:     #&appenv($cachename => time);
1.379     matthew  6526: }
                   6527: 
1.28      www      6528: # --------------------------------------------------------- Value of a Variable
1.58      www      6529: sub EXT {
1.715     albertel 6530: 
1.395     albertel 6531:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      6532:     unless ($varname) { return ''; }
1.218     albertel 6533:     #get real user name/domain, courseid and symb
                   6534:     my $courseid;
1.359     albertel 6535:     my $publicuser;
1.427     www      6536:     if ($symbparm) {
                   6537: 	$symbparm=&get_symb_from_alias($symbparm);
                   6538:     }
1.218     albertel 6539:     if (!($uname && $udom)) {
1.790     albertel 6540:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 6541:       if (!$symbparm) {	$symbparm=$cursymb; }
                   6542:     } else {
1.620     albertel 6543: 	$courseid=$env{'request.course.id'};
1.218     albertel 6544:     }
1.48      www      6545:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   6546:     my $rest;
1.320     albertel 6547:     if (defined($therest[0])) {
1.48      www      6548:        $rest=join('.',@therest);
                   6549:     } else {
                   6550:        $rest='';
                   6551:     }
1.320     albertel 6552: 
1.57      www      6553:     my $qualifierrest=$qualifier;
                   6554:     if ($rest) { $qualifierrest.='.'.$rest; }
                   6555:     my $spacequalifierrest=$space;
                   6556:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      6557:     if ($realm eq 'user') {
1.48      www      6558: # --------------------------------------------------------------- user.resource
                   6559: 	if ($space eq 'resource') {
1.651     albertel 6560: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   6561: 		  || defined($Apache::lonhomework::parsing_a_task))
                   6562: 		 &&
1.744     albertel 6563: 		 ($symbparm eq &symbread()) ) {	
                   6564: 		# if we are in the middle of processing the resource the
                   6565: 		# get the value we are planning on committing
                   6566:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   6567:                     return $Apache::lonhomework::results{$qualifierrest};
                   6568:                 } else {
                   6569:                     return $Apache::lonhomework::history{$qualifierrest};
                   6570:                 }
1.335     albertel 6571: 	    } else {
1.359     albertel 6572: 		my %restored;
1.620     albertel 6573: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 6574: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   6575: 		} else {
                   6576: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   6577: 		}
1.335     albertel 6578: 		return $restored{$qualifierrest};
                   6579: 	    }
1.48      www      6580: # ----------------------------------------------------------------- user.access
                   6581:         } elsif ($space eq 'access') {
1.218     albertel 6582: 	    # FIXME - not supporting calls for a specific user
1.48      www      6583:             return &allowed($qualifier,$rest);
                   6584: # ------------------------------------------ user.preferences, user.environment
                   6585:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 6586: 	    if (($uname eq $env{'user.name'}) &&
                   6587: 		($udom eq $env{'user.domain'})) {
                   6588: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 6589: 	    } else {
1.359     albertel 6590: 		my %returnhash;
                   6591: 		if (!$publicuser) {
                   6592: 		    %returnhash=&userenvironment($udom,$uname,
                   6593: 						 $qualifierrest);
                   6594: 		}
1.218     albertel 6595: 		return $returnhash{$qualifierrest};
                   6596: 	    }
1.48      www      6597: # ----------------------------------------------------------------- user.course
                   6598:         } elsif ($space eq 'course') {
1.218     albertel 6599: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 6600:             return $env{join('.',('request.course',$qualifier))};
1.48      www      6601: # ------------------------------------------------------------------- user.role
                   6602:         } elsif ($space eq 'role') {
1.218     albertel 6603: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 6604:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      6605:             if ($qualifier eq 'value') {
                   6606: 		return $role;
                   6607:             } elsif ($qualifier eq 'extent') {
                   6608:                 return $where;
                   6609:             }
                   6610: # ----------------------------------------------------------------- user.domain
                   6611:         } elsif ($space eq 'domain') {
1.218     albertel 6612:             return $udom;
1.48      www      6613: # ------------------------------------------------------------------- user.name
                   6614:         } elsif ($space eq 'name') {
1.218     albertel 6615:             return $uname;
1.48      www      6616: # ---------------------------------------------------- Any other user namespace
1.29      www      6617:         } else {
1.359     albertel 6618: 	    my %reply;
                   6619: 	    if (!$publicuser) {
                   6620: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   6621: 	    }
                   6622: 	    return $reply{$qualifierrest};
1.48      www      6623:         }
1.236     www      6624:     } elsif ($realm eq 'query') {
                   6625: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 6626:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   6627: 						[$spacequalifierrest]);
1.620     albertel 6628: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      6629:    } elsif ($realm eq 'request') {
1.48      www      6630: # ------------------------------------------------------------- request.browser
                   6631:         if ($space eq 'browser') {
1.430     www      6632: 	    if ($qualifier eq 'textremote') {
1.676     albertel 6633: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      6634: 		    return 1;
                   6635: 		} else {
                   6636: 		    return 0;
                   6637: 		}
                   6638: 	    } else {
1.620     albertel 6639: 		return $env{'browser.'.$qualifier};
1.430     www      6640: 	    }
1.57      www      6641: # ------------------------------------------------------------ request.filename
                   6642:         } else {
1.620     albertel 6643:             return $env{'request.'.$spacequalifierrest};
1.29      www      6644:         }
1.28      www      6645:     } elsif ($realm eq 'course') {
1.48      www      6646: # ---------------------------------------------------------- course.description
1.620     albertel 6647:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      6648:     } elsif ($realm eq 'resource') {
1.165     www      6649: 
1.620     albertel 6650: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 6651: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   6652: 	}
1.693     albertel 6653: 
                   6654: 	if ($space eq 'title') {
                   6655: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   6656: 	    return &gettitle($symbparm);
                   6657: 	}
                   6658: 	
                   6659: 	if ($space eq 'map') {
                   6660: 	    my ($map) = &decode_symb($symbparm);
                   6661: 	    return &symbread($map);
                   6662: 	}
1.905     albertel 6663: 	if ($space eq 'filename') {
                   6664: 	    if ($symbparm) {
                   6665: 		return &clutter((&decode_symb($symbparm))[2]);
                   6666: 	    }
                   6667: 	    return &hreflocation('',$env{'request.filename'});
                   6668: 	}
1.693     albertel 6669: 
                   6670: 	my ($section, $group, @groups);
1.593     albertel 6671: 	my ($courselevelm,$courselevel);
1.539     albertel 6672: 	if ($symbparm && defined($courseid) && 
1.620     albertel 6673: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      6674: 
1.218     albertel 6675: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      6676: 
1.60      www      6677: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 6678: 	    my $symbp=$symbparm;
1.735     albertel 6679: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 6680: 
                   6681: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   6682: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   6683: 
1.620     albertel 6684: 	    if (($env{'user.name'} eq $uname) &&
                   6685: 		($env{'user.domain'} eq $udom)) {
                   6686: 		$section=$env{'request.course.sec'};
1.733     raeburn  6687:                 @groups = split(/:/,$env{'request.course.groups'});  
                   6688:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 6689: 	    } else {
1.539     albertel 6690: 		if (! defined($usection)) {
1.551     albertel 6691: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 6692: 		} else {
                   6693: 		    $section = $usection;
                   6694: 		}
1.733     raeburn  6695:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 6696: 	    }
                   6697: 
                   6698: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   6699: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   6700: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   6701: 
1.593     albertel 6702: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 6703: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 6704: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      6705: 
1.60      www      6706: # ----------------------------------------------------------- first, check user
1.624     albertel 6707: 
                   6708: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 6709: 				       ([$courselevelr,'resource'],
                   6710: 					[$courselevelm,'map'     ],
                   6711: 					[$courselevel, 'course'  ]));
1.931     albertel 6712: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      6713: 
1.594     albertel 6714: # ------------------------------------------------ second, check some of course
1.684     raeburn  6715:             my $coursereply;
1.691     raeburn  6716:             if (@groups > 0) {
                   6717:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   6718:                                        $mapparm,$spacequalifierrest);
1.927     albertel 6719:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  6720:             }
1.96      www      6721: 
1.684     raeburn  6722: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 6723: 				  $env{'course.'.$courseid.'.domain'},
                   6724: 				  'course',
                   6725: 				  ([$seclevelr,   'resource'],
                   6726: 				   [$seclevelm,   'map'     ],
                   6727: 				   [$seclevel,    'course'  ],
                   6728: 				   [$courselevelr,'resource']));
                   6729: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      6730: 
1.60      www      6731: # ------------------------------------------------------ third, check map parms
1.218     albertel 6732: 	    my %parmhash=();
                   6733: 	    my $thisparm='';
                   6734: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 6735: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 6736: 		    &GDBM_READER(),0640)) {
1.218     albertel 6737: 		$thisparm=$parmhash{$symbparm};
                   6738: 		untie(%parmhash);
                   6739: 	    }
1.927     albertel 6740: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 6741: 	}
1.594     albertel 6742: # ------------------------------------------ fourth, look in resource metadata
1.71      www      6743: 
1.218     albertel 6744: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 6745: 	my $filename;
                   6746: 	if (!$symbparm) { $symbparm=&symbread(); }
                   6747: 	if ($symbparm) {
1.409     www      6748: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 6749: 	} else {
1.620     albertel 6750: 	    $filename=$env{'request.filename'};
1.282     albertel 6751: 	}
                   6752: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 6753: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 6754: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 6755: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      6756: 
1.927     albertel 6757: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 6758: 	if ($symbparm && defined($courseid) && 
1.620     albertel 6759: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 6760: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   6761: 				     $env{'course.'.$courseid.'.domain'},
                   6762: 				     'course',
1.927     albertel 6763: 				     ([$courselevelm,'map'   ],
                   6764: 				      [$courselevel, 'course']));
                   6765: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 6766: 	}
1.145     www      6767: # ------------------------------------------------------------------ Cascade up
1.218     albertel 6768: 	unless ($space eq '0') {
1.336     albertel 6769: 	    my @parts=split(/_/,$space);
                   6770: 	    my $id=pop(@parts);
                   6771: 	    my $part=join('_',@parts);
                   6772: 	    if ($part eq '') { $part='0'; }
1.927     albertel 6773: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 6774: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  6775: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 6776: 	}
1.395     albertel 6777: 	if ($recurse) { return undef; }
                   6778: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 6779: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      6780: # ---------------------------------------------------- Any other user namespace
                   6781:     } elsif ($realm eq 'environment') {
                   6782: # ----------------------------------------------------------------- environment
1.620     albertel 6783: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   6784: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 6785: 	} else {
1.770     albertel 6786: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   6787: 		return '';
                   6788: 	    }
1.219     albertel 6789: 	    my %returnhash=&userenvironment($udom,$uname,
                   6790: 					    $spacequalifierrest);
                   6791: 	    return $returnhash{$spacequalifierrest};
                   6792: 	}
1.28      www      6793:     } elsif ($realm eq 'system') {
1.48      www      6794: # ----------------------------------------------------------------- system.time
                   6795: 	if ($space eq 'time') {
                   6796: 	    return time;
                   6797:         }
1.696     albertel 6798:     } elsif ($realm eq 'server') {
                   6799: # ----------------------------------------------------------------- system.time
                   6800: 	if ($space eq 'name') {
                   6801: 	    return $ENV{'SERVER_NAME'};
                   6802:         }
1.28      www      6803:     }
1.48      www      6804:     return '';
1.61      www      6805: }
                   6806: 
1.927     albertel 6807: sub get_reply {
                   6808:     my ($reply_value) = @_;
1.940     raeburn  6809:     if (ref($reply_value) eq 'ARRAY') {
                   6810:         if (wantarray) {
                   6811: 	    return @$reply_value;
                   6812:         }
                   6813:         return $reply_value->[0];
                   6814:     } else {
                   6815:         return $reply_value;
1.927     albertel 6816:     }
                   6817: }
                   6818: 
1.691     raeburn  6819: sub check_group_parms {
                   6820:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   6821:     my @groupitems = ();
                   6822:     my $resultitem;
1.927     albertel 6823:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  6824:     foreach my $group (@{$groups}) {
                   6825:         foreach my $level (@levels) {
1.927     albertel 6826:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   6827:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  6828:         }
                   6829:     }
                   6830:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   6831:                             $env{'course.'.$courseid.'.domain'},
                   6832:                                      'course',@groupitems);
                   6833:     return $coursereply;
                   6834: }
                   6835: 
                   6836: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  6837:     my ($courseid,@groups) = @_;
                   6838:     @groups = sort(@groups);
1.691     raeburn  6839:     return @groups;
                   6840: }
                   6841: 
1.395     albertel 6842: sub packages_tab_default {
                   6843:     my ($uri,$varname)=@_;
                   6844:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 6845: 
                   6846:     my (@extension,@specifics,$do_default);
                   6847:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 6848: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 6849: 	if ($pack_type eq 'default') {
                   6850: 	    $do_default=1;
                   6851: 	} elsif ($pack_type eq 'extension') {
                   6852: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 6853: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 6854: 	    # only look at packages defaults for packages that this id is
1.738     albertel 6855: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   6856: 	}
                   6857:     }
                   6858:     # first look for a package that matches the requested part id
                   6859:     foreach my $package (@specifics) {
                   6860: 	my (undef,$pack_type,$pack_part)=@{$package};
                   6861: 	next if ($pack_part ne $part);
                   6862: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6863: 	    return $packagetab{"$pack_type&$name&default"};
                   6864: 	}
                   6865:     }
                   6866:     # look for any possible matching non extension_ package
                   6867:     foreach my $package (@specifics) {
                   6868: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 6869: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6870: 	    return $packagetab{"$pack_type&$name&default"};
                   6871: 	}
1.585     albertel 6872: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 6873: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   6874: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 6875: 	}
                   6876:     }
1.738     albertel 6877:     # look for any posible extension_ match
                   6878:     foreach my $package (@extension) {
                   6879: 	my ($package,$pack_type)=@{$package};
                   6880: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6881: 	    return $packagetab{"$pack_type&$name&default"};
                   6882: 	}
                   6883: 	if (defined($packagetab{$package."&$name&default"})) {
                   6884: 	    return $packagetab{$package."&$name&default"};
                   6885: 	}
                   6886:     }
                   6887:     # look for a global default setting
                   6888:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   6889: 	return $packagetab{"default&$name&default"};
                   6890:     }
1.395     albertel 6891:     return undef;
                   6892: }
                   6893: 
1.334     albertel 6894: sub add_prefix_and_part {
                   6895:     my ($prefix,$part)=@_;
                   6896:     my $keyroot;
                   6897:     if (defined($prefix) && $prefix !~ /^__/) {
                   6898: 	# prefix that has a part already
                   6899: 	$keyroot=$prefix;
                   6900:     } elsif (defined($prefix)) {
                   6901: 	# prefix that is missing a part
                   6902: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   6903:     } else {
                   6904: 	# no prefix at all
                   6905: 	if (defined($part)) { $keyroot='_'.$part; }
                   6906:     }
                   6907:     return $keyroot;
                   6908: }
                   6909: 
1.71      www      6910: # ---------------------------------------------------------------- Get metadata
                   6911: 
1.599     albertel 6912: my %metaentry;
1.71      www      6913: sub metadata {
1.176     www      6914:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      6915:     $uri=&declutter($uri);
1.288     albertel 6916:     # if it is a non metadata possible uri return quickly
1.529     albertel 6917:     if (($uri eq '') || 
                   6918: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 6919: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.924     albertel 6920:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
                   6921: 	return undef;
                   6922:     }
                   6923:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
                   6924: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 6925: 	return undef;
1.288     albertel 6926:     }
1.73      www      6927:     my $filename=$uri;
                   6928:     $uri=~s/\.meta$//;
1.172     www      6929: #
                   6930: # Is the metadata already cached?
1.177     www      6931: # Look at timestamp of caching
1.172     www      6932: # Everything is cached by the main uri, libraries are never directly cached
                   6933: #
1.428     albertel 6934:     if (!defined($liburi)) {
1.599     albertel 6935: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 6936: 	if (defined($cached)) { return $result->{':'.$what}; }
                   6937:     }
                   6938:     {
1.172     www      6939: #
                   6940: # Is this a recursive call for a library?
                   6941: #
1.599     albertel 6942: #	if (! exists($metacache{$uri})) {
                   6943: #	    $metacache{$uri}={};
                   6944: #	}
1.924     albertel 6945: 	my $cachetime = 60*60;
1.171     www      6946:         if ($liburi) {
                   6947: 	    $liburi=&declutter($liburi);
                   6948:             $filename=$liburi;
1.401     bowersj2 6949:         } else {
1.599     albertel 6950: 	    &devalidate_cache_new('meta',$uri);
                   6951: 	    undef(%metaentry);
1.401     bowersj2 6952: 	}
1.140     www      6953:         my %metathesekeys=();
1.73      www      6954:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 6955: 	my $metastring;
1.924     albertel 6956: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929     albertel 6957: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 6958: 	    $metastring = 
1.929     albertel 6959: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 6960: 					  ('grade_target' => 'meta'));
                   6961: 	    $cachetime = 1; # only want this cached in the child not long term
                   6962: 	} elsif ($uri !~ m -^(editupload)/-) {
1.543     albertel 6963: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 6964: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 6965: 	    $metastring=&getfile($file);
1.489     albertel 6966: 	}
1.208     albertel 6967:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      6968:         my $token;
1.140     www      6969:         undef %metathesekeys;
1.71      www      6970:         while ($token=$parser->get_token) {
1.339     albertel 6971: 	    if ($token->[0] eq 'S') {
                   6972: 		if (defined($token->[2]->{'package'})) {
1.172     www      6973: #
                   6974: # This is a package - get package info
                   6975: #
1.339     albertel 6976: 		    my $package=$token->[2]->{'package'};
                   6977: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6978: 		    if (defined($token->[2]->{'id'})) { 
                   6979: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   6980: 		    }
1.599     albertel 6981: 		    if ($metaentry{':packages'}) {
                   6982: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 6983: 		    } else {
1.599     albertel 6984: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 6985: 		    }
1.736     albertel 6986: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 6987: 			my $part=$keyroot;
                   6988: 			$part=~s/^\_//;
1.736     albertel 6989: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   6990: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   6991: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 6992: 			    # ignore package.tab specified default values
                   6993:                             # here &package_tab_default() will fetch those
                   6994: 			    if ($subp eq 'default') { next; }
1.736     albertel 6995: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 6996: 			    my $unikey;
                   6997: 			    if ($pack =~ /_0$/) {
                   6998: 				$unikey='parameter_0_'.$name;
                   6999: 				$part=0;
                   7000: 			    } else {
                   7001: 				$unikey='parameter'.$keyroot.'_'.$name;
                   7002: 			    }
1.339     albertel 7003: 			    if ($subp eq 'display') {
                   7004: 				$value.=' [Part: '.$part.']';
                   7005: 			    }
1.599     albertel 7006: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 7007: 			    $metathesekeys{$unikey}=1;
1.599     albertel 7008: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   7009: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 7010: 			    }
1.599     albertel 7011: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   7012: 				$metaentry{':'.$unikey}=
                   7013: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 7014: 			    }
1.339     albertel 7015: 			}
                   7016: 		    }
                   7017: 		} else {
1.172     www      7018: #
                   7019: # This is not a package - some other kind of start tag
1.339     albertel 7020: #
                   7021: 		    my $entry=$token->[1];
                   7022: 		    my $unikey;
                   7023: 		    if ($entry eq 'import') {
                   7024: 			$unikey='';
                   7025: 		    } else {
                   7026: 			$unikey=$entry;
                   7027: 		    }
                   7028: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   7029: 
                   7030: 		    if (defined($token->[2]->{'id'})) { 
                   7031: 			$unikey.='_'.$token->[2]->{'id'}; 
                   7032: 		    }
1.175     www      7033: 
1.339     albertel 7034: 		    if ($entry eq 'import') {
1.175     www      7035: #
                   7036: # Importing a library here
1.339     albertel 7037: #
                   7038: 			if ($depthcount<20) {
                   7039: 			    my $location=$parser->get_text('/import');
                   7040: 			    my $dir=$filename;
                   7041: 			    $dir=~s|[^/]*$||;
                   7042: 			    $location=&filelocation($dir,$location);
1.736     albertel 7043: 			    my $metadata = 
                   7044: 				&metadata($uri,'keys', $location,$unikey,
                   7045: 					  $depthcount+1);
                   7046: 			    foreach my $meta (split(',',$metadata)) {
                   7047: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   7048: 				$metathesekeys{$meta}=1;
1.339     albertel 7049: 			    }
                   7050: 			}
                   7051: 		    } else { 
                   7052: 			
                   7053: 			if (defined($token->[2]->{'name'})) { 
                   7054: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   7055: 			}
                   7056: 			$metathesekeys{$unikey}=1;
1.736     albertel 7057: 			foreach my $param (@{$token->[3]}) {
                   7058: 			    $metaentry{':'.$unikey.'.'.$param} =
                   7059: 				$token->[2]->{$param};
1.339     albertel 7060: 			}
                   7061: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 7062: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 7063: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   7064: 		 # only ws inside the tag, and not in default, so use default
                   7065: 		 # as value
1.599     albertel 7066: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 7067: 			} elsif ( $internaltext =~ /\S/ ) {
                   7068: 		  # something interesting inside the tag
                   7069: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 7070: 			} else {
1.908     albertel 7071: 		  # no interesting values, don't set a default
1.339     albertel 7072: 			}
1.172     www      7073: # end of not-a-package not-a-library import
1.339     albertel 7074: 		    }
1.172     www      7075: # end of not-a-package start tag
1.339     albertel 7076: 		}
1.172     www      7077: # the next is the end of "start tag"
1.339     albertel 7078: 	    }
                   7079: 	}
1.483     albertel 7080: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 7081: 	$extension = lc($extension);
                   7082: 	if ($extension eq 'htm') { $extension='html'; }
                   7083: 
1.737     albertel 7084: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 7085: 	    #no specific packages #how's our extension
                   7086: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 7087: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 7088: 					 \%metathesekeys);
                   7089: 	}
1.883     albertel 7090: 
                   7091: 	if (!exists($metaentry{':packages'})
                   7092: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 7093: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 7094: 		#no specific packages well let's get default then
                   7095: 		if ($key!~/^default&/) { next; }
1.488     albertel 7096: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 7097: 					     \%metathesekeys);
                   7098: 	    }
                   7099: 	}
1.338     www      7100: # are there custom rights to evaluate
1.599     albertel 7101: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 7102: 
1.338     www      7103:     #
                   7104:     # Importing a rights file here
1.339     albertel 7105:     #
                   7106: 	    unless ($depthcount) {
1.599     albertel 7107: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 7108: 		my $dir=$filename;
                   7109: 		$dir=~s|[^/]*$||;
                   7110: 		$location=&filelocation($dir,$location);
1.736     albertel 7111: 		my $rights_metadata =
                   7112: 		    &metadata($uri,'keys',$location,'_rights',
                   7113: 			      $depthcount+1);
                   7114: 		foreach my $rights (split(',',$rights_metadata)) {
                   7115: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   7116: 		    $metathesekeys{$rights}=1;
1.339     albertel 7117: 		}
                   7118: 	    }
                   7119: 	}
1.737     albertel 7120: 	# uniqifiy package listing
                   7121: 	my %seen;
                   7122: 	my @uniq_packages =
                   7123: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   7124: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   7125: 
                   7126: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 7127: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   7128: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 7129: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      7130: # this is the end of "was not already recently cached
1.71      www      7131:     }
1.599     albertel 7132:     return $metaentry{':'.$what};
1.261     albertel 7133: }
                   7134: 
1.488     albertel 7135: sub metadata_create_package_def {
1.483     albertel 7136:     my ($uri,$key,$package,$metathesekeys)=@_;
                   7137:     my ($pack,$name,$subp)=split(/\&/,$key);
                   7138:     if ($subp eq 'default') { next; }
                   7139:     
1.599     albertel 7140:     if (defined($metaentry{':packages'})) {
                   7141: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 7142:     } else {
1.599     albertel 7143: 	$metaentry{':packages'}=$package;
1.483     albertel 7144:     }
                   7145:     my $value=$packagetab{$key};
                   7146:     my $unikey;
                   7147:     $unikey='parameter_0_'.$name;
1.599     albertel 7148:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 7149:     $$metathesekeys{$unikey}=1;
1.599     albertel 7150:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   7151: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 7152:     }
1.599     albertel 7153:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   7154: 	$metaentry{':'.$unikey}=
                   7155: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 7156:     }
                   7157: }
                   7158: 
1.261     albertel 7159: sub metadata_generate_part0 {
                   7160:     my ($metadata,$metacache,$uri) = @_;
                   7161:     my %allnames;
1.737     albertel 7162:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 7163: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 7164: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   7165: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 7166: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 7167: 	    $allnames{$name}=$part;
                   7168: 	  }
                   7169: 	}
                   7170:     }
                   7171:     foreach my $name (keys(%allnames)) {
                   7172:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 7173:       my $key=":parameter_0_$name";
1.261     albertel 7174:       $$metacache{"$key.part"}='0';
                   7175:       $$metacache{"$key.name"}=$name;
1.428     albertel 7176:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 7177: 					   $allnames{$name}.'_'.$name.
                   7178: 					   '.type'};
1.428     albertel 7179:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 7180: 			     '.display'};
1.644     www      7181:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 7182:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 7183:       $$metacache{"$key.display"}=$olddis;
                   7184:     }
1.71      www      7185: }
                   7186: 
1.764     albertel 7187: # ------------------------------------------------------ Devalidate title cache
                   7188: 
                   7189: sub devalidate_title_cache {
                   7190:     my ($url)=@_;
                   7191:     if (!$env{'request.course.id'}) { return; }
                   7192:     my $symb=&symbread($url);
                   7193:     if (!$symb) { return; }
                   7194:     my $key=$env{'request.course.id'}."\0".$symb;
                   7195:     &devalidate_cache_new('title',$key);
                   7196: }
                   7197: 
1.301     www      7198: # ------------------------------------------------- Get the title of a resource
                   7199: 
                   7200: sub gettitle {
                   7201:     my $urlsymb=shift;
                   7202:     my $symb=&symbread($urlsymb);
1.534     albertel 7203:     if ($symb) {
1.620     albertel 7204: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 7205: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 7206: 	if (defined($cached)) { 
                   7207: 	    return $result;
                   7208: 	}
1.534     albertel 7209: 	my ($map,$resid,$url)=&decode_symb($symb);
                   7210: 	my $title='';
1.907     albertel 7211: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   7212: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   7213: 	} else {
                   7214: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   7215: 		    &GDBM_READER(),0640)) {
                   7216: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   7217: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   7218: 		untie(%bighash);
                   7219: 	    }
1.534     albertel 7220: 	}
                   7221: 	$title=~s/\&colon\;/\:/gs;
                   7222: 	if ($title) {
1.599     albertel 7223: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 7224: 	}
                   7225: 	$urlsymb=$url;
                   7226:     }
                   7227:     my $title=&metadata($urlsymb,'title');
                   7228:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   7229:     return $title;
1.301     www      7230: }
1.613     albertel 7231: 
1.614     albertel 7232: sub get_slot {
                   7233:     my ($which,$cnum,$cdom)=@_;
                   7234:     if (!$cnum || !$cdom) {
1.790     albertel 7235: 	(undef,my $courseid)=&whichuser();
1.620     albertel 7236: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   7237: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 7238:     }
1.703     albertel 7239:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   7240:     my %slotinfo;
                   7241:     if (exists($remembered{$key})) {
                   7242: 	$slotinfo{$which} = $remembered{$key};
                   7243:     } else {
                   7244: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   7245: 	&Apache::lonhomework::showhash(%slotinfo);
                   7246: 	my ($tmp)=keys(%slotinfo);
                   7247: 	if ($tmp=~/^error:/) { return (); }
                   7248: 	$remembered{$key} = $slotinfo{$which};
                   7249:     }
1.616     albertel 7250:     if (ref($slotinfo{$which}) eq 'HASH') {
                   7251: 	return %{$slotinfo{$which}};
                   7252:     }
                   7253:     return $slotinfo{$which};
1.614     albertel 7254: }
1.31      www      7255: # ------------------------------------------------- Update symbolic store links
                   7256: 
                   7257: sub symblist {
                   7258:     my ($mapname,%newhash)=@_;
1.438     www      7259:     $mapname=&deversion(&declutter($mapname));
1.31      www      7260:     my %hash;
1.620     albertel 7261:     if (($env{'request.course.fn'}) && (%newhash)) {
                   7262:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 7263:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 7264: 	    foreach my $url (keys %newhash) {
                   7265: 		next if ($url eq 'last_known'
                   7266: 			 && $env{'form.no_update_last_known'});
                   7267: 		$hash{declutter($url)}=&encode_symb($mapname,
                   7268: 						    $newhash{$url}->[1],
                   7269: 						    $newhash{$url}->[0]);
1.191     harris41 7270:             }
1.31      www      7271:             if (untie(%hash)) {
                   7272: 		return 'ok';
                   7273:             }
                   7274:         }
                   7275:     }
                   7276:     return 'error';
1.212     www      7277: }
                   7278: 
                   7279: # --------------------------------------------------------------- Verify a symb
                   7280: 
                   7281: sub symbverify {
1.510     www      7282:     my ($symb,$thisurl)=@_;
                   7283:     my $thisfn=$thisurl;
1.439     www      7284:     $thisfn=&declutter($thisfn);
1.215     www      7285: # direct jump to resource in page or to a sequence - will construct own symbs
                   7286:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   7287: # check URL part
1.409     www      7288:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      7289: 
1.431     www      7290:     unless ($url eq $thisfn) { return 0; }
1.213     www      7291: 
1.216     www      7292:     $symb=&symbclean($symb);
1.510     www      7293:     $thisurl=&deversion($thisurl);
1.439     www      7294:     $thisfn=&deversion($thisfn);
1.213     www      7295: 
                   7296:     my %bighash;
                   7297:     my $okay=0;
1.431     www      7298: 
1.620     albertel 7299:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 7300:                             &GDBM_READER(),0640)) {
1.510     www      7301:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      7302:         unless ($ids) { 
1.510     www      7303:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      7304:         }
                   7305:         if ($ids) {
                   7306: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 7307: 	    foreach my $id (split(/\,/,$ids)) {
                   7308: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      7309:                if (
                   7310:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   7311:    eq $symb) { 
1.620     albertel 7312: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 7313: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 7314: 		       $okay=1; 
                   7315: 		   }
                   7316: 	       }
1.216     www      7317: 	   }
                   7318:         }
1.213     www      7319: 	untie(%bighash);
                   7320:     }
                   7321:     return $okay;
1.31      www      7322: }
                   7323: 
1.210     www      7324: # --------------------------------------------------------------- Clean-up symb
                   7325: 
                   7326: sub symbclean {
                   7327:     my $symb=shift;
1.568     albertel 7328:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      7329: # remove version from map
                   7330:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      7331: 
1.210     www      7332: # remove version from URL
                   7333:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      7334: 
1.507     www      7335: # remove wrapper
                   7336: 
1.510     www      7337:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 7338:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      7339:     return $symb;
1.409     www      7340: }
                   7341: 
                   7342: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 7343: 
                   7344: sub encode_symb {
                   7345:     my ($map,$resid,$url)=@_;
                   7346:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   7347: }
1.409     www      7348: 
                   7349: sub decode_symb {
1.568     albertel 7350:     my $symb=shift;
                   7351:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   7352:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      7353:     return (&fixversion($map),$resid,&fixversion($url));
                   7354: }
                   7355: 
                   7356: sub fixversion {
                   7357:     my $fn=shift;
1.609     banghart 7358:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      7359:     my %bighash;
                   7360:     my $uri=&clutter($fn);
1.620     albertel 7361:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      7362: # is this cached?
1.599     albertel 7363:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      7364:     if (defined($cached)) { return $result; }
                   7365: # unfortunately not cached, or expired
1.620     albertel 7366:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      7367: 	    &GDBM_READER(),0640)) {
                   7368:  	if ($bighash{'version_'.$uri}) {
                   7369:  	    my $version=$bighash{'version_'.$uri};
1.444     www      7370:  	    unless (($version eq 'mostrecent') || 
                   7371: 		    ($version==&getversion($uri))) {
1.440     www      7372:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   7373:  	    }
                   7374:  	}
                   7375:  	untie %bighash;
1.413     www      7376:     }
1.599     albertel 7377:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      7378: }
                   7379: 
                   7380: sub deversion {
                   7381:     my $url=shift;
                   7382:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   7383:     return $url;
1.210     www      7384: }
                   7385: 
1.31      www      7386: # ------------------------------------------------------ Return symb list entry
                   7387: 
                   7388: sub symbread {
1.249     www      7389:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 7390:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 7391:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      7392: # no filename provided? try from environment
1.44      www      7393:     unless ($thisfn) {
1.620     albertel 7394:         if ($env{'request.symb'}) {
                   7395: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 7396: 	}
1.620     albertel 7397: 	$thisfn=$env{'request.filename'};
1.44      www      7398:     }
1.569     albertel 7399:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      7400: # is that filename actually a symb? Verify, clean, and return
                   7401:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 7402: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 7403: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 7404: 	}
1.242     www      7405:     }
1.44      www      7406:     $thisfn=declutter($thisfn);
1.31      www      7407:     my %hash;
1.37      www      7408:     my %bighash;
                   7409:     my $syval='';
1.620     albertel 7410:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  7411:         my $targetfn = $thisfn;
1.609     banghart 7412:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  7413:             $targetfn = 'adm/wrapper/'.$thisfn;
                   7414:         }
1.687     albertel 7415: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   7416: 	    $targetfn=$1;
                   7417: 	}
1.620     albertel 7418:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 7419:                       &GDBM_READER(),0640)) {
1.481     raeburn  7420: 	    $syval=$hash{$targetfn};
1.37      www      7421:             untie(%hash);
                   7422:         }
                   7423: # ---------------------------------------------------------- There was an entry
                   7424:         if ($syval) {
1.601     albertel 7425: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 7426: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.601     albertel 7427: 		    #&appenv('request.ambiguous' => $thisfn);
1.620     albertel 7428: 		    #return $env{$cache_str}='';
1.601     albertel 7429: 		#}    
                   7430: 		#$syval.=$1;
                   7431: 	    #}
1.37      www      7432:         } else {
                   7433: # ------------------------------------------------------- Was not in symb table
1.620     albertel 7434:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 7435:                             &GDBM_READER(),0640)) {
1.37      www      7436: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      7437:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      7438:               unless ($ids) { 
                   7439:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      7440:               }
                   7441:               unless ($ids) {
                   7442: # alias?
                   7443: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      7444:               }
1.37      www      7445:               if ($ids) {
                   7446: # ------------------------------------------------------------------- Has ID(s)
                   7447:                  my @possibilities=split(/\,/,$ids);
1.39      www      7448:                  if ($#possibilities==0) {
                   7449: # ----------------------------------------------- There is only one possibility
1.37      www      7450: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 7451: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   7452: 						    $resid,$thisfn);
1.249     www      7453:                  } elsif (!$donotrecurse) {
1.39      www      7454: # ------------------------------------------ There is more than one possibility
                   7455:                      my $realpossible=0;
1.800     albertel 7456:                      foreach my $id (@possibilities) {
                   7457: 			 my $file=$bighash{'src_'.$id};
1.39      www      7458:                          if (&allowed('bre',$file)) {
1.800     albertel 7459:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      7460:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   7461: 				$realpossible++;
1.626     albertel 7462:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   7463: 						    $resid,$thisfn);
1.39      www      7464:                             }
                   7465: 			 }
1.191     harris41 7466:                      }
1.39      www      7467: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      7468:                  } else {
                   7469:                      $syval='';
1.37      www      7470:                  }
                   7471: 	      }
                   7472:               untie(%bighash)
1.481     raeburn  7473:            }
1.31      www      7474:         }
1.62      www      7475:         if ($syval) {
1.620     albertel 7476: 	    return $env{$cache_str}=$syval;
1.62      www      7477:         }
1.31      www      7478:     }
1.44      www      7479:     &appenv('request.ambiguous' => $thisfn);
1.620     albertel 7480:     return $env{$cache_str}='';
1.31      www      7481: }
                   7482: 
                   7483: # ---------------------------------------------------------- Return random seed
                   7484: 
1.32      www      7485: sub numval {
                   7486:     my $txt=shift;
                   7487:     $txt=~tr/A-J/0-9/;
                   7488:     $txt=~tr/a-j/0-9/;
                   7489:     $txt=~tr/K-T/0-9/;
                   7490:     $txt=~tr/k-t/0-9/;
                   7491:     $txt=~tr/U-Z/0-5/;
                   7492:     $txt=~tr/u-z/0-5/;
                   7493:     $txt=~s/\D//g;
1.564     albertel 7494:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      7495:     return int($txt);
1.368     albertel 7496: }
                   7497: 
1.484     albertel 7498: sub numval2 {
                   7499:     my $txt=shift;
                   7500:     $txt=~tr/A-J/0-9/;
                   7501:     $txt=~tr/a-j/0-9/;
                   7502:     $txt=~tr/K-T/0-9/;
                   7503:     $txt=~tr/k-t/0-9/;
                   7504:     $txt=~tr/U-Z/0-5/;
                   7505:     $txt=~tr/u-z/0-5/;
                   7506:     $txt=~s/\D//g;
                   7507:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7508:     my $total;
                   7509:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 7510:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 7511:     return int($total);
                   7512: }
                   7513: 
1.575     albertel 7514: sub numval3 {
                   7515:     use integer;
                   7516:     my $txt=shift;
                   7517:     $txt=~tr/A-J/0-9/;
                   7518:     $txt=~tr/a-j/0-9/;
                   7519:     $txt=~tr/K-T/0-9/;
                   7520:     $txt=~tr/k-t/0-9/;
                   7521:     $txt=~tr/U-Z/0-5/;
                   7522:     $txt=~tr/u-z/0-5/;
                   7523:     $txt=~s/\D//g;
                   7524:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   7525:     my $total;
                   7526:     foreach my $val (@txts) { $total+=$val; }
                   7527:     if ($_64bit) { $total=(($total<<32)>>32); }
                   7528:     return $total;
                   7529: }
                   7530: 
1.675     albertel 7531: sub digest {
                   7532:     my ($data)=@_;
                   7533:     my $digest=&Digest::MD5::md5($data);
                   7534:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   7535:     my ($e,$f);
                   7536:     {
                   7537:         use integer;
                   7538:         $e=($a+$b);
                   7539:         $f=($c+$d);
                   7540:         if ($_64bit) {
                   7541:             $e=(($e<<32)>>32);
                   7542:             $f=(($f<<32)>>32);
                   7543:         }
                   7544:     }
                   7545:     if (wantarray) {
                   7546: 	return ($e,$f);
                   7547:     } else {
                   7548: 	my $g;
                   7549: 	{
                   7550: 	    use integer;
                   7551: 	    $g=($e+$f);
                   7552: 	    if ($_64bit) {
                   7553: 		$g=(($g<<32)>>32);
                   7554: 	    }
                   7555: 	}
                   7556: 	return $g;
                   7557:     }
                   7558: }
                   7559: 
1.368     albertel 7560: sub latest_rnd_algorithm_id {
1.675     albertel 7561:     return '64bit5';
1.366     albertel 7562: }
1.32      www      7563: 
1.503     albertel 7564: sub get_rand_alg {
                   7565:     my ($courseid)=@_;
1.790     albertel 7566:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 7567:     if ($courseid) {
1.620     albertel 7568: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 7569:     }
                   7570:     return &latest_rnd_algorithm_id();
                   7571: }
                   7572: 
1.562     albertel 7573: sub validCODE {
                   7574:     my ($CODE)=@_;
                   7575:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   7576:     return 0;
                   7577: }
                   7578: 
1.491     albertel 7579: sub getCODE {
1.620     albertel 7580:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 7581:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   7582: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   7583: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 7584: 	return $Apache::lonhomework::history{'resource.CODE'};
                   7585:     }
                   7586:     return undef;
                   7587: }
                   7588: 
1.31      www      7589: sub rndseed {
1.155     albertel 7590:     my ($symb,$courseid,$domain,$username)=@_;
1.790     albertel 7591:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 7592:     if (!defined($symb)) {
1.366     albertel 7593: 	unless ($symb=$wsymb) { return time; }
                   7594:     }
                   7595:     if (!$courseid) { $courseid=$wcourseid; }
                   7596:     if (!$domain) { $domain=$wdomain; }
                   7597:     if (!$username) { $username=$wusername }
1.503     albertel 7598:     my $which=&get_rand_alg();
1.803     albertel 7599: 
1.491     albertel 7600:     if (defined(&getCODE())) {
1.675     albertel 7601: 	if ($which eq '64bit5') {
                   7602: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   7603: 	} elsif ($which eq '64bit4') {
1.575     albertel 7604: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   7605: 	} else {
                   7606: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   7607: 	}
1.675     albertel 7608:     } elsif ($which eq '64bit5') {
                   7609: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 7610:     } elsif ($which eq '64bit4') {
                   7611: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 7612:     } elsif ($which eq '64bit3') {
                   7613: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 7614:     } elsif ($which eq '64bit2') {
                   7615: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 7616:     } elsif ($which eq '64bit') {
                   7617: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   7618:     }
                   7619:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   7620: }
                   7621: 
                   7622: sub rndseed_32bit {
                   7623:     my ($symb,$courseid,$domain,$username)=@_;
                   7624:     {
                   7625: 	use integer;
                   7626: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   7627: 	my $symbseed=numval($symb) << 22;
                   7628: 	my $namechck=unpack("%32C*",$username) << 17;
                   7629: 	my $nameseed=numval($username) << 12;
                   7630: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   7631: 	my $courseseed=unpack("%32C*",$courseid);
                   7632: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 7633: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7634: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 7635: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 7636: 	return $num;
                   7637:     }
                   7638: }
                   7639: 
                   7640: sub rndseed_64bit {
                   7641:     my ($symb,$courseid,$domain,$username)=@_;
                   7642:     {
                   7643: 	use integer;
                   7644: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   7645: 	my $symbseed=numval($symb) << 10;
                   7646: 	my $namechck=unpack("%32S*",$username);
                   7647: 	
                   7648: 	my $nameseed=numval($username) << 21;
                   7649: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   7650: 	my $courseseed=unpack("%32S*",$courseid);
                   7651: 	
                   7652: 	my $num1=$symbchck+$symbseed+$namechck;
                   7653: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7654: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7655: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 7656: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 7657: 	return "$num1,$num2";
1.155     albertel 7658:     }
1.366     albertel 7659: }
                   7660: 
1.443     albertel 7661: sub rndseed_64bit2 {
                   7662:     my ($symb,$courseid,$domain,$username)=@_;
                   7663:     {
                   7664: 	use integer;
                   7665: 	# strings need to be an even # of cahracters long, it it is odd the
                   7666:         # last characters gets thrown away
                   7667: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7668: 	my $symbseed=numval($symb) << 10;
                   7669: 	my $namechck=unpack("%32S*",$username.' ');
                   7670: 	
                   7671: 	my $nameseed=numval($username) << 21;
1.501     albertel 7672: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7673: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7674: 	
                   7675: 	my $num1=$symbchck+$symbseed+$namechck;
                   7676: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7677: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7678: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 7679: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 7680: 	return "$num1,$num2";
                   7681:     }
                   7682: }
                   7683: 
                   7684: sub rndseed_64bit3 {
                   7685:     my ($symb,$courseid,$domain,$username)=@_;
                   7686:     {
                   7687: 	use integer;
                   7688: 	# strings need to be an even # of cahracters long, it it is odd the
                   7689:         # last characters gets thrown away
                   7690: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7691: 	my $symbseed=numval2($symb) << 10;
                   7692: 	my $namechck=unpack("%32S*",$username.' ');
                   7693: 	
                   7694: 	my $nameseed=numval2($username) << 21;
1.443     albertel 7695: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7696: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7697: 	
                   7698: 	my $num1=$symbchck+$symbseed+$namechck;
                   7699: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7700: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7701: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 7702: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   7703: 	
1.503     albertel 7704: 	return "$num1:$num2";
1.443     albertel 7705:     }
                   7706: }
                   7707: 
1.575     albertel 7708: sub rndseed_64bit4 {
                   7709:     my ($symb,$courseid,$domain,$username)=@_;
                   7710:     {
                   7711: 	use integer;
                   7712: 	# strings need to be an even # of cahracters long, it it is odd the
                   7713:         # last characters gets thrown away
                   7714: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7715: 	my $symbseed=numval3($symb) << 10;
                   7716: 	my $namechck=unpack("%32S*",$username.' ');
                   7717: 	
                   7718: 	my $nameseed=numval3($username) << 21;
                   7719: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7720: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7721: 	
                   7722: 	my $num1=$symbchck+$symbseed+$namechck;
                   7723: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7724: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7725: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 7726: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   7727: 	
                   7728: 	return "$num1:$num2";
                   7729:     }
                   7730: }
                   7731: 
1.675     albertel 7732: sub rndseed_64bit5 {
                   7733:     my ($symb,$courseid,$domain,$username)=@_;
                   7734:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   7735:     return "$num1:$num2";
                   7736: }
                   7737: 
1.366     albertel 7738: sub rndseed_CODE_64bit {
                   7739:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 7740:     {
1.366     albertel 7741: 	use integer;
1.443     albertel 7742: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 7743: 	my $symbseed=numval2($symb);
1.491     albertel 7744: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   7745: 	my $CODEseed=numval(&getCODE());
1.443     albertel 7746: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 7747: 	my $num1=$symbseed+$CODEchck;
                   7748: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 7749: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   7750: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 7751: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   7752: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 7753: 	return "$num1:$num2";
1.366     albertel 7754:     }
                   7755: }
                   7756: 
1.575     albertel 7757: sub rndseed_CODE_64bit4 {
                   7758:     my ($symb,$courseid,$domain,$username)=@_;
                   7759:     {
                   7760: 	use integer;
                   7761: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   7762: 	my $symbseed=numval3($symb);
                   7763: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   7764: 	my $CODEseed=numval3(&getCODE());
                   7765: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7766: 	my $num1=$symbseed+$CODEchck;
                   7767: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 7768: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   7769: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 7770: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   7771: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   7772: 	return "$num1:$num2";
                   7773:     }
                   7774: }
                   7775: 
1.675     albertel 7776: sub rndseed_CODE_64bit5 {
                   7777:     my ($symb,$courseid,$domain,$username)=@_;
                   7778:     my $code = &getCODE();
                   7779:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   7780:     return "$num1:$num2";
                   7781: }
                   7782: 
1.366     albertel 7783: sub setup_random_from_rndseed {
                   7784:     my ($rndseed)=@_;
1.503     albertel 7785:     if ($rndseed =~/([,:])/) {
                   7786: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 7787: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   7788:     } else {
                   7789: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 7790:     }
1.36      albertel 7791: }
                   7792: 
1.474     albertel 7793: sub latest_receipt_algorithm_id {
1.835     albertel 7794:     return 'receipt3';
1.474     albertel 7795: }
                   7796: 
1.480     www      7797: sub recunique {
                   7798:     my $fucourseid=shift;
                   7799:     my $unique;
1.835     albertel 7800:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   7801: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 7802: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      7803:     } else {
                   7804: 	$unique=$perlvar{'lonReceipt'};
                   7805:     }
                   7806:     return unpack("%32C*",$unique);
                   7807: }
                   7808: 
                   7809: sub recprefix {
                   7810:     my $fucourseid=shift;
                   7811:     my $prefix;
1.835     albertel 7812:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   7813: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 7814: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      7815:     } else {
                   7816: 	$prefix=$perlvar{'lonHostID'};
                   7817:     }
                   7818:     return unpack("%32C*",$prefix);
                   7819: }
                   7820: 
1.76      www      7821: sub ireceipt {
1.474     albertel 7822:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 7823: 
                   7824:     my $return =&recprefix($fucourseid).'-';
                   7825: 
                   7826:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   7827: 	$env{'request.state'} eq 'construct') {
                   7828: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   7829: 	return $return;
                   7830:     }
                   7831: 
1.76      www      7832:     my $cuname=unpack("%32C*",$funame);
                   7833:     my $cudom=unpack("%32C*",$fudom);
                   7834:     my $cucourseid=unpack("%32C*",$fucourseid);
                   7835:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      7836:     my $cunique=&recunique($fucourseid);
1.474     albertel 7837:     my $cpart=unpack("%32S*",$part);
1.835     albertel 7838:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   7839: 
1.790     albertel 7840: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 7841: 			       
                   7842: 	$return.= ($cunique%$cuname+
                   7843: 		   $cunique%$cudom+
                   7844: 		   $cusymb%$cuname+
                   7845: 		   $cusymb%$cudom+
                   7846: 		   $cucourseid%$cuname+
                   7847: 		   $cucourseid%$cudom+
                   7848: 		   $cpart%$cuname+
                   7849: 		   $cpart%$cudom);
                   7850:     } else {
                   7851: 	$return.= ($cunique%$cuname+
                   7852: 		   $cunique%$cudom+
                   7853: 		   $cusymb%$cuname+
                   7854: 		   $cusymb%$cudom+
                   7855: 		   $cucourseid%$cuname+
                   7856: 		   $cucourseid%$cudom);
                   7857:     }
                   7858:     return $return;
1.76      www      7859: }
                   7860: 
                   7861: sub receipt {
1.474     albertel 7862:     my ($part)=@_;
1.790     albertel 7863:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 7864:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      7865: }
1.260     ng       7866: 
1.790     albertel 7867: sub whichuser {
                   7868:     my ($passedsymb)=@_;
                   7869:     my ($symb,$courseid,$domain,$name,$publicuser);
                   7870:     if (defined($env{'form.grade_symb'})) {
                   7871: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   7872: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   7873: 	if (!$allowed &&
                   7874: 	    exists($env{'request.course.sec'}) &&
                   7875: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   7876: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   7877: 			      '/'.$env{'request.course.sec'});
                   7878: 	}
                   7879: 	if ($allowed) {
                   7880: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   7881: 	    $courseid=$tmp_courseid;
                   7882: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   7883: 	    ($name)=&get_env_multiple('form.grade_username');
                   7884: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   7885: 	}
                   7886:     }
                   7887:     if (!$passedsymb) {
                   7888: 	$symb=&symbread();
                   7889:     } else {
                   7890: 	$symb=$passedsymb;
                   7891:     }
                   7892:     $courseid=$env{'request.course.id'};
                   7893:     $domain=$env{'user.domain'};
                   7894:     $name=$env{'user.name'};
                   7895:     if ($name eq 'public' && $domain eq 'public') {
                   7896: 	if (!defined($env{'form.username'})) {
                   7897: 	    $env{'form.username'}.=time.rand(10000000);
                   7898: 	}
                   7899: 	$name.=$env{'form.username'};
                   7900:     }
                   7901:     return ($symb,$courseid,$domain,$name,$publicuser);
                   7902: 
                   7903: }
                   7904: 
1.36      albertel 7905: # ------------------------------------------------------------ Serves up a file
1.472     albertel 7906: # returns either the contents of the file or 
                   7907: # -1 if the file doesn't exist
1.481     raeburn  7908: #
                   7909: # if the target is a file that was uploaded via DOCS, 
                   7910: # a check will be made to see if a current copy exists on the local server,
                   7911: # if it does this will be served, otherwise a copy will be retrieved from
                   7912: # the home server for the course and stored in /home/httpd/html/userfiles on
                   7913: # the local server.   
1.472     albertel 7914: 
1.36      albertel 7915: sub getfile {
1.538     albertel 7916:     my ($file) = @_;
1.609     banghart 7917:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 7918:     &repcopy($file);
                   7919:     return &readfile($file);
                   7920: }
                   7921: 
                   7922: sub repcopy_userfile {
                   7923:     my ($file)=@_;
1.609     banghart 7924:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 7925:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 7926:     my ($cdom,$cnum,$filename) = 
1.811     albertel 7927: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 7928:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   7929:     if (-e "$file") {
1.828     www      7930: # we already have a local copy, check it out
1.538     albertel 7931: 	my @fileinfo = stat($file);
1.828     www      7932: 	my $rtncode;
                   7933: 	my $info;
1.538     albertel 7934: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 7935: 	if ($lwpresp ne 'ok') {
1.828     www      7936: # there is no such file anymore, even though we had a local copy
1.482     albertel 7937: 	    if ($rtncode eq '404') {
1.538     albertel 7938: 		unlink($file);
1.482     albertel 7939: 	    }
                   7940: 	    return -1;
                   7941: 	}
                   7942: 	if ($info < $fileinfo[9]) {
1.828     www      7943: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  7944: 	    return 'ok';
1.828     www      7945: 	} else {
                   7946: # the file is outdated, get rid of it
                   7947: 	    unlink($file);
1.482     albertel 7948: 	}
1.828     www      7949:     }
                   7950: # one way or the other, at this point, we don't have the file
                   7951: # construct the correct path for the file
                   7952:     my @parts = ($cdom,$cnum); 
                   7953:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   7954: 	push @parts, split(/\//,$1);
                   7955:     }
                   7956:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   7957:     foreach my $part (@parts) {
                   7958: 	$path .= '/'.$part;
                   7959: 	if (!-e $path) {
                   7960: 	    mkdir($path,0770);
1.482     albertel 7961: 	}
                   7962:     }
1.828     www      7963: # now the path exists for sure
                   7964: # get a user agent
                   7965:     my $ua=new LWP::UserAgent;
                   7966:     my $transferfile=$file.'.in.transfer';
                   7967: # FIXME: this should flock
                   7968:     if (-e $transferfile) { return 'ok'; }
                   7969:     my $request;
                   7970:     $uri=~s/^\///;
1.838     albertel 7971:     $request=new HTTP::Request('GET','http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri);
1.828     www      7972:     my $response=$ua->request($request,$transferfile);
                   7973: # did it work?
                   7974:     if ($response->is_error()) {
                   7975: 	unlink($transferfile);
                   7976: 	&logthis("Userfile repcopy failed for $uri");
                   7977: 	return -1;
                   7978:     }
                   7979: # worked, rename the transfer file
                   7980:     rename($transferfile,$file);
1.607     raeburn  7981:     return 'ok';
1.481     raeburn  7982: }
                   7983: 
1.517     albertel 7984: sub tokenwrapper {
                   7985:     my $uri=shift;
1.552     albertel 7986:     $uri=~s|^http\://([^/]+)||;
                   7987:     $uri=~s|^/||;
1.620     albertel 7988:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 7989:     my $token=$1;
1.552     albertel 7990:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   7991:     if ($udom && $uname && $file) {
                   7992: 	$file=~s|(\?\.*)*$||;
1.620     albertel 7993:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
1.838     albertel 7994:         return 'http://'.&hostname(&homeserver($uname,$udom)).'/'.$uri.
1.517     albertel 7995:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   7996:                                '&tokenissued='.$perlvar{'lonHostID'};
                   7997:     } else {
                   7998:         return '/adm/notfound.html';
                   7999:     }
                   8000: }
                   8001: 
1.828     www      8002: # call with reqtype HEAD: get last modification time
                   8003: # call with reqtype GET: get the file contents
                   8004: # Do not call this with reqtype GET for large files! It loads everything into memory
                   8005: #
1.481     raeburn  8006: sub getuploaded {
                   8007:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   8008:     $uri=~s/^\///;
1.838     albertel 8009:     $uri = 'http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri;
1.481     raeburn  8010:     my $ua=new LWP::UserAgent;
                   8011:     my $request=new HTTP::Request($reqtype,$uri);
                   8012:     my $response=$ua->request($request);
                   8013:     $$rtncode = $response->code;
1.482     albertel 8014:     if (! $response->is_success()) {
                   8015: 	return 'failed';
                   8016:     }      
                   8017:     if ($reqtype eq 'HEAD') {
1.486     www      8018: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 8019:     } elsif ($reqtype eq 'GET') {
                   8020: 	$$info = $response->content;
1.472     albertel 8021:     }
1.482     albertel 8022:     return 'ok';
1.36      albertel 8023: }
                   8024: 
1.481     raeburn  8025: sub readfile {
                   8026:     my $file = shift;
                   8027:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   8028:     my $fh;
                   8029:     open($fh,"<$file");
                   8030:     my $a='';
1.800     albertel 8031:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  8032:     return $a;
                   8033: }
                   8034: 
1.36      albertel 8035: sub filelocation {
1.590     banghart 8036:     my ($dir,$file) = @_;
                   8037:     my $location;
                   8038:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 8039: 
                   8040:     if ($file =~ m-^/adm/-) {
                   8041: 	$file=~s-^/adm/wrapper/-/-;
                   8042: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   8043:     }
1.882     albertel 8044: 
1.590     banghart 8045:     if ($file=~m:^/~:) { # is a contruction space reference
                   8046:         $location = $file;
                   8047:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 8048:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 8049: 	# is a correct contruction space reference
                   8050:         $location = $file;
1.609     banghart 8051:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 8052:         my ($udom,$uname,$filename)=
1.811     albertel 8053:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 8054:         my $home=&homeserver($uname,$udom);
                   8055:         my $is_me=0;
                   8056:         my @ids=&current_machine_ids();
                   8057:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   8058:         if ($is_me) {
1.740     www      8059:   	    $location=&propath($udom,$uname).
1.590     banghart 8060:   	      '/userfiles/'.$filename;
                   8061:         } else {
                   8062:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   8063:   	      $udom.'/'.$uname.'/'.$filename;
                   8064:         }
1.882     albertel 8065:     } elsif ($file =~ m-^/adm/-) {
                   8066: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 8067:     } else {
                   8068:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   8069:         $file=~s:^/res/:/:;
                   8070:         if ( !( $file =~ m:^/:) ) {
                   8071:             $location = $dir. '/'.$file;
                   8072:         } else {
                   8073:             $location = '/home/httpd/html/res'.$file;
                   8074:         }
1.59      albertel 8075:     }
1.590     banghart 8076:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 8077:     while ($location=~m{/\.\./}) {
                   8078: 	if ($location =~ m{/[^/]+/\.\./}) {
                   8079: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   8080: 	} else {
                   8081: 	    $location=~ s{/\.\./}{/}g;
                   8082: 	}
                   8083:     } #remove dir/..
1.590     banghart 8084:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   8085:     return $location;
1.46      www      8086: }
1.36      albertel 8087: 
1.46      www      8088: sub hreflocation {
                   8089:     my ($dir,$file)=@_;
1.460     albertel 8090:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666     albertel 8091: 	$file=filelocation($dir,$file);
1.700     albertel 8092:     } elsif ($file=~m-^/adm/-) {
                   8093: 	$file=~s-^/adm/wrapper/-/-;
                   8094: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 8095:     }
                   8096:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   8097: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 8098:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   8099: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 8100:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 8101: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 8102: 	    -/uploaded/$1/$2/-x;
1.46      www      8103:     }
1.913     albertel 8104:     if ($file=~ m{^/userfiles/}) {
                   8105: 	$file =~ s{^/userfiles/}{/uploaded/};
                   8106:     }
1.462     albertel 8107:     return $file;
1.465     albertel 8108: }
                   8109: 
                   8110: sub current_machine_domains {
1.853     albertel 8111:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   8112: }
                   8113: 
                   8114: sub machine_domains {
                   8115:     my ($hostname) = @_;
1.465     albertel 8116:     my @domains;
1.838     albertel 8117:     my %hostname = &all_hostnames();
1.465     albertel 8118:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  8119: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 8120: 	if ($hostname eq $name) {
1.844     albertel 8121: 	    push(@domains,&host_domain($id));
1.465     albertel 8122: 	}
                   8123:     }
                   8124:     return @domains;
                   8125: }
                   8126: 
                   8127: sub current_machine_ids {
1.853     albertel 8128:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   8129: }
                   8130: 
                   8131: sub machine_ids {
                   8132:     my ($hostname) = @_;
                   8133:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 8134:     my @ids;
1.888     albertel 8135:     my %name_to_host = &all_names();
1.889     albertel 8136:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   8137: 	return @{ $name_to_host{$hostname} };
                   8138:     }
                   8139:     return;
1.31      www      8140: }
                   8141: 
1.824     raeburn  8142: sub additional_machine_domains {
                   8143:     my @domains;
                   8144:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   8145:     while( my $line = <$fh>) {
                   8146:         $line =~ s/\s//g;
                   8147:         push(@domains,$line);
                   8148:     }
                   8149:     return @domains;
                   8150: }
                   8151: 
                   8152: sub default_login_domain {
                   8153:     my $domain = $perlvar{'lonDefDomain'};
                   8154:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   8155:     foreach my $posdom (&current_machine_domains(),
                   8156:                         &additional_machine_domains()) {
                   8157:         if (lc($posdom) eq lc($testdomain)) {
                   8158:             $domain=$posdom;
                   8159:             last;
                   8160:         }
                   8161:     }
                   8162:     return $domain;
                   8163: }
                   8164: 
1.31      www      8165: # ------------------------------------------------------------- Declutters URLs
                   8166: 
                   8167: sub declutter {
                   8168:     my $thisfn=shift;
1.569     albertel 8169:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 8170:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      8171:     $thisfn=~s/^\///;
1.697     albertel 8172:     $thisfn=~s|^adm/wrapper/||;
                   8173:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      8174:     $thisfn=~s/^res\///;
1.235     www      8175:     $thisfn=~s/\?.+$//;
1.268     www      8176:     return $thisfn;
                   8177: }
                   8178: 
                   8179: # ------------------------------------------------------------- Clutter up URLs
                   8180: 
                   8181: sub clutter {
                   8182:     my $thisfn='/'.&declutter(shift);
1.887     albertel 8183:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 8184: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      8185:        $thisfn='/res'.$thisfn; 
                   8186:     }
1.694     albertel 8187:     if ($thisfn !~m|/adm|) {
1.695     albertel 8188: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 8189: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 8190: 	} else {
                   8191: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   8192: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 8193: 	    if ($embstyle eq 'ssi'
                   8194: 		|| ($embstyle eq 'hdn')
                   8195: 		|| ($embstyle eq 'rat')
                   8196: 		|| ($embstyle eq 'prv')
                   8197: 		|| ($embstyle eq 'ign')) {
                   8198: 		#do nothing with these
                   8199: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 8200: 		|| ($embstyle eq 'emb')
                   8201: 		|| ($embstyle eq 'wrp')) {
                   8202: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 8203: 	    } elsif ($embstyle eq 'unk'
                   8204: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 8205: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 8206: 	    } else {
1.718     www      8207: #		&logthis("Got a blank emb style");
1.695     albertel 8208: 	    }
1.694     albertel 8209: 	}
                   8210:     }
1.31      www      8211:     return $thisfn;
1.12      www      8212: }
                   8213: 
1.787     albertel 8214: sub clutter_with_no_wrapper {
                   8215:     my $uri = &clutter(shift);
                   8216:     if ($uri =~ m-^/adm/-) {
                   8217: 	$uri =~ s-^/adm/wrapper/-/-;
                   8218: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   8219:     }
                   8220:     return $uri;
                   8221: }
                   8222: 
1.557     albertel 8223: sub freeze_escape {
                   8224:     my ($value)=@_;
                   8225:     if (ref($value)) {
                   8226: 	$value=&nfreeze($value);
                   8227: 	return '__FROZEN__'.&escape($value);
                   8228:     }
                   8229:     return &escape($value);
                   8230: }
                   8231: 
1.11      www      8232: 
1.557     albertel 8233: sub thaw_unescape {
                   8234:     my ($value)=@_;
                   8235:     if ($value =~ /^__FROZEN__/) {
                   8236: 	substr($value,0,10,undef);
                   8237: 	$value=&unescape($value);
                   8238: 	return &thaw($value);
                   8239:     }
                   8240:     return &unescape($value);
                   8241: }
                   8242: 
1.436     albertel 8243: sub correct_line_ends {
                   8244:     my ($result)=@_;
                   8245:     $$result =~s/\r\n/\n/mg;
                   8246:     $$result =~s/\r/\n/mg;
1.415     albertel 8247: }
1.1       albertel 8248: # ================================================================ Main Program
                   8249: 
1.184     www      8250: sub goodbye {
1.204     albertel 8251:    &logthis("Starting Shut down");
1.443     albertel 8252: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 8253:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 8254: #converted
1.599     albertel 8255: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 8256:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   8257: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   8258: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 8259: #1.1 only
1.870     albertel 8260: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   8261: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   8262: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   8263: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   8264:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 8265:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   8266:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      8267:    &flushcourselogs();
                   8268:    &logthis("Shutting down");
                   8269: }
                   8270: 
1.852     albertel 8271: sub get_dns {
1.869     albertel 8272:     my ($url,$func,$ignore_cache) = @_;
                   8273:     if (!$ignore_cache) {
                   8274: 	my ($content,$cached)=
                   8275: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   8276: 	if ($cached) {
                   8277: 	    &$func($content);
                   8278: 	    return;
                   8279: 	}
                   8280:     }
                   8281: 
                   8282:     my %alldns;
1.852     albertel 8283:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   8284:     foreach my $dns (<$config>) {
                   8285: 	next if ($dns !~ /^\^(\S*)/x);
1.869     albertel 8286: 	$alldns{$1} = 1;
                   8287:     }
                   8288:     while (%alldns) {
                   8289: 	my ($dns) = keys(%alldns);
                   8290: 	delete($alldns{$dns});
1.852     albertel 8291: 	my $ua=new LWP::UserAgent;
                   8292: 	my $request=new HTTP::Request('GET',"http://$dns$url");
                   8293: 	my $response=$ua->request($request);
                   8294: 	next if ($response->is_error());
                   8295: 	my @content = split("\n",$response->content);
1.869     albertel 8296: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 8297: 	&$func(\@content);
1.869     albertel 8298: 	return;
1.852     albertel 8299:     }
                   8300:     close($config);
1.871     albertel 8301:     my $which = (split('/',$url))[3];
                   8302:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   8303:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 8304:     my @content = <$config>;
                   8305:     &$func(\@content);
                   8306:     return;
1.852     albertel 8307: }
1.327     albertel 8308: # ------------------------------------------------------------ Read domain file
                   8309: {
1.852     albertel 8310:     my $loaded;
1.846     albertel 8311:     my %domain;
                   8312: 
1.852     albertel 8313:     sub parse_domain_tab {
                   8314: 	my ($lines) = @_;
                   8315: 	foreach my $line (@$lines) {
                   8316: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      8317: 
1.846     albertel 8318: 	    chomp($line);
1.852     albertel 8319: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 8320: 	    my %this_domain;
                   8321: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   8322: 			       'lang_def', 'city', 'longi', 'lati',
                   8323: 			       'primary') {
                   8324: 		$this_domain{$field} = shift(@elements);
                   8325: 	    }
                   8326: 	    $domain{$name} = \%this_domain;
1.852     albertel 8327: 	}
                   8328:     }
1.864     albertel 8329: 
                   8330:     sub reset_domain_info {
                   8331: 	undef($loaded);
                   8332: 	undef(%domain);
                   8333:     }
                   8334: 
1.852     albertel 8335:     sub load_domain_tab {
1.869     albertel 8336: 	my ($ignore_cache) = @_;
                   8337: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 8338: 	my $fh;
                   8339: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   8340: 	    my @lines = <$fh>;
                   8341: 	    &parse_domain_tab(\@lines);
1.448     albertel 8342: 	}
1.852     albertel 8343: 	close($fh);
                   8344: 	$loaded = 1;
1.327     albertel 8345:     }
1.846     albertel 8346: 
                   8347:     sub domain {
1.852     albertel 8348: 	&load_domain_tab() if (!$loaded);
                   8349: 
1.846     albertel 8350: 	my ($name,$what) = @_;
                   8351: 	return if ( !exists($domain{$name}) );
                   8352: 
                   8353: 	if (!$what) {
                   8354: 	    return $domain{$name}{'description'};
                   8355: 	}
                   8356: 	return $domain{$name}{$what};
                   8357:     }
1.327     albertel 8358: }
                   8359: 
                   8360: 
1.1       albertel 8361: # ------------------------------------------------------------- Read hosts file
                   8362: {
1.838     albertel 8363:     my %hostname;
1.844     albertel 8364:     my %hostdom;
1.845     albertel 8365:     my %libserv;
1.852     albertel 8366:     my $loaded;
1.888     albertel 8367:     my %name_to_host;
1.852     albertel 8368: 
                   8369:     sub parse_hosts_tab {
                   8370: 	my ($file) = @_;
                   8371: 	foreach my $configline (@$file) {
                   8372: 	    next if ($configline =~ /^(\#|\s*$ )/x);
                   8373: 	    next if ($configline =~ /^\^/);
                   8374: 	    chomp($configline);
                   8375: 	    my ($id,$domain,$role,$name)=split(/:/,$configline);
                   8376: 	    $name=~s/\s//g;
                   8377: 	    if ($id && $domain && $role && $name) {
                   8378: 		$hostname{$id}=$name;
1.888     albertel 8379: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 8380: 		$hostdom{$id}=$domain;
                   8381: 		if ($role eq 'library') { $libserv{$id}=$name; }
                   8382: 	    }
                   8383: 	}
                   8384:     }
1.864     albertel 8385:     
                   8386:     sub reset_hosts_info {
1.897     albertel 8387: 	&purge_remembered();
1.864     albertel 8388: 	&reset_domain_info();
                   8389: 	&reset_hosts_ip_info();
1.892     albertel 8390: 	undef(%name_to_host);
1.864     albertel 8391: 	undef(%hostname);
                   8392: 	undef(%hostdom);
                   8393: 	undef(%libserv);
                   8394: 	undef($loaded);
                   8395:     }
1.1       albertel 8396: 
1.852     albertel 8397:     sub load_hosts_tab {
1.869     albertel 8398: 	my ($ignore_cache) = @_;
                   8399: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 8400: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   8401: 	my @config = <$config>;
                   8402: 	&parse_hosts_tab(\@config);
                   8403: 	close($config);
                   8404: 	$loaded=1;
1.1       albertel 8405:     }
1.852     albertel 8406: 
1.838     albertel 8407:     sub hostname {
1.852     albertel 8408: 	&load_hosts_tab() if (!$loaded);
                   8409: 
1.838     albertel 8410: 	my ($lonid) = @_;
                   8411: 	return $hostname{$lonid};
                   8412:     }
1.845     albertel 8413: 
1.838     albertel 8414:     sub all_hostnames {
1.852     albertel 8415: 	&load_hosts_tab() if (!$loaded);
                   8416: 
1.838     albertel 8417: 	return %hostname;
                   8418:     }
1.845     albertel 8419: 
1.888     albertel 8420:     sub all_names {
                   8421: 	&load_hosts_tab() if (!$loaded);
                   8422: 
                   8423: 	return %name_to_host;
                   8424:     }
                   8425: 
1.845     albertel 8426:     sub is_library {
1.852     albertel 8427: 	&load_hosts_tab() if (!$loaded);
                   8428: 
1.845     albertel 8429: 	return exists($libserv{$_[0]});
                   8430:     }
                   8431: 
                   8432:     sub all_library {
1.852     albertel 8433: 	&load_hosts_tab() if (!$loaded);
                   8434: 
1.845     albertel 8435: 	return %libserv;
                   8436:     }
                   8437: 
1.841     albertel 8438:     sub get_servers {
1.852     albertel 8439: 	&load_hosts_tab() if (!$loaded);
                   8440: 
1.841     albertel 8441: 	my ($domain,$type) = @_;
                   8442: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   8443: 	                                          : %hostname;
                   8444: 	my %result;
1.842     albertel 8445: 	if (ref($domain) eq 'ARRAY') {
                   8446: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 8447: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 8448: 		    $result{$host} = $hostname;
                   8449: 		}
                   8450: 	    }
                   8451: 	} else {
                   8452: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   8453: 		if ($hostdom{$host} eq $domain) {
                   8454: 		    $result{$host} = $hostname;
                   8455: 		}
1.841     albertel 8456: 	    }
                   8457: 	}
                   8458: 	return %result;
                   8459:     }
1.845     albertel 8460: 
1.844     albertel 8461:     sub host_domain {
1.852     albertel 8462: 	&load_hosts_tab() if (!$loaded);
                   8463: 
1.844     albertel 8464: 	my ($lonid) = @_;
                   8465: 	return $hostdom{$lonid};
                   8466:     }
                   8467: 
1.841     albertel 8468:     sub all_domains {
1.852     albertel 8469: 	&load_hosts_tab() if (!$loaded);
                   8470: 
1.841     albertel 8471: 	my %seen;
                   8472: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   8473: 	return @uniq;
                   8474:     }
1.1       albertel 8475: }
                   8476: 
1.847     albertel 8477: { 
                   8478:     my %iphost;
1.856     albertel 8479:     my %name_to_ip;
                   8480:     my %lonid_to_ip;
1.869     albertel 8481: 
1.847     albertel 8482:     sub get_hosts_from_ip {
                   8483: 	my ($ip) = @_;
                   8484: 	my %iphosts = &get_iphost();
                   8485: 	if (ref($iphosts{$ip})) {
                   8486: 	    return @{$iphosts{$ip}};
                   8487: 	}
                   8488: 	return;
1.839     albertel 8489:     }
1.864     albertel 8490:     
                   8491:     sub reset_hosts_ip_info {
                   8492: 	undef(%iphost);
                   8493: 	undef(%name_to_ip);
                   8494: 	undef(%lonid_to_ip);
                   8495:     }
1.856     albertel 8496: 
                   8497:     sub get_host_ip {
                   8498: 	my ($lonid) = @_;
                   8499: 	if (exists($lonid_to_ip{$lonid})) {
                   8500: 	    return $lonid_to_ip{$lonid};
                   8501: 	}
                   8502: 	my $name=&hostname($lonid);
                   8503:    	my $ip = gethostbyname($name);
                   8504: 	return if (!$ip || length($ip) ne 4);
                   8505: 	$ip=inet_ntoa($ip);
                   8506: 	$name_to_ip{$name}   = $ip;
                   8507: 	$lonid_to_ip{$lonid} = $ip;
                   8508: 	return $ip;
                   8509:     }
1.847     albertel 8510:     
                   8511:     sub get_iphost {
1.869     albertel 8512: 	my ($ignore_cache) = @_;
1.894     albertel 8513: 
1.869     albertel 8514: 	if (!$ignore_cache) {
                   8515: 	    if (%iphost) {
                   8516: 		return %iphost;
                   8517: 	    }
                   8518: 	    my ($ip_info,$cached)=
                   8519: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   8520: 	    if ($cached) {
                   8521: 		%iphost      = %{$ip_info->[0]};
                   8522: 		%name_to_ip  = %{$ip_info->[1]};
                   8523: 		%lonid_to_ip = %{$ip_info->[2]};
                   8524: 		return %iphost;
                   8525: 	    }
                   8526: 	}
1.894     albertel 8527: 
                   8528: 	# get yesterday's info for fallback
                   8529: 	my %old_name_to_ip;
                   8530: 	my ($ip_info,$cached)=
                   8531: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   8532: 	if ($cached) {
                   8533: 	    %old_name_to_ip = %{$ip_info->[1]};
                   8534: 	}
                   8535: 
1.888     albertel 8536: 	my %name_to_host = &all_names();
                   8537: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 8538: 	    my $ip;
                   8539: 	    if (!exists($name_to_ip{$name})) {
                   8540: 		$ip = gethostbyname($name);
                   8541: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 8542: 		    if (defined($old_name_to_ip{$name})) {
                   8543: 			$ip = $old_name_to_ip{$name};
                   8544: 			&logthis("Can't find $name defaulting to old $ip");
                   8545: 		    } else {
                   8546: 			&logthis("Name $name no IP found");
                   8547: 			next;
                   8548: 		    }
                   8549: 		} else {
                   8550: 		    $ip=inet_ntoa($ip);
1.847     albertel 8551: 		}
                   8552: 		$name_to_ip{$name} = $ip;
                   8553: 	    } else {
                   8554: 		$ip = $name_to_ip{$name};
1.653     albertel 8555: 	    }
1.888     albertel 8556: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   8557: 		$lonid_to_ip{$id} = $ip;
                   8558: 	    }
                   8559: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 8560: 	}
1.869     albertel 8561: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   8562: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 8563: 				      48*60*60);
1.869     albertel 8564: 
1.847     albertel 8565: 	return %iphost;
1.598     albertel 8566:     }
                   8567: }
                   8568: 
1.862     albertel 8569: BEGIN {
                   8570: 
                   8571: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   8572:     unless ($readit) {
                   8573: {
                   8574:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   8575:     %perlvar = (%perlvar,%{$configvars});
                   8576: }
                   8577: 
                   8578: 
1.1       albertel 8579: # ------------------------------------------------------ Read spare server file
                   8580: {
1.448     albertel 8581:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 8582: 
                   8583:     while (my $configline=<$config>) {
                   8584:        chomp($configline);
1.284     matthew  8585:        if ($configline) {
1.784     albertel 8586: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 8587: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 8588: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 8589:        }
                   8590:     }
1.448     albertel 8591:     close($config);
1.1       albertel 8592: }
1.11      www      8593: # ------------------------------------------------------------ Read permissions
                   8594: {
1.448     albertel 8595:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      8596: 
                   8597:     while (my $configline=<$config>) {
1.448     albertel 8598: 	chomp($configline);
                   8599: 	if ($configline) {
                   8600: 	    my ($role,$perm)=split(/ /,$configline);
                   8601: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   8602: 	}
1.11      www      8603:     }
1.448     albertel 8604:     close($config);
1.11      www      8605: }
                   8606: 
                   8607: # -------------------------------------------- Read plain texts for permissions
                   8608: {
1.448     albertel 8609:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      8610: 
                   8611:     while (my $configline=<$config>) {
1.448     albertel 8612: 	chomp($configline);
                   8613: 	if ($configline) {
1.742     raeburn  8614: 	    my ($short,@plain)=split(/:/,$configline);
                   8615:             %{$prp{$short}} = ();
                   8616: 	    if (@plain > 0) {
                   8617:                 $prp{$short}{'std'} = $plain[0];
                   8618:                 for (my $i=1; $i<@plain; $i++) {
                   8619:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   8620:                 }
                   8621:             }
1.448     albertel 8622: 	}
1.135     www      8623:     }
1.448     albertel 8624:     close($config);
1.135     www      8625: }
                   8626: 
                   8627: # ---------------------------------------------------------- Read package table
                   8628: {
1.448     albertel 8629:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      8630: 
                   8631:     while (my $configline=<$config>) {
1.483     albertel 8632: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 8633: 	chomp($configline);
                   8634: 	my ($short,$plain)=split(/:/,$configline);
                   8635: 	my ($pack,$name)=split(/\&/,$short);
                   8636: 	if ($plain ne '') {
                   8637: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   8638: 	    $packagetab{$short}=$plain; 
                   8639: 	}
1.11      www      8640:     }
1.448     albertel 8641:     close($config);
1.329     matthew  8642: }
                   8643: 
                   8644: # ------------- set up temporary directory
                   8645: {
                   8646:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   8647: 
1.11      www      8648: }
                   8649: 
1.794     albertel 8650: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   8651: 				'compress_threshold'=> 20_000,
                   8652:  			        });
1.185     www      8653: 
1.281     www      8654: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      8655: $dumpcount=0;
1.22      www      8656: 
1.163     harris41 8657: &logtouch();
1.672     albertel 8658: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      8659: $readit=1;
1.564     albertel 8660:     {
                   8661: 	use integer;
                   8662: 	my $test=(2**32)+1;
1.568     albertel 8663: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 8664: 	&logthis(" Detected 64bit platform ($_64bit)");
                   8665:     }
1.195     www      8666: }
1.1       albertel 8667: }
1.179     www      8668: 
1.1       albertel 8669: 1;
1.191     harris41 8670: __END__
                   8671: 
1.243     albertel 8672: =pod
                   8673: 
1.191     harris41 8674: =head1 NAME
                   8675: 
1.243     albertel 8676: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 8677: 
                   8678: =head1 SYNOPSIS
                   8679: 
1.243     albertel 8680: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 8681: 
                   8682:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   8683: 
1.243     albertel 8684: Common parameters:
                   8685: 
                   8686: =over 4
                   8687: 
                   8688: =item *
                   8689: 
                   8690: $uname : an internal username (if $cname expecting a course Id specifically)
                   8691: 
                   8692: =item *
                   8693: 
                   8694: $udom : a domain (if $cdom expecting a course's domain specifically)
                   8695: 
                   8696: =item *
                   8697: 
                   8698: $symb : a resource instance identifier
                   8699: 
                   8700: =item *
                   8701: 
                   8702: $namespace : the name of a .db file that contains the data needed or
                   8703: being set.
                   8704: 
                   8705: =back
                   8706: 
1.394     bowersj2 8707: =head1 OVERVIEW
1.191     harris41 8708: 
1.394     bowersj2 8709: lonnet provides subroutines which interact with the
                   8710: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   8711: about classes, users, and resources.
1.243     albertel 8712: 
                   8713: For many of these objects you can also use this to store data about
                   8714: them or modify them in various ways.
1.191     harris41 8715: 
1.394     bowersj2 8716: =head2 Symbs
1.191     harris41 8717: 
1.394     bowersj2 8718: To identify a specific instance of a resource, LON-CAPA uses symbols
                   8719: or "symbs"X<symb>. These identifiers are built from the URL of the
                   8720: map, the resource number of the resource in the map, and the URL of
                   8721: the resource itself. The latter is somewhat redundant, but might help
                   8722: if maps change.
                   8723: 
                   8724: An example is
                   8725: 
                   8726:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   8727: 
                   8728: The respective map entry is
                   8729: 
                   8730:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   8731:   title="Problem 2">
                   8732:  </resource>
                   8733: 
                   8734: Symbs are used by the random number generator, as well as to store and
                   8735: restore data specific to a certain instance of for example a problem.
                   8736: 
                   8737: =head2 Storing And Retrieving Data
                   8738: 
                   8739: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   8740: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   8741: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   8742: is is the non-critical message twin of cstore. These functions are for
                   8743: handlers to store a perl hash to a user's permanent data space in an
                   8744: easy manner, and to retrieve it again on another call. It is expected
                   8745: that a handler would use this once at the beginning to retrieve data,
                   8746: and then again once at the end to send only the new data back.
                   8747: 
                   8748: The data is stored in the user's data directory on the user's
                   8749: homeserver under the ID of the course.
                   8750: 
                   8751: The hash that is returned by restore will have all of the previous
                   8752: value for all of the elements of the hash.
                   8753: 
                   8754: Example:
                   8755: 
                   8756:  #creating a hash
                   8757:  my %hash;
                   8758:  $hash{'foo'}='bar';
                   8759: 
                   8760:  #storing it
                   8761:  &Apache::lonnet::cstore(\%hash);
                   8762: 
                   8763:  #changing a value
                   8764:  $hash{'foo'}='notbar';
                   8765: 
                   8766:  #adding a new value
                   8767:  $hash{'bar'}='foo';
                   8768:  &Apache::lonnet::cstore(\%hash);
                   8769: 
                   8770:  #retrieving the hash
                   8771:  my %history=&Apache::lonnet::restore();
                   8772: 
                   8773:  #print the hash
                   8774:  foreach my $key (sort(keys(%history))) {
                   8775:    print("\%history{$key} = $history{$key}");
                   8776:  }
                   8777: 
                   8778: Will print out:
1.191     harris41 8779: 
1.394     bowersj2 8780:  %history{1:foo} = bar
                   8781:  %history{1:keys} = foo:timestamp
                   8782:  %history{1:timestamp} = 990455579
                   8783:  %history{2:bar} = foo
                   8784:  %history{2:foo} = notbar
                   8785:  %history{2:keys} = foo:bar:timestamp
                   8786:  %history{2:timestamp} = 990455580
                   8787:  %history{bar} = foo
                   8788:  %history{foo} = notbar
                   8789:  %history{timestamp} = 990455580
                   8790:  %history{version} = 2
                   8791: 
                   8792: Note that the special hash entries C<keys>, C<version> and
                   8793: C<timestamp> were added to the hash. C<version> will be equal to the
                   8794: total number of versions of the data that have been stored. The
                   8795: C<timestamp> attribute will be the UNIX time the hash was
                   8796: stored. C<keys> is available in every historical section to list which
                   8797: keys were added or changed at a specific historical revision of a
                   8798: hash.
                   8799: 
                   8800: B<Warning>: do not store the hash that restore returns directly. This
                   8801: will cause a mess since it will restore the historical keys as if the
                   8802: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 8803: 
1.394     bowersj2 8804: Calling convention:
1.191     harris41 8805: 
1.394     bowersj2 8806:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   8807:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 8808: 
1.394     bowersj2 8809: For more detailed information, see lonnet specific documentation.
1.191     harris41 8810: 
1.394     bowersj2 8811: =head1 RETURN MESSAGES
1.191     harris41 8812: 
1.394     bowersj2 8813: =over 4
1.191     harris41 8814: 
1.394     bowersj2 8815: =item * B<con_lost>: unable to contact remote host
1.191     harris41 8816: 
1.394     bowersj2 8817: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   8818: when the connection is brought back up
1.191     harris41 8819: 
1.394     bowersj2 8820: =item * B<con_failed>: unable to contact remote host and unable to save message
                   8821: for later delivery
1.191     harris41 8822: 
1.394     bowersj2 8823: =item * B<error:>: an error a occured, a description of the error follows the :
1.191     harris41 8824: 
1.394     bowersj2 8825: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 8826: that was requested
1.191     harris41 8827: 
1.243     albertel 8828: =back
1.191     harris41 8829: 
1.243     albertel 8830: =head1 PUBLIC SUBROUTINES
1.191     harris41 8831: 
1.243     albertel 8832: =head2 Session Environment Functions
1.191     harris41 8833: 
1.243     albertel 8834: =over 4
1.191     harris41 8835: 
1.394     bowersj2 8836: =item * 
                   8837: X<appenv()>
                   8838: B<appenv(%hash)>: the value of %hash is written to
                   8839: the user envirnoment file, and will be restored for each access this
1.620     albertel 8840: user makes during this session, also modifies the %env for the current
1.394     bowersj2 8841: process
1.191     harris41 8842: 
                   8843: =item *
1.394     bowersj2 8844: X<delenv()>
                   8845: B<delenv($regexp)>: removes all items from the session
                   8846: environment file that matches the regular expression in $regexp. The
1.620     albertel 8847: values are also delted from the current processes %env.
1.191     harris41 8848: 
1.795     albertel 8849: =item * get_env_multiple($name) 
                   8850: 
                   8851: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   8852: values may be defined and end up as an array ref.
                   8853: 
                   8854: returns an array of values
                   8855: 
1.243     albertel 8856: =back
                   8857: 
                   8858: =head2 User Information
1.191     harris41 8859: 
1.243     albertel 8860: =over 4
1.191     harris41 8861: 
                   8862: =item *
1.394     bowersj2 8863: X<queryauthenticate()>
                   8864: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 8865: authentication scheme
                   8866: 
                   8867: =item *
1.394     bowersj2 8868: X<authenticate()>
                   8869: B<authenticate($uname,$upass,$udom)>: try to
                   8870: authenticate user from domain's lib servers (first use the current
                   8871: one). C<$upass> should be the users password.
1.191     harris41 8872: 
                   8873: =item *
1.394     bowersj2 8874: X<homeserver()>
                   8875: B<homeserver($uname,$udom)>: find the server which has
                   8876: the user's directory and files (there must be only one), this caches
                   8877: the answer, and also caches if there is a borken connection.
1.191     harris41 8878: 
                   8879: =item *
1.394     bowersj2 8880: X<idget()>
                   8881: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   8882: (IDs are a unique resource in a domain, there must be only 1 ID per
                   8883: username, and only 1 username per ID in a specific domain) (returns
                   8884: hash: id=>name,id=>name)
1.191     harris41 8885: 
                   8886: =item *
1.394     bowersj2 8887: X<idrget()>
                   8888: B<idrget($udom,@unames)>: find the IDs behind a list of
                   8889: usernames (returns hash: name=>id,name=>id)
1.191     harris41 8890: 
                   8891: =item *
1.394     bowersj2 8892: X<idput()>
                   8893: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 8894: 
                   8895: =item *
1.394     bowersj2 8896: X<rolesinit()>
                   8897: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 8898: 
                   8899: =item *
1.551     albertel 8900: X<getsection()>
                   8901: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 8902: course $cname, return section name/number or '' for "not in course"
                   8903: and '-1' for "no section"
                   8904: 
                   8905: =item *
1.394     bowersj2 8906: X<userenvironment()>
                   8907: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 8908: passed in @what from the requested user's environment, returns a hash
                   8909: 
1.858     raeburn  8910: =item * 
                   8911: X<userlog_query()>
1.859     albertel 8912: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   8913: activity.log file. %filters defines filters applied when parsing the
                   8914: log file. These can be start or end timestamps, or the type of action
                   8915: - log to look for Login or Logout events, check for Checkin or
                   8916: Checkout, role for role selection. The response is in the form
                   8917: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   8918: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  8919: 
1.243     albertel 8920: =back
                   8921: 
                   8922: =head2 User Roles
                   8923: 
                   8924: =over 4
                   8925: 
                   8926: =item *
                   8927: 
1.810     raeburn  8928: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 8929:  F: full access
                   8930:  U,I,K: authentication modes (cxx only)
                   8931:  '': forbidden
                   8932:  1: user needs to choose course
                   8933:  2: browse allowed
1.766     albertel 8934:  A: passphrase authentication needed
1.243     albertel 8935: 
                   8936: =item *
                   8937: 
                   8938: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   8939: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   8940: and course level
                   8941: 
                   8942: =item *
                   8943: 
                   8944: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   8945: explanation of a user role term
                   8946: 
1.832     raeburn  8947: =item *
                   8948: 
1.935     raeburn  8949: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  8950: All arguments are optional. Returns a hash of a roles, either for
                   8951: co-author/assistant author roles for a user's Construction Space
1.906     albertel 8952: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  8953: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   8954: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   8955: For each key, value is set to colon-separated start and end times for
                   8956: the role.  If no username and domain are specified, will default to
1.934     raeburn  8957: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  8958: of role statuses (active, future or previous), roles 
                   8959: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   8960: to restrict the list of roles reported. If no array ref is 
                   8961: provided for types, will default to return only active roles.
1.834     albertel 8962: 
1.243     albertel 8963: =back
                   8964: 
                   8965: =head2 User Modification
                   8966: 
                   8967: =over 4
                   8968: 
                   8969: =item *
                   8970: 
                   8971: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
                   8972: user for the level given by URL.  Optional start and end dates (leave empty
                   8973: string or zero for "no date")
1.191     harris41 8974: 
                   8975: =item *
                   8976: 
1.243     albertel 8977: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   8978: change a users, password, possible return values are: ok,
                   8979: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   8980: refused
1.191     harris41 8981: 
                   8982: =item *
                   8983: 
1.243     albertel 8984: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 8985: 
                   8986: =item *
                   8987: 
1.243     albertel 8988: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
                   8989: modify user
1.191     harris41 8990: 
                   8991: =item *
                   8992: 
1.286     matthew  8993: modifystudent
                   8994: 
                   8995: modify a students enrollment and identification information.
                   8996: The course id is resolved based on the current users environment.  
                   8997: This means the envoking user must be a course coordinator or otherwise
                   8998: associated with a course.
                   8999: 
1.297     matthew  9000: This call is essentially a wrapper for lonnet::modifyuser and
                   9001: lonnet::modify_student_enrollment
1.286     matthew  9002: 
                   9003: Inputs: 
                   9004: 
                   9005: =over 4
                   9006: 
                   9007: =item B<$udom> Students loncapa domain
                   9008: 
                   9009: =item B<$uname> Students loncapa login name
                   9010: 
                   9011: =item B<$uid> Students id/student number
                   9012: 
                   9013: =item B<$umode> Students authentication mode
                   9014: 
                   9015: =item B<$upass> Students password
                   9016: 
                   9017: =item B<$first> Students first name
                   9018: 
                   9019: =item B<$middle> Students middle name
                   9020: 
                   9021: =item B<$last> Students last name
                   9022: 
                   9023: =item B<$gene> Students generation
                   9024: 
                   9025: =item B<$usec> Students section in course
                   9026: 
                   9027: =item B<$end> Unix time of the roles expiration
                   9028: 
                   9029: =item B<$start> Unix time of the roles start date
                   9030: 
                   9031: =item B<$forceid> If defined, allow $uid to be changed
                   9032: 
                   9033: =item B<$desiredhome> server to use as home server for student
                   9034: 
                   9035: =back
1.297     matthew  9036: 
                   9037: =item *
                   9038: 
                   9039: modify_student_enrollment
                   9040: 
                   9041: Change a students enrollment status in a class.  The environment variable
                   9042: 'role.request.course' must be defined for this function to proceed.
                   9043: 
                   9044: Inputs:
                   9045: 
                   9046: =over 4
                   9047: 
                   9048: =item $udom, students domain
                   9049: 
                   9050: =item $uname, students name
                   9051: 
                   9052: =item $uid, students user id
                   9053: 
                   9054: =item $first, students first name
                   9055: 
                   9056: =item $middle
                   9057: 
                   9058: =item $last
                   9059: 
                   9060: =item $gene
                   9061: 
                   9062: =item $usec
                   9063: 
                   9064: =item $end
                   9065: 
                   9066: =item $start
                   9067: 
                   9068: =back
                   9069: 
1.191     harris41 9070: 
                   9071: =item *
                   9072: 
1.243     albertel 9073: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   9074: custom role; give a custom role to a user for the level given by URL.  Specify
                   9075: name and domain of role author, and role name
1.191     harris41 9076: 
                   9077: =item *
                   9078: 
1.243     albertel 9079: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 9080: 
                   9081: =item *
                   9082: 
1.243     albertel 9083: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   9084: 
                   9085: =back
                   9086: 
                   9087: =head2 Course Infomation
                   9088: 
                   9089: =over 4
1.191     harris41 9090: 
                   9091: =item *
                   9092: 
1.631     albertel 9093: coursedescription($courseid) : returns a hash of information about the
                   9094: specified course id, including all environment settings for the
                   9095: course, the description of the course will be in the hash under the
                   9096: key 'description'
1.191     harris41 9097: 
                   9098: =item *
                   9099: 
1.624     albertel 9100: resdata($name,$domain,$type,@which) : request for current parameter
                   9101: setting for a specific $type, where $type is either 'course' or 'user',
                   9102: @what should be a list of parameters to ask about. This routine caches
                   9103: answers for 5 minutes.
1.243     albertel 9104: 
1.877     foxr     9105: =item *
                   9106: 
                   9107: get_courseresdata($courseid, $domain) : dump the entire course resource
                   9108: data base, returning a hash that is keyed by the resource name and has
                   9109: values that are the resource value.  I believe that the timestamps and
                   9110: versions are also returned.
                   9111: 
                   9112: 
1.243     albertel 9113: =back
                   9114: 
                   9115: =head2 Course Modification
                   9116: 
                   9117: =over 4
1.191     harris41 9118: 
                   9119: =item *
                   9120: 
1.243     albertel 9121: writecoursepref($courseid,%prefs) : write preferences (environment
                   9122: database) for a course
1.191     harris41 9123: 
                   9124: =item *
                   9125: 
1.243     albertel 9126: createcourse($udom,$description,$url) : make/modify course
                   9127: 
                   9128: =back
                   9129: 
                   9130: =head2 Resource Subroutines
                   9131: 
                   9132: =over 4
1.191     harris41 9133: 
                   9134: =item *
                   9135: 
1.243     albertel 9136: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 9137: 
                   9138: =item *
                   9139: 
1.243     albertel 9140: repcopy($filename) : subscribes to the requested file, and attempts to
                   9141: replicate from the owning library server, Might return
1.607     raeburn  9142: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   9143: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 9144: resource. Expects the local filesystem pathname
                   9145: (/home/httpd/html/res/....)
                   9146: 
                   9147: =back
                   9148: 
                   9149: =head2 Resource Information
                   9150: 
                   9151: =over 4
1.191     harris41 9152: 
                   9153: =item *
                   9154: 
1.243     albertel 9155: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   9156: a vairety of different possible values, $varname should be a request
                   9157: string, and the other parameters can be used to specify who and what
                   9158: one is asking about.
                   9159: 
                   9160: Possible values for $varname are environment.lastname (or other item
                   9161: from the envirnment hash), user.name (or someother aspect about the
                   9162: user), resource.0.maxtries (or some other part and parameter of a
                   9163: resource)
1.204     albertel 9164: 
                   9165: =item *
                   9166: 
1.243     albertel 9167: directcondval($number) : get current value of a condition; reads from a state
                   9168: string
1.204     albertel 9169: 
                   9170: =item *
                   9171: 
1.243     albertel 9172: condval($condidx) : value of condition index based on state
1.204     albertel 9173: 
                   9174: =item *
                   9175: 
1.243     albertel 9176: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   9177: resource's metadata, $what should be either a specific key, or either
                   9178: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   9179: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   9180: 
                   9181: this function automatically caches all requests
1.191     harris41 9182: 
                   9183: =item *
                   9184: 
1.243     albertel 9185: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   9186: network of library servers; returns file handle of where SQL and regex results
                   9187: will be stored for query
1.191     harris41 9188: 
                   9189: =item *
                   9190: 
1.243     albertel 9191: symbread($filename) : return symbolic list entry (filename argument optional);
                   9192: returns the data handle
1.191     harris41 9193: 
                   9194: =item *
                   9195: 
1.243     albertel 9196: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 9197: a possible symb for the URL in $thisfn, and if is an encryypted
                   9198: resource that the user accessed using /enc/ returns a 1 on success, 0
                   9199: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 9200: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 9201: 
1.191     harris41 9202: 
                   9203: =item *
                   9204: 
1.243     albertel 9205: symbclean($symb) : removes versions numbers from a symb, returns the
                   9206: cleaned symb
1.191     harris41 9207: 
                   9208: =item *
                   9209: 
1.243     albertel 9210: is_on_map($uri) : checks if the $uri is somewhere on the current
                   9211: course map, user must be in a course for it to work.
1.191     harris41 9212: 
                   9213: =item *
                   9214: 
1.243     albertel 9215: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 9216: 
                   9217: =item *
                   9218: 
1.243     albertel 9219: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   9220: a random seed, all arguments are optional, if they aren't sent it uses the
                   9221: environment to derive them. Note: if symb isn't sent and it can't get one
                   9222: from &symbread it will use the current time as its return value
1.191     harris41 9223: 
                   9224: =item *
                   9225: 
1.243     albertel 9226: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   9227: unfakeable, receipt
1.191     harris41 9228: 
                   9229: =item *
                   9230: 
1.620     albertel 9231: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 9232: 
                   9233: =item *
                   9234: 
1.243     albertel 9235: countacc($url) : count the number of accesses to a given URL
1.191     harris41 9236: 
                   9237: =item *
                   9238: 
1.243     albertel 9239: 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 9240: 
                   9241: =item *
                   9242: 
1.243     albertel 9243: 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 9244: 
                   9245: =item *
                   9246: 
1.243     albertel 9247: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 9248: 
                   9249: =item *
                   9250: 
1.243     albertel 9251: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   9252: forcing spreadsheet to reevaluate the resource scores next time.
                   9253: 
                   9254: =back
                   9255: 
                   9256: =head2 Storing/Retreiving Data
                   9257: 
                   9258: =over 4
1.191     harris41 9259: 
                   9260: =item *
                   9261: 
1.243     albertel 9262: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   9263: for this url; hashref needs to be given and should be a \%hashname; the
                   9264: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 9265: be derived from the env
1.191     harris41 9266: 
                   9267: =item *
                   9268: 
1.243     albertel 9269: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   9270: uses critical subroutine
1.191     harris41 9271: 
                   9272: =item *
                   9273: 
1.243     albertel 9274: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   9275: all args are optional
1.191     harris41 9276: 
                   9277: =item *
                   9278: 
1.717     albertel 9279: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   9280: dumps the complete (or key matching regexp) namespace into a hash
                   9281: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   9282: normally &store()ed into
                   9283: 
                   9284: $range should be either an integer '100' (give me the first 100
                   9285:                                            matching records)
                   9286:               or be  two integers sperated by a - with no spaces
                   9287:                  '30-50' (give me the 30th through the 50th matching
                   9288:                           records)
                   9289: 
                   9290: 
                   9291: =item *
                   9292: 
                   9293: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   9294: replaces a &store() version of data with a replacement set of data
                   9295: for a particular resource in a namespace passed in the $storehash hash 
                   9296: reference
                   9297: 
                   9298: =item *
                   9299: 
1.243     albertel 9300: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   9301: works very similar to store/cstore, but all data is stored in a
                   9302: temporary location and can be reset using tmpreset, $storehash should
                   9303: be a hash reference, returns nothing on success
1.191     harris41 9304: 
                   9305: =item *
                   9306: 
1.243     albertel 9307: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   9308: similar to restore, but all data is stored in a temporary location and
                   9309: can be reset using tmpreset. Returns a hash of values on success,
                   9310: error string otherwise.
1.191     harris41 9311: 
                   9312: =item *
                   9313: 
1.243     albertel 9314: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   9315: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 9316: 
                   9317: =item *
                   9318: 
1.243     albertel 9319: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   9320: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 9321: 
                   9322: =item *
                   9323: 
1.243     albertel 9324: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   9325: namesp ($udom and $uname are optional)
1.191     harris41 9326: 
                   9327: =item *
                   9328: 
1.702     albertel 9329: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 9330: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 9331: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  9332: 
1.702     albertel 9333: $range should be either an integer '100' (give me the first 100
                   9334:                                            matching records)
                   9335:               or be  two integers sperated by a - with no spaces
                   9336:                  '30-50' (give me the 30th through the 50th matching
                   9337:                           records)
1.449     matthew  9338: =item *
                   9339: 
                   9340: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   9341: $store can be a scalar, an array reference, or if the amount to be 
                   9342: incremented is > 1, a hash reference.
                   9343: 
                   9344: ($udom and $uname are optional)
1.191     harris41 9345: 
                   9346: =item *
                   9347: 
1.243     albertel 9348: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   9349: ($udom and $uname are optional)
1.191     harris41 9350: 
                   9351: =item *
                   9352: 
1.243     albertel 9353: cput($namespace,$storehash,$udom,$uname) : critical put
                   9354: ($udom and $uname are optional)
1.191     harris41 9355: 
                   9356: =item *
                   9357: 
1.748     albertel 9358: newput($namespace,$storehash,$udom,$uname) :
                   9359: 
                   9360: Attempts to store the items in the $storehash, but only if they don't
                   9361: currently exist, if this succeeds you can be certain that you have 
                   9362: successfully created a new key value pair in the $namespace db.
                   9363: 
                   9364: 
                   9365: Args:
                   9366:  $namespace: name of database to store values to
                   9367:  $storehash: hashref to store to the db
                   9368:  $udom: (optional) domain of user containing the db
                   9369:  $uname: (optional) name of user caontaining the db
                   9370: 
                   9371: Returns:
                   9372:  'ok' -> succeeded in storing all keys of $storehash
                   9373:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   9374:                         least <key> already existed in the db (other
                   9375:                         requested keys may also already exist)
                   9376:  'error: <msg>' -> unable to tie the DB or other erorr occured
                   9377:  'con_lost' -> unable to contact request server
                   9378:  'refused' -> action was not allowed by remote machine
                   9379: 
                   9380: 
                   9381: =item *
                   9382: 
1.243     albertel 9383: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   9384: reference filled in from namesp (encrypts the return communication)
                   9385: ($udom and $uname are optional)
1.191     harris41 9386: 
                   9387: =item *
                   9388: 
1.243     albertel 9389: log($udom,$name,$home,$message) : write to permanent log for user; use
                   9390: critical subroutine
                   9391: 
1.806     raeburn  9392: =item *
                   9393: 
1.860     raeburn  9394: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   9395: array reference filled in from namespace found in domain level on either
                   9396: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  9397: 
                   9398: =item *
                   9399: 
1.860     raeburn  9400: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   9401: domain level either on specified domain server ($uhome) or primary domain 
                   9402: server ($udom and $uhome are optional)
1.806     raeburn  9403: 
1.943     raeburn  9404: =item * 
                   9405: 
                   9406: get_domain_defaults($target_domain) : returns hash with defaults for
                   9407: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   9408: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   9409: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   9410: Values are retrieved from cache (if current), or from domain's configuration.db
                   9411: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   9412: or lonTabs/domain.tab. 
                   9413: 
                   9414: %domdefaults = &get_auth_defaults($target_domain);
                   9415: 
1.243     albertel 9416: =back
                   9417: 
                   9418: =head2 Network Status Functions
                   9419: 
                   9420: =over 4
1.191     harris41 9421: 
                   9422: =item *
                   9423: 
                   9424: dirlist($uri) : return directory list based on URI
                   9425: 
                   9426: =item *
                   9427: 
1.243     albertel 9428: spareserver() : find server with least workload from spare.tab
                   9429: 
                   9430: =back
                   9431: 
                   9432: =head2 Apache Request
                   9433: 
                   9434: =over 4
1.191     harris41 9435: 
                   9436: =item *
                   9437: 
1.243     albertel 9438: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   9439: localhost, posts hash
                   9440: 
                   9441: =back
                   9442: 
                   9443: =head2 Data to String to Data
                   9444: 
                   9445: =over 4
1.191     harris41 9446: 
                   9447: =item *
                   9448: 
1.243     albertel 9449: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   9450: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 9451: 
                   9452: =item *
                   9453: 
1.243     albertel 9454: hashref2str($hashref) : convert a hashref into a string complete with
                   9455: escaping and '=' and '&' separators, supports elements that are
                   9456: arrayrefs and hashrefs
1.191     harris41 9457: 
                   9458: =item *
                   9459: 
1.243     albertel 9460: arrayref2str($arrayref) : convert an arrayref into a string complete
                   9461: with escaping and '&' separators, supports elements that are arrayrefs
                   9462: and hashrefs
1.191     harris41 9463: 
                   9464: =item *
                   9465: 
1.243     albertel 9466: str2hash($string) : convert string to hash using unescaping and
                   9467: splitting on '=' and '&', supports elements that are arrayrefs and
                   9468: hashrefs
1.191     harris41 9469: 
                   9470: =item *
                   9471: 
1.243     albertel 9472: str2array($string) : convert string to hash using unescaping and
                   9473: splitting on '&', supports elements that are arrayrefs and hashrefs
                   9474: 
                   9475: =back
                   9476: 
                   9477: =head2 Logging Routines
                   9478: 
                   9479: =over 4
                   9480: 
                   9481: These routines allow one to make log messages in the lonnet.log and
                   9482: lonnet.perm logfiles.
1.191     harris41 9483: 
                   9484: =item *
                   9485: 
1.243     albertel 9486: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 9487: 
                   9488: =item *
                   9489: 
1.243     albertel 9490: logthis() : append message to the normal lonnet.log file, it gets
                   9491: preiodically rolled over and deleted.
1.191     harris41 9492: 
                   9493: =item *
                   9494: 
1.243     albertel 9495: logperm() : append a permanent message to lonnet.perm.log, this log
                   9496: file never gets deleted by any automated portion of the system, only
                   9497: messages of critical importance should go in here.
                   9498: 
                   9499: =back
                   9500: 
                   9501: =head2 General File Helper Routines
                   9502: 
                   9503: =over 4
1.191     harris41 9504: 
                   9505: =item *
                   9506: 
1.481     raeburn  9507: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   9508: (a) files in /uploaded
                   9509:   (i) If a local copy of the file exists - 
                   9510:       compares modification date of local copy with last-modified date for 
                   9511:       definitive version stored on home server for course. If local copy is 
                   9512:       stale, requests a new version from the home server and stores it. 
                   9513:       If the original has been removed from the home server, then local copy 
                   9514:       is unlinked.
                   9515:   (ii) If local copy does not exist -
                   9516:       requests the file from the home server and stores it. 
                   9517:   
                   9518:   If $caller is 'uploadrep':  
                   9519:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   9520:     for request for files originally uploaded via DOCS. 
                   9521:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   9522:   
                   9523:   Otherwise:
                   9524:      This indicates a call from the content generation phase of the request.
                   9525:      -  returns the entire contents of the file or -1.
                   9526:      
                   9527: (b) files in /res
                   9528:    - returns the entire contents of a file or -1; 
                   9529:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 9530: 
1.712     albertel 9531: 
                   9532: =item *
                   9533: 
                   9534: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   9535:                   reference
                   9536: 
                   9537: returns either a stat() list of data about the file or an empty list
                   9538: if the file doesn't exist or couldn't find out about it (connection
                   9539: problems or user unknown)
                   9540: 
1.191     harris41 9541: =item *
                   9542: 
1.243     albertel 9543: filelocation($dir,$file) : returns file system location of a file
                   9544: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   9545: directory that relative $file lookups are to looked in ($dir of /a/dir
                   9546: and a file of ../bob will become /a/bob)
1.191     harris41 9547: 
                   9548: =item *
                   9549: 
                   9550: hreflocation($dir,$file) : returns file system location or a URL; same as
                   9551: filelocation except for hrefs
                   9552: 
                   9553: =item *
                   9554: 
                   9555: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   9556: 
1.243     albertel 9557: =back
                   9558: 
1.608     albertel 9559: =head2 Usererfile file routines (/uploaded*)
                   9560: 
                   9561: =over 4
                   9562: 
                   9563: =item *
                   9564: 
                   9565: userfileupload(): main rotine for putting a file in a user or course's
                   9566:                   filespace, arguments are,
                   9567: 
1.620     albertel 9568:  formname - required - this is the name of the element in $env where the
1.608     albertel 9569:            filename, and the contents of the file to create/modifed exist
1.620     albertel 9570:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   9571:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 9572:  coursedoc - if true, store the file in the course of the active role
                   9573:              of the current user
                   9574:  subdir - required - subdirectory to put the file in under ../userfiles/
                   9575:          if undefined, it will be placed in "unknown"
                   9576: 
                   9577:  (This routine calls clean_filename() to remove any dangerous
                   9578:  characters from the filename, and then calls finuserfileupload() to
                   9579:  complete the transaction)
                   9580: 
                   9581:  returns either the url of the uploaded file (/uploaded/....) if successful
                   9582:  and /adm/notfound.html if unsuccessful
                   9583: 
                   9584: =item *
                   9585: 
                   9586: clean_filename(): routine for cleaing a filename up for storage in
                   9587:                  userfile space, argument is:
                   9588: 
                   9589:  filename - proposed filename
                   9590: 
                   9591: returns: the new clean filename
                   9592: 
                   9593: =item *
                   9594: 
                   9595: finishuserfileupload(): routine that creaes and sends the file to
                   9596: userspace, probably shouldn't be called directly
                   9597: 
                   9598:   docuname: username or courseid of destination for the file
                   9599:   docudom: domain of user/course of destination for the file
                   9600:   formname: same as for userfileupload()
                   9601:   fname: filename (inculding subdirectories) for the file
                   9602: 
                   9603:  returns either the url of the uploaded file (/uploaded/....) if successful
                   9604:  and /adm/notfound.html if unsuccessful
                   9605: 
                   9606: =item *
                   9607: 
                   9608: renameuserfile(): renames an existing userfile to a new name
                   9609: 
                   9610:   Args:
                   9611:    docuname: username or courseid of destination for the file
                   9612:    docudom: domain of user/course of destination for the file
                   9613:    old: current file name (including any subdirs under userfiles)
                   9614:    new: desired file name (including any subdirs under userfiles)
                   9615: 
                   9616: =item *
                   9617: 
                   9618: mkdiruserfile(): creates a directory is a userfiles dir
                   9619: 
                   9620:   Args:
                   9621:    docuname: username or courseid of destination for the file
                   9622:    docudom: domain of user/course of destination for the file
                   9623:    dir: dir to create (including any subdirs under userfiles)
                   9624: 
                   9625: =item *
                   9626: 
                   9627: removeuserfile(): removes a file that exists in userfiles
                   9628: 
                   9629:   Args:
                   9630:    docuname: username or courseid of destination for the file
                   9631:    docudom: domain of user/course of destination for the file
                   9632:    fname: filname to delete (including any subdirs under userfiles)
                   9633: 
                   9634: =item *
                   9635: 
                   9636: removeuploadedurl(): convience function for removeuserfile()
                   9637: 
                   9638:   Args:
                   9639:    url:  a full /uploaded/... url to delete
                   9640: 
1.747     albertel 9641: =item * 
                   9642: 
                   9643: get_portfile_permissions():
                   9644:   Args:
                   9645:     domain: domain of user or course contain the portfolio files
                   9646:     user: name of user or num of course contain the portfolio files
                   9647:   Returns:
                   9648:     hashref of a dump of the proper file_permissions.db
                   9649:    
                   9650: 
                   9651: =item * 
                   9652: 
                   9653: get_access_controls():
                   9654: 
                   9655: Args:
                   9656:   current_permissions: the hash ref returned from get_portfile_permissions()
                   9657:   group: (optional) the group you want the files associated with
                   9658:   file: (optional) the file you want access info on
                   9659: 
                   9660: Returns:
1.749     raeburn  9661:     a hash (keys are file names) of hashes containing
                   9662:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   9663:         values are XML containing access control settings (see below) 
1.747     albertel 9664: 
                   9665: Internal notes:
                   9666: 
1.749     raeburn  9667:  access controls are stored in file_permissions.db as key=value pairs.
                   9668:     key -> path to file/file_name\0uniqueID:scope_end_start
                   9669:         where scope -> public,guest,course,group,domains or users.
                   9670:               end -> UNIX time for end of access (0 -> no end date)
                   9671:               start -> UNIX time for start of access
                   9672: 
                   9673:     value -> XML description of access control
                   9674:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   9675:             <start></start>
                   9676:             <end></end>
                   9677: 
                   9678:             <password></password>  for scope type = guest
                   9679: 
                   9680:             <domain></domain>     for scope type = course or group
                   9681:             <number></number>
                   9682:             <roles id="">
                   9683:              <role></role>
                   9684:              <access></access>
                   9685:              <section></section>
                   9686:              <group></group>
                   9687:             </roles>
                   9688: 
                   9689:             <dom></dom>         for scope type = domains
                   9690: 
                   9691:             <users>             for scope type = users
                   9692:              <user>
                   9693:               <uname></uname>
                   9694:               <udom></udom>
                   9695:              </user>
                   9696:             </users>
                   9697:            </scope> 
                   9698:               
                   9699:  Access data is also aggregated for each file in an additional key=value pair:
                   9700:  key -> path to file/file_name\0accesscontrol 
                   9701:  value -> reference to hash
                   9702:           hash contains key = value pairs
                   9703:           where key = uniqueID:scope_end_start
                   9704:                 value = UNIX time record was last updated
                   9705: 
                   9706:           Used to improve speed of look-ups of access controls for each file.  
                   9707:  
                   9708:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   9709: 
                   9710: modify_access_controls():
                   9711: 
                   9712: Modifies access controls for a portfolio file
                   9713: Args
                   9714: 1. file name
                   9715: 2. reference to hash of required changes,
                   9716: 3. domain
                   9717: 4. username
                   9718:   where domain,username are the domain of the portfolio owner 
                   9719:   (either a user or a course) 
                   9720: 
                   9721: Returns:
                   9722: 1. result of additions or updates ('ok' or 'error', with error message). 
                   9723: 2. result of deletions ('ok' or 'error', with error message).
                   9724: 3. reference to hash of any new or updated access controls.
                   9725: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   9726:    key = integer (inbound ID)
                   9727:    value = uniqueID  
1.747     albertel 9728: 
1.608     albertel 9729: =back
                   9730: 
1.243     albertel 9731: =head2 HTTP Helper Routines
                   9732: 
                   9733: =over 4
                   9734: 
1.191     harris41 9735: =item *
                   9736: 
                   9737: escape() : unpack non-word characters into CGI-compatible hex codes
                   9738: 
                   9739: =item *
                   9740: 
                   9741: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   9742: 
1.243     albertel 9743: =back
                   9744: 
                   9745: =head1 PRIVATE SUBROUTINES
                   9746: 
                   9747: =head2 Underlying communication routines (Shouldn't call)
                   9748: 
                   9749: =over 4
                   9750: 
                   9751: =item *
                   9752: 
                   9753: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   9754: 
                   9755: =item *
                   9756: 
                   9757: reply() : uses subreply to send a message to remote machine, logs all failures
                   9758: 
                   9759: =item *
                   9760: 
                   9761: critical() : passes a critical message to another server; if cannot
                   9762: get through then place message in connection buffer directory and
                   9763: returns con_delayed, if incapable of saving message, returns
                   9764: con_failed
                   9765: 
                   9766: =item *
                   9767: 
                   9768: reconlonc() : tries to reconnect lonc client processes.
                   9769: 
                   9770: =back
                   9771: 
                   9772: =head2 Resource Access Logging
                   9773: 
                   9774: =over 4
                   9775: 
                   9776: =item *
                   9777: 
                   9778: flushcourselogs() : flush (save) buffer logs and access logs
                   9779: 
                   9780: =item *
                   9781: 
                   9782: courselog($what) : save message for course in hash
                   9783: 
                   9784: =item *
                   9785: 
                   9786: courseacclog($what) : save message for course using &courselog().  Perform
                   9787: special processing for specific resource types (problems, exams, quizzes, etc).
                   9788: 
1.191     harris41 9789: =item *
                   9790: 
                   9791: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   9792: as a PerlChildExitHandler
1.243     albertel 9793: 
                   9794: =back
                   9795: 
                   9796: =head2 Other
                   9797: 
                   9798: =over 4
                   9799: 
                   9800: =item *
                   9801: 
                   9802: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 9803: 
                   9804: =back
                   9805: 
                   9806: =cut
1.877     foxr     9807: 

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